Security & Compliance Expert Core Principles 1. Defense in Depth Apply multiple layers of security controls so that if one fails, others provide protection. Never rely on a single security mechanism. 2. Zero Trust Architecture Never trust, always verify. Assume breach and verify every access request regardless of location or network. 3. Least Privilege Grant the minimum access necessary for users and systems to perform their functions. Regularly review and revoke unused permissions. 4. Security by Design Integrate security requirements from the earliest stages of system design, not as an afte…

, host):\n return \"Invalid host\", 400\n\n # Use array format (no shell interpretation)\n try:\n result = subprocess.run(['ping', '-c', '1', host],\n capture_output=True,\n timeout=5,\n check=False)\n return result.stdout.decode()\n except subprocess.TimeoutExpired:\n return \"Timeout\", 408\n```\n\n**Mitigation**:\n- Use parameterized queries (prepared statements)\n- Use ORM frameworks\n- Input validation (allowlist preferred over blocklist)\n- Escape special characters\n- Use language-specific APIs instead of shell commands\n\n---\n\n### A04:2021 - Insecure Design\n\n**Description**: Missing or ineffective security design patterns.\n\n**Examples**:\n- No rate limiting on authentication (allows brute force)\n- No defense against automated attacks (bots)\n- Insufficient logging for security events\n\n**Mitigation**:\n- Threat modeling during design phase\n- Secure design patterns (rate limiting, circuit breakers)\n- Defense in depth\n- Separation of duties\n\n---\n\n### A05:2021 - Security Misconfiguration\n\n**Description**: Improperly configured security settings.\n\n**Examples**:\n- Default credentials not changed\n- Unnecessary features enabled (directory listing, debug mode)\n- Error messages revealing stack traces\n- Missing security headers\n\n**Secure Configuration Example**:\n\n```python\n# Flask example with security headers\nfrom flask import Flask\nfrom flask_talisman import Talisman\n\napp = Flask(__name__)\n\n# Enforce HTTPS and security headers\nTalisman(app,\n force_https=True,\n strict_transport_security=True,\n content_security_policy={\n 'default-src': \"'self'\",\n 'script-src': \"'self' 'unsafe-inline'\",\n 'style-src': \"'self' 'unsafe-inline'\"\n },\n content_security_policy_nonce_in=['script-src'],\n referrer_policy='strict-origin-when-cross-origin',\n feature_policy={\n 'geolocation': \"'none'\",\n 'camera': \"'none'\",\n 'microphone': \"'none'\"\n }\n)\n\n# Disable debug mode in production\napp.config['DEBUG'] = False\n\n# Custom error handlers (don't reveal stack traces)\[email protected](500)\ndef internal_error(error):\n # Log error details server-side\n app.logger.error(f'Server Error: {error}')\n # Return generic message to user\n return \"Internal server error\", 500\n```\n\n**Nginx Security Headers**:\n\n```nginx\n# Security headers\nadd_header Strict-Transport-Security \"max-age=31536000; includeSubDomains; preload\" always;\nadd_header X-Frame-Options \"DENY\" always;\nadd_header X-Content-Type-Options \"nosniff\" always;\nadd_header X-XSS-Protection \"1; mode=block\" always;\nadd_header Referrer-Policy \"strict-origin-when-cross-origin\" always;\nadd_header Content-Security-Policy \"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';\" always;\n\n# Disable server version disclosure\nserver_tokens off;\n```\n\n---\n\n### A06:2021 - Vulnerable and Outdated Components\n\n**Description**: Using components with known vulnerabilities.\n\n**Examples**:\n- Outdated libraries with known CVEs\n- Unsupported software versions\n- Not scanning dependencies for vulnerabilities\n\n**Mitigation**:\n- Inventory all dependencies\n- Monitor for CVEs (use Snyk, Dependabot, Renovate)\n- Update dependencies regularly\n- Remove unused dependencies\n\n**Example: package.json with automated scanning**:\n\n```json\n{\n \"name\": \"secure-app\",\n \"scripts\": {\n \"audit\": \"npm audit\",\n \"audit:fix\": \"npm audit fix\"\n },\n \"dependencies\": {\n \"express\": \"^4.18.2\",\n \"helmet\": \"^7.0.0\"\n }\n}\n```\n\n**GitHub Dependabot configuration** (`.github/dependabot.yml`):\n\n```yaml\nversion: 2\nupdates:\n - package-ecosystem: \"npm\"\n directory: \"/\"\n schedule:\n interval: \"weekly\"\n open-pull-requests-limit: 10\n reviewers:\n - \"security-team\"\n labels:\n - \"dependencies\"\n - \"security\"\n```\n\n---\n\n### A07:2021 - Identification and Authentication Failures\n\n**Description**: Weaknesses in authentication and session management.\n\n**Examples**:\n- Weak password requirements\n- No brute force protection\n- Session fixation\n- Insecure session tokens\n\n**Secure Authentication Example**:\n\n```python\nfrom flask import Flask, session, request\nfrom flask_limiter import Limiter\nfrom flask_limiter.util import get_remote_address\nimport bcrypt\nimport secrets\n\napp = Flask(__name__)\napp.secret_key = secrets.token_hex(32) # Strong random secret\n\n# Rate limiting (brute force protection)\nlimiter = Limiter(\n app=app,\n key_func=get_remote_address,\n default_limits=[\"100 per hour\"]\n)\n\n# Session configuration\napp.config.update(\n SESSION_COOKIE_SECURE=True, # HTTPS only\n SESSION_COOKIE_HTTPONLY=True, # No JavaScript access\n SESSION_COOKIE_SAMESITE='Lax', # CSRF protection\n PERMANENT_SESSION_LIFETIME=timedelta(hours=1) # Session timeout\n)\n\[email protected]('/login', methods=['POST'])\[email protected](\"5 per minute\") # Max 5 login attempts per minute\ndef login():\n username = request.form.get('username')\n password = request.form.get('password')\n\n user = User.query.filter_by(username=username).first()\n\n if user and bcrypt.checkpw(password.encode(), user.password_hash):\n # Regenerate session ID (prevent session fixation)\n session.clear()\n session['user_id'] = user.id\n session['login_time'] = datetime.utcnow()\n return {\"status\": \"success\"}\n else:\n # Generic error message (don't reveal if username exists)\n return {\"error\": \"Invalid credentials\"}, 401\n```\n\n**Password Policy**:\n\n```python\nimport re\n\ndef validate_password(password):\n \"\"\"\n Enforce strong password 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 \"\"\"\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 digit\"\n\n if not re.search(r'[!@#$%^&*(),.?\":{}|\u003c>]', password):\n return False, \"Password must contain special character\"\n\n # Check against common passwords (implement breach password check)\n # Example: Use haveibeenpwned API\n\n return True, \"Password is strong\"\n```\n\n---\n\n### A08:2021 - Software and Data Integrity Failures\n\n**Description**: Code and infrastructure that does not protect against integrity violations.\n\n**Examples**:\n- Unsigned or unverified software updates\n- Insecure CI/CD pipeline\n- Insecure deserialization\n\n**Mitigation**:\n- Code signing\n- Verify software signatures before installation\n- Use SRI (Subresource Integrity) for CDN resources\n- Secure CI/CD pipeline\n\n**Example: SRI for CDN resources**:\n\n```html\n\u003c!-- With Subresource Integrity -->\n\u003cscript src=\"https://cdn.example.com/library.js\"\n integrity=\"sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC\"\n crossorigin=\"anonymous\">\u003c/script>\n```\n\n---\n\n### A09:2021 - Security Logging and Monitoring Failures\n\n**Description**: Insufficient logging and monitoring.\n\n**Examples**:\n- Login attempts not logged\n- No alerting on suspicious activity\n- Logs not retained long enough\n\n**Secure Logging Example**:\n\n```python\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom flask import request, g\n\n# Configure secure logging\nhandler = RotatingFileHandler('security.log', maxBytes=10000000, backupCount=10)\nhandler.setLevel(logging.INFO)\nformatter = logging.Formatter(\n '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'\n)\nhandler.setFormatter(formatter)\n\nsecurity_logger = logging.getLogger('security')\nsecurity_logger.addHandler(handler)\nsecurity_logger.setLevel(logging.INFO)\n\[email protected]_request\ndef log_request():\n # Log all requests with security context\n security_logger.info(f'Request: {request.method} {request.path} from {request.remote_addr}')\n\[email protected]('/login', methods=['POST'])\ndef login():\n username = request.form.get('username')\n password = request.form.get('password')\n\n user = User.query.filter_by(username=username).first()\n\n if user and verify_password(password, user.password_hash):\n security_logger.info(f'Successful login: {username} from {request.remote_addr}')\n session['user_id'] = user.id\n return {\"status\": \"success\"}\n else:\n # Log failed login attempt\n security_logger.warning(f'Failed login attempt: {username} from {request.remote_addr}')\n return {\"error\": \"Invalid credentials\"}, 401\n```\n\n**What to Log**:\n\n```\nAuthentication Events:\n□ Login success/failure (username, IP, timestamp)\n□ Logout\n□ Password change\n□ MFA enrollment/removal\n□ Account lockout\n\nAuthorization Events:\n□ Access denied (403 errors)\n□ Privilege escalation attempts\n□ Admin actions\n\nInput Validation Failures:\n□ SQL injection attempts\n□ XSS attempts\n□ Path traversal attempts\n\nSystem Events:\n□ Application start/stop\n□ Configuration changes\n□ Error conditions\n\nNEVER LOG:\n✗ Passwords or password hashes\n✗ Session tokens or API keys\n✗ Credit card numbers or PII\n✗ Cryptographic keys\n```\n\n---\n\n### A10:2021 - Server-Side Request Forgery (SSRF)\n\n**Description**: Application fetches a remote resource without validating the user-supplied URL.\n\n**Code Example (Vulnerable)**:\n\n```python\n# Vulnerable: No URL validation\[email protected]('/fetch')\ndef fetch_url():\n url = request.args.get('url')\n response = requests.get(url)\n return response.text\n```\n\n**Code Example (Secure)**:\n\n```python\nfrom urllib.parse import urlparse\nimport ipaddress\n\n# Secure: Validate and restrict URLs\nALLOWED_DOMAINS = ['api.trusted-partner.com', 'cdn.example.com']\n\ndef is_safe_url(url):\n parsed = urlparse(url)\n\n # Only allow HTTPS\n if parsed.scheme != 'https':\n return False\n\n # Check against allowlist\n if parsed.hostname not in ALLOWED_DOMAINS:\n return False\n\n # Prevent access to internal IPs\n try:\n ip = ipaddress.ip_address(parsed.hostname)\n if ip.is_private or ip.is_loopback:\n return False\n except ValueError:\n # Hostname is not an IP (which is fine)\n pass\n\n return True\n\[email protected]('/fetch')\ndef fetch_url():\n url = request.args.get('url')\n\n if not is_safe_url(url):\n return \"Invalid URL\", 400\n\n try:\n response = requests.get(url, timeout=5)\n return response.text\n except requests.exceptions.RequestException:\n return \"Error fetching URL\", 500\n```\n\n---\n\n## DevSecOps Pipeline\n\n### CI/CD Security Integration\n\n```yaml\n# .github/workflows/security.yml\nname: Security Checks\n\non: [push, pull_request]\n\njobs:\n security-scan:\n runs-on: ubuntu-latest\n\n steps:\n - uses: actions/checkout@v3\n\n # Secrets scanning\n - name: Gitleaks\n uses: gitleaks/gitleaks-action@v2\n\n # Dependency scanning\n - name: Dependency Check\n uses: dependency-check/Dependency-Check_Action@main\n with:\n project: 'my-app'\n path: '.'\n format: 'HTML'\n\n # SAST (Static Application Security Testing)\n - name: SonarCloud Scan\n uses: SonarSource/sonarcloud-github-action@master\n env:\n GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}\n\n # Container scanning\n - name: Build Docker image\n run: docker build -t myapp:${{ github.sha }} .\n\n - name: Trivy container scan\n uses: aquasecurity/trivy-action@master\n with:\n image-ref: 'myapp:${{ github.sha }}'\n format: 'sarif'\n output: 'trivy-results.sarif'\n\n # IaC scanning\n - name: Checkov IaC scan\n uses: bridgecrewio/checkov-action@master\n with:\n directory: terraform/\n framework: terraform\n\n # Upload results\n - name: Upload SARIF results\n uses: github/codeql-action/upload-sarif@v2\n with:\n sarif_file: trivy-results.sarif\n```\n\n### Pre-commit Hooks\n\n```yaml\n# .pre-commit-config.yaml\nrepos:\n - repo: https://github.com/gitleaks/gitleaks\n rev: v8.18.0\n hooks:\n - id: gitleaks\n\n - repo: https://github.com/PyCQA/bandit\n rev: 1.7.5\n hooks:\n - id: bandit\n args: ['-r', 'src/']\n\n - repo: https://github.com/pre-commit/pre-commit-hooks\n rev: v4.5.0\n hooks:\n - id: check-added-large-files\n args: ['--maxkb=500']\n - id: detect-private-key\n - id: check-yaml\n - id: check-json\n```\n\n---\n\n## API Security\n\n### API Security Best Practices\n\n**1. Authentication**:\n\n```python\n# JWT-based API authentication\nfrom flask import Flask, request, jsonify\nfrom functools import wraps\nimport jwt\nfrom datetime import datetime, timedelta\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your-secret-key'\n\ndef token_required(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization')\n\n if not token:\n return jsonify({'error': 'Token is missing'}), 401\n\n try:\n # Remove \"Bearer \" prefix if present\n if token.startswith('Bearer '):\n token = token[7:]\n\n data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=[\"HS256\"])\n current_user = User.query.get(data['user_id'])\n except jwt.ExpiredSignatureError:\n return jsonify({'error': 'Token has expired'}), 401\n except jwt.InvalidTokenError:\n return jsonify({'error': 'Invalid token'}), 401\n\n return f(current_user, *args, **kwargs)\n\n return decorated\n\[email protected]('/api/protected', methods=['GET'])\n@token_required\ndef protected_route(current_user):\n return jsonify({'message': f'Hello, {current_user.username}'})\n```\n\n**2. Rate Limiting**:\n\n```python\nfrom flask_limiter import Limiter\nfrom flask_limiter.util import get_remote_address\n\nlimiter = Limiter(\n app=app,\n key_func=get_remote_address,\n default_limits=[\"1000 per day\", \"100 per hour\"],\n storage_uri=\"redis://localhost:6379\"\n)\n\[email protected]('/api/login', methods=['POST'])\[email protected](\"5 per minute\")\ndef api_login():\n # Login logic\n pass\n```\n\n**3. Input Validation**:\n\n```python\nfrom marshmallow import Schema, fields, validate, ValidationError\n\nclass UserRegistrationSchema(Schema):\n username = fields.Str(required=True, validate=validate.Length(min=3, max=50))\n email = fields.Email(required=True)\n password = fields.Str(required=True, validate=validate.Length(min=12))\n age = fields.Int(validate=validate.Range(min=18, max=120))\n\[email protected]('/api/register', methods=['POST'])\ndef register():\n schema = UserRegistrationSchema()\n\n try:\n data = schema.load(request.json)\n except ValidationError as err:\n return jsonify({'errors': err.messages}), 400\n\n # Proceed with registration\n # ...\n```\n\n**4. CORS Configuration**:\n\n```python\nfrom flask_cors import CORS\n\n# Restrict CORS to specific origins\nCORS(app, resources={\n r\"/api/*\": {\n \"origins\": [\"https://trusted-frontend.com\"],\n \"methods\": [\"GET\", \"POST\"],\n \"allow_headers\": [\"Content-Type\", \"Authorization\"]\n }\n})\n```\n\n---\n\n## Container Security\n\n### Dockerfile Security Best Practices\n\n```dockerfile\n# Use specific version (not 'latest')\nFROM python:3.11.7-slim-bookworm\n\n# Run as non-root user\nRUN useradd --create-home --shell /bin/bash appuser\n\n# Set working directory\nWORKDIR /app\n\n# Copy only requirements first (layer caching)\nCOPY requirements.txt .\n\n# Install dependencies without cache\nRUN pip install --no-cache-dir -r requirements.txt\n\n# Copy application code\nCOPY --chown=appuser:appuser . .\n\n# Switch to non-root user\nUSER appuser\n\n# Expose port\nEXPOSE 5000\n\n# Health check\nHEALTHCHECK --interval=30s --timeout=3s \\\n CMD python healthcheck.py || exit 1\n\n# Run application\nCMD [\"gunicorn\", \"--bind\", \"0.0.0.0:5000\", \"app:app\"]\n```\n\n### Container Scanning\n\n```bash\n# Scan container image with Trivy\ntrivy image myapp:latest\n\n# Scan for critical and high severity vulnerabilities only\ntrivy image --severity CRITICAL,HIGH myapp:latest\n\n# Scan and fail CI if vulnerabilities found\ntrivy image --exit-code 1 --severity CRITICAL myapp:latest\n```\n\nThis comprehensive application security guide provides developers with the knowledge and code examples needed to build secure applications following industry best practices.\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":26748,"content_sha256":"c548c9c876c0e569190e02483b20a6f22384d628799929dd5206b9c374754a76"},{"filename":"reference/compliance-frameworks.md","content":"# Compliance Frameworks\n\n## SOC 2 (Service Organization Control 2)\n\n### Overview\n\nSOC 2 is an auditing standard developed by the American Institute of CPAs (AICPA) for service organizations. It evaluates a company's information systems based on five Trust Service Criteria (TSC).\n\n**Best for**: SaaS companies, cloud service providers, hosting companies\n\n**Audit Types**:\n- **Type I**: Point-in-time assessment of control design\n- **Type II**: 3-12 month assessment of control operating effectiveness (required for most customers)\n\n### Trust Service Criteria\n\n```\n1. Security (Common Criteria - Required for all SOC 2 audits)\n ├─ Access controls (logical and physical)\n ├─ System operations and change management\n ├─ Risk mitigation\n └─ Network and data protection\n\n2. Availability (Optional)\n ├─ System uptime and reliability\n ├─ Disaster recovery\n └─ Business continuity\n\n3. Processing Integrity (Optional)\n ├─ Data processing accuracy and completeness\n ├─ Error detection and correction\n └─ Data validation\n\n4. Confidentiality (Optional)\n ├─ Protection of confidential information\n ├─ Data classification\n └─ Secure disposal\n\n5. Privacy (Optional)\n ├─ Collection, use, retention, disposal of personal information\n ├─ Privacy notices and consent\n └─ Data subject access requests\n```\n\n### SOC 2 Readiness Roadmap\n\n**Months 6-4 Before Audit**:\n```\n1. Scoping\n □ Define in-scope systems and services\n □ Select Trust Service Criteria (most choose Security + Availability)\n □ Identify control boundaries\n □ Engage auditor for planning\n\n2. Gap Assessment\n □ Review current controls against SOC 2 requirements\n □ Document control deficiencies\n □ Create remediation plan with priorities\n □ Estimate implementation timeline\n\n3. Policy & Procedure Development\n □ Information Security Policy\n □ Access Control Policy\n □ Change Management Policy\n □ Incident Response Policy\n □ Risk Assessment Policy\n □ Vendor Management Policy\n □ Business Continuity/Disaster Recovery Plan\n □ Employee onboarding/offboarding procedures\n```\n\n**Months 4-2 Before Audit**:\n```\n4. Control Implementation\n □ Implement technical controls (MFA, encryption, logging)\n □ Configure security tools (SIEM, EDR, vulnerability scanner)\n □ Establish change management process\n □ Deploy monitoring and alerting\n □ Implement backup and recovery procedures\n □ Establish access review process\n\n5. Evidence Preparation\n □ Set up evidence collection automation\n □ Create evidence repository (shared drive or GRC tool)\n □ Document control narratives\n □ Assign control owners\n □ Train team on evidence collection\n```\n\n**Months 2-0 (Audit Period)**:\n```\n6. Observation Period (3-12 months)\n □ Operate controls consistently\n □ Collect evidence continuously\n □ Conduct quarterly access reviews\n □ Perform vulnerability scans monthly\n □ Document security incidents and responses\n □ Track change requests and approvals\n □ Maintain audit trails\n\n7. Audit Execution\n □ Provide evidence to auditor\n □ Schedule interviews with control owners\n □ Respond to auditor information requests\n □ Address preliminary findings\n □ Review draft report\n □ Receive final SOC 2 report\n```\n\n### SOC 2 Control Examples\n\n**CC6.1 - Logical and Physical Access Controls**\n\n```yaml\nControl Objective:\n The entity implements logical access security software, infrastructure, and\n architectures over protected information assets to protect them from security events.\n\nExample Controls:\n\n1. Multi-Factor Authentication (MFA)\n - Control: MFA is required for all user access to production systems\n - Evidence: MFA enrollment report, authentication logs\n - Frequency: Quarterly review\n - Test: Auditor validates MFA enforcement by attempting login\n\n2. Least Privilege Access\n - Control: Users are granted minimum access necessary for job function\n - Evidence: Role-based access matrix, access review certifications\n - Frequency: Quarterly access reviews\n - Test: Auditor samples 25 users and validates access is appropriate\n\n3. Access Provisioning/Deprovisioning\n - Control: Access is granted via approval workflow and revoked within 24 hours of termination\n - Evidence: Onboarding/offboarding tickets, access modification logs\n - Frequency: For each user change\n - Test: Auditor samples 20 new hires and 20 terminations\n```\n\n**CC7.2 - System Monitoring**\n\n```yaml\nControl Objective:\n The entity monitors system components and the operation of those components\n for anomalies that are indicative of malicious acts.\n\nExample Controls:\n\n1. Security Information and Event Management (SIEM)\n - Control: SIEM collects and monitors security logs from all critical systems\n - Evidence: SIEM configuration, log source inventory, sample alerts\n - Frequency: Continuous monitoring\n - Test: Auditor validates SIEM is ingesting logs from all in-scope systems\n\n2. Intrusion Detection\n - Control: IDS/IPS monitors network traffic for malicious activity\n - Evidence: IDS/IPS configuration, alert dashboard, investigation records\n - Frequency: Continuous monitoring\n - Test: Auditor reviews alert volume and response procedures\n\n3. Log Review\n - Control: Security team reviews high-severity alerts within 24 hours\n - Evidence: SIEM investigation records, incident tickets\n - Frequency: Daily review of alerts\n - Test: Auditor samples 20 alerts and validates timely review\n```\n\n**CC8.1 - Change Management**\n\n```yaml\nControl Objective:\n The entity authorizes, designs, develops or acquires, configures, documents,\n tests, approves, and implements changes to infrastructure, data, software,\n and procedures to meet its objectives.\n\nExample Control:\n\n1. Production Change Approval\n - Control: All production changes require approval from change management board\n - Evidence: Change request tickets in Jira/ServiceNow with approval\n - Frequency: For each production change\n - Test: Auditor samples 25 production changes and validates approval\n\n2. Segregation of Duties\n - Control: Developers cannot deploy to production without approval\n - Evidence: CI/CD pipeline configuration, deployment logs with approver\n - Frequency: Enforced by automation\n - Test: Auditor validates pipeline prevents unauthorized deployments\n\n3. Change Testing\n - Control: All changes are tested in non-production environment before production\n - Evidence: Test results, staging deployment logs\n - Frequency: For each change\n - Test: Auditor samples 15 changes and validates testing occurred\n```\n\n### SOC 2 Evidence Collection\n\n**Automated Evidence Collection**:\n\n```python\n# Example: Automated evidence collection for quarterly access review\nimport subprocess\nimport json\nfrom datetime import datetime\n\ndef collect_access_review_evidence():\n evidence = {\n \"collection_date\": datetime.now().isoformat(),\n \"control_id\": \"CC6.2\",\n \"control_name\": \"Quarterly Access Review\"\n }\n\n # Collect list of all users with production access\n okta_users = subprocess.check_output([\n \"okta\", \"user\", \"list\",\n \"--groups\", \"production-access\",\n \"--format\", \"json\"\n ])\n evidence[\"users\"] = json.loads(okta_users)\n\n # Collect AWS IAM users\n aws_users = subprocess.check_output([\n \"aws\", \"iam\", \"list-users\",\n \"--output\", \"json\"\n ])\n evidence[\"aws_iam_users\"] = json.loads(aws_users)\n\n # Collect MFA enrollment status\n mfa_status = subprocess.check_output([\n \"okta\", \"user\", \"list\",\n \"--mfa-status\",\n \"--format\", \"json\"\n ])\n evidence[\"mfa_enrollment\"] = json.loads(mfa_status)\n\n # Save evidence to repository\n filename = f\"access_review_{datetime.now().strftime('%Y_%m_%d')}.json\"\n with open(f\"/evidence/access_reviews/{filename}\", \"w\") as f:\n json.dump(evidence, indent=2, fp=f)\n\n print(f\"Evidence collected: {filename}\")\n return evidence\n\n# Run quarterly\ncollect_access_review_evidence()\n```\n\n**Evidence Retention**:\n- SOC 2 evidence should be retained for at least 7 years\n- Organize by control and audit period\n- Use version control for policies and procedures\n\n---\n\n## ISO/IEC 27001\n\n### Overview\n\nISO/IEC 27001 is an international standard for information security management systems (ISMS). It provides a systematic approach to managing sensitive information.\n\n**Best for**: Organizations seeking international recognition, government contractors, enterprises\n\n**Certification Process**:\n1. **Gap Assessment** (optional but recommended)\n2. **Stage 1 Audit**: Documentation review\n3. **Stage 2 Audit**: Implementation assessment\n4. **Certification**: Valid for 3 years\n5. **Surveillance Audits**: Annual audits in years 1 and 2\n6. **Recertification**: Full audit in year 3\n\n### ISMS Framework\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Plan │\n│ • Establish ISMS scope │\n│ • Define information security policy │\n│ • Conduct risk assessment │\n│ • Select controls from Annex A │\n│ • Create Statement of Applicability (SOA) │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Do │\n│ • Implement controls │\n│ • Provide security awareness training │\n│ • Document procedures │\n│ • Operate the ISMS │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Check │\n│ • Monitor and measure control effectiveness │\n│ • Conduct internal audits │\n│ • Management review │\n│ • Review risk assessment │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Act │\n│ • Implement improvements │\n│ • Corrective actions for nonconformities │\n│ • Update risk treatment plan │\n│ • Continual improvement │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### Annex A Controls (ISO 27001:2022)\n\n**14 Control Domains, 93 Controls**:\n\n```\nA.5 Organizational Controls (37 controls)\n├─ Information security policies\n├─ Roles and responsibilities\n├─ Segregation of duties\n├─ Management responsibilities\n├─ Contact with authorities\n├─ Contact with special interest groups\n├─ Threat intelligence\n├─ Information security in project management\n├─ Inventory of information and assets\n├─ Acceptable use of information and assets\n├─ Return of assets\n├─ Classification of information\n├─ Labelling of information\n├─ Information transfer\n├─ Access control\n├─ Identity management\n├─ Authentication information\n├─ Access rights\n├─ Information security in supplier relationships\n├─ Addressing information security in supplier agreements\n├─ Managing information security in ICT supply chain\n├─ Monitoring, review and change management of supplier services\n├─ Information security for use of cloud services\n├─ Information security incident management planning\n├─ Assessment and decision on information security events\n├─ Response to information security incidents\n├─ Learning from information security incidents\n├─ Collection of evidence\n├─ Information security during disruption\n├─ ICT readiness for business continuity\n├─ Legal, statutory, regulatory and contractual requirements\n├─ Intellectual property rights\n├─ Protection of records\n├─ Privacy and protection of PII\n├─ Independent review of information security\n├─ Compliance with policies, rules and standards\n├─ Documented operating procedures\n\nA.6 People Controls (8 controls)\n├─ Screening\n├─ Terms and conditions of employment\n├─ Information security awareness, education and training\n├─ Disciplinary process\n├─ Responsibilities after termination or change of employment\n├─ Confidentiality or non-disclosure agreements\n├─ Remote working\n└─ Information security event reporting\n\nA.7 Physical Controls (14 controls)\n├─ Physical security perimeters\n├─ Physical entry\n├─ Securing offices, rooms and facilities\n├─ Physical security monitoring\n├─ Protecting against physical and environmental threats\n├─ Working in secure areas\n├─ Clear desk and clear screen\n├─ Equipment siting and protection\n├─ Security of assets off-premises\n├─ Storage media\n├─ Supporting utilities\n├─ Cabling security\n├─ Equipment maintenance\n└─ Secure disposal or reuse of equipment\n\nA.8 Technological Controls (34 controls)\n├─ User endpoint devices\n├─ Privileged access rights\n├─ Information access restriction\n├─ Access to source code\n├─ Secure authentication\n├─ Capacity management\n├─ Protection against malware\n├─ Management of technical vulnerabilities\n├─ Configuration management\n├─ Information deletion\n├─ Data masking\n├─ Data leakage prevention\n├─ Information backup\n├─ Redundancy of information processing facilities\n├─ Logging\n├─ Monitoring activities\n├─ Clock synchronization\n├─ Use of privileged utility programs\n├─ Installation of software on operational systems\n├─ Networks security\n├─ Security of network services\n├─ Segregation of networks\n├─ Web filtering\n├─ Use of cryptography\n├─ Secure development life cycle\n├─ Application security requirements\n├─ Secure system architecture and engineering principles\n├─ Secure coding\n├─ Security testing in development and acceptance\n├─ Outsourced development\n├─ Separation of development, test and production environments\n├─ Change management\n├─ Test information\n└─ Protection of information systems during audit testing\n```\n\n### Statement of Applicability (SOA)\n\nThe SOA is a critical ISO 27001 document that lists all 93 Annex A controls and states whether each is applicable.\n\n**SOA Format**:\n\n```\nControl Reference: A.8.5\nControl Name: Secure authentication\nApplicable: Yes\nImplementation Status: Implemented\nJustification:\n Multi-factor authentication is required for all users accessing corporate\n systems. MFA is enforced via Okta with TOTP or hardware tokens.\nControl Owner: IT Security Manager\nEvidence:\n - Okta MFA configuration\n - MFA enrollment report\n - Authentication logs\nRelated Risks: R-007 (Unauthorized access to systems)\n```\n\n**Example SOA Entry for Non-Applicable Control**:\n\n```\nControl Reference: A.7.4\nControl Name: Physical security monitoring\nApplicable: No\nImplementation Status: Not applicable\nJustification:\n Company operates entirely in cloud environments (AWS, Azure) with no\n physical data centers. Physical security is the responsibility of cloud\n providers (covered by their ISO 27001 certifications).\nControl Owner: N/A\nEvidence: N/A\nRelated Risks: N/A\n```\n\n### ISO 27001 Risk Assessment\n\n**Risk Assessment Process**:\n\n```python\n# Example risk assessment framework for ISO 27001\n\nclass RiskAssessment:\n def __init__(self):\n self.assets = []\n self.threats = []\n self.vulnerabilities = []\n self.risks = []\n\n def assess_risk(self, asset, threat, vulnerability):\n # Calculate likelihood (1-5 scale)\n likelihood = self.calculate_likelihood(threat, vulnerability)\n\n # Calculate impact (1-5 scale)\n impact = self.calculate_impact(asset)\n\n # Risk level = Likelihood × Impact\n risk_level = likelihood * impact\n\n # Determine risk category\n if risk_level >= 15:\n category = \"Critical\"\n elif risk_level >= 10:\n category = \"High\"\n elif risk_level >= 5:\n category = \"Medium\"\n else:\n category = \"Low\"\n\n risk = {\n \"asset\": asset,\n \"threat\": threat,\n \"vulnerability\": vulnerability,\n \"likelihood\": likelihood,\n \"impact\": impact,\n \"risk_level\": risk_level,\n \"category\": category\n }\n\n self.risks.append(risk)\n return risk\n\n def calculate_likelihood(self, threat, vulnerability):\n # Likelihood based on threat capability and vulnerability exploitability\n threat_levels = {\n \"nation-state\": 5,\n \"organized_crime\": 4,\n \"hacktivist\": 3,\n \"insider\": 3,\n \"script_kiddie\": 2\n }\n\n vuln_levels = {\n \"critical\": 5, # Easily exploitable, public exploit available\n \"high\": 4,\n \"medium\": 3,\n \"low\": 2,\n \"minimal\": 1\n }\n\n threat_score = threat_levels.get(threat.get(\"actor\"), 3)\n vuln_score = vuln_levels.get(vulnerability.get(\"severity\"), 3)\n\n # Average of threat capability and vulnerability exploitability\n return round((threat_score + vuln_score) / 2)\n\n def calculate_impact(self, asset):\n # Impact based on asset criticality and data sensitivity\n criticality = {\n \"critical\": 5, # Business-critical, revenue-generating\n \"high\": 4,\n \"medium\": 3,\n \"low\": 2,\n \"minimal\": 1\n }\n\n data_sensitivity = {\n \"highly_confidential\": 5, # PII, PHI, financial data\n \"confidential\": 4,\n \"internal\": 3,\n \"public\": 1\n }\n\n crit_score = criticality.get(asset.get(\"criticality\"), 3)\n data_score = data_sensitivity.get(asset.get(\"data_classification\"), 3)\n\n # Take maximum of criticality or data sensitivity\n return max(crit_score, data_score)\n\n# Example usage\nra = RiskAssessment()\n\nasset = {\n \"name\": \"Customer Database\",\n \"criticality\": \"critical\",\n \"data_classification\": \"highly_confidential\"\n}\n\nthreat = {\n \"name\": \"SQL Injection Attack\",\n \"actor\": \"organized_crime\"\n}\n\nvulnerability = {\n \"name\": \"Unvalidated user input in search function\",\n \"severity\": \"high\"\n}\n\nrisk = ra.assess_risk(asset, threat, vulnerability)\nprint(f\"Risk: {risk['category']} ({risk['risk_level']})\")\n# Output: Risk: Critical (20)\n```\n\n---\n\n## GDPR (General Data Protection Regulation)\n\n### Overview\n\nGDPR is a European Union regulation on data protection and privacy. It applies to any organization that processes personal data of EU residents, regardless of where the organization is located.\n\n**Applicability**:\n- Organizations in the EU\n- Organizations offering goods/services to EU residents\n- Organizations monitoring behavior of EU residents\n\n**Penalties**: Up to €20 million or 4% of annual global turnover (whichever is higher)\n\n### Key Principles\n\n```\n1. Lawfulness, Fairness, Transparency\n - Process data lawfully with a valid legal basis\n - Transparent about data processing activities\n\n2. Purpose Limitation\n - Collect data for specified, explicit, legitimate purposes\n - Do not use data for incompatible purposes\n\n3. Data Minimization\n - Collect only data that is necessary for the purpose\n - Avoid excessive data collection\n\n4. Accuracy\n - Ensure personal data is accurate and up to date\n - Erase or rectify inaccurate data\n\n5. Storage Limitation\n - Retain data only as long as necessary\n - Define retention periods\n\n6. Integrity and Confidentiality\n - Protect data with appropriate security measures\n - Prevent unauthorized access and data breaches\n\n7. Accountability\n - Demonstrate compliance with GDPR\n - Document processing activities and decisions\n```\n\n### Legal Bases for Processing\n\n```\n1. Consent\n - Freely given, specific, informed, unambiguous\n - Easy to withdraw\n - Example: Newsletter subscriptions\n\n2. Contract\n - Processing necessary to fulfill a contract\n - Example: Customer name/address for shipping\n\n3. Legal Obligation\n - Required by law\n - Example: Tax record retention\n\n4. Vital Interests\n - Necessary to protect life or safety\n - Example: Medical emergency\n\n5. Public Task\n - Performing a task in the public interest\n - Example: Government services\n\n6. Legitimate Interests\n - Balancing test: Your interests vs. data subject's rights\n - Example: Fraud prevention\n```\n\n### Data Subject Rights\n\n```\n1. Right to be Informed\n - Provide privacy notice explaining data processing\n - Include: what data, why, how long, who has access\n\n2. Right of Access (Subject Access Request - SAR)\n - Provide copy of personal data upon request\n - Response time: 1 month (free of charge)\n - Include: what data you hold, why you process it, who you share it with\n\n3. Right to Rectification\n - Correct inaccurate data within 1 month\n - Notify third parties of corrections\n\n4. Right to Erasure (\"Right to be Forgotten\")\n - Delete data when:\n - No longer necessary\n - Consent withdrawn\n - Object to processing\n - Exceptions: Legal obligations, legal claims\n\n5. Right to Restrict Processing\n - Temporarily suspend processing when:\n - Accuracy is contested\n - Processing is unlawful\n - Data subject objects\n\n6. Right to Data Portability\n - Provide data in machine-readable format (JSON, CSV)\n - Applies only to data provided by the subject (not derived data)\n\n7. Right to Object\n - Object to processing based on legitimate interests\n - Must stop unless compelling legitimate grounds\n\n8. Rights Related to Automated Decision Making\n - Right not to be subject to automated decisions with legal effects\n - Right to human review of automated decisions\n```\n\n### GDPR Compliance Checklist\n\n**Data Mapping**:\n```\n□ Create data inventory (what personal data you collect)\n□ Document data flows (where data comes from, where it goes)\n□ Identify legal basis for each processing activity\n□ Maintain Record of Processing Activities (ROPA)\n□ Classify data by sensitivity\n```\n\n**Privacy by Design**:\n```\n□ Conduct Data Protection Impact Assessments (DPIA) for high-risk processing\n□ Implement data minimization (collect only what's needed)\n□ Pseudonymization and anonymization where possible\n□ Privacy-friendly default settings\n□ Embed privacy in system design\n```\n\n**Security Measures**:\n```\n□ Encryption of personal data (at rest and in transit)\n□ Access controls (least privilege, RBAC)\n□ Pseudonymization and anonymization\n□ Regular security testing (penetration tests, vulnerability scans)\n□ Incident response plan\n□ Data breach notification procedures (72 hours to authority)\n```\n\n**Transparency**:\n```\n□ Privacy policy/notice published and accessible\n□ Cookie consent mechanism (explicit opt-in for non-essential cookies)\n□ Clear, plain language in privacy notices\n□ Layered privacy notices (summary + full version)\n```\n\n**Data Subject Rights**:\n```\n□ Process for handling subject access requests (SAR)\n□ Process for data rectification and erasure\n□ Process for data portability (export functionality)\n□ Mechanism to withdraw consent\n□ Process for objections to processing\n□ Response time: 1 month (extendable to 3 months with justification)\n```\n\n**Vendor Management**:\n```\n□ Data Processing Agreements (DPA) with all processors\n□ DPA includes: Purpose, duration, data types, security measures, sub-processors\n□ Vendor security assessments\n□ List of sub-processors disclosed\n□ Standard Contractual Clauses (SCC) for transfers outside EU\n```\n\n**Breach Management**:\n```\n□ Breach detection and logging\n□ Breach assessment procedure (risk to individuals?)\n□ Notification to supervisory authority within 72 hours\n□ Notification to affected individuals if high risk\n□ Breach documentation and lessons learned\n```\n\n### Data Protection Impact Assessment (DPIA)\n\n**When DPIA is Required**:\n- Large-scale processing of sensitive data\n- Systematic monitoring (e.g., tracking, profiling)\n- Automated decision-making with legal effects\n- Processing of vulnerable populations (children)\n- New technologies with high privacy risk\n\n**DPIA Template**:\n\n```markdown\n## Data Protection Impact Assessment\n\n### 1. Project Description\n- **Project Name**: Customer Behavior Analytics Platform\n- **Purpose**: Analyze customer purchasing patterns to provide personalized recommendations\n- **Legal Basis**: Legitimate interests (improving customer experience)\n- **Data Controller**: Acme Corp\n- **Data Processor**: Analytics Vendor Inc.\n\n### 2. Data Processing Description\n- **Data Categories**:\n - Purchase history\n - Browsing behavior\n - Demographics (age, gender, location)\n - Device information\n- **Data Subjects**: Customers (18+)\n- **Volume**: 1 million customers\n- **Retention**: 2 years\n- **Automated Decision Making**: Yes (product recommendations)\n\n### 3. Necessity and Proportionality\n- **Why is processing necessary?**: To improve customer experience and increase sales\n- **Is data minimized?**: Yes, only collect data relevant to recommendations\n- **Alternatives considered?**:\n - Option 1: Manual curation (not scalable)\n - Option 2: Anonymous analytics only (less effective)\n\n### 4. Risks to Data Subjects\n| Risk | Likelihood | Severity | Risk Level |\n|------|-----------|----------|-----------|\n| Unauthorized access to purchase history | Medium | High | High |\n| Re-identification from pseudonymized data | Low | High | Medium |\n| Inaccurate recommendations affecting user experience | Medium | Low | Low |\n| Data breach exposing customer data | Low | Critical | High |\n\n### 5. Measures to Address Risks\n- **Encryption**: AES-256 encryption at rest, TLS 1.3 in transit\n- **Access Control**: RBAC with least privilege, MFA required\n- **Pseudonymization**: Customer IDs pseudonymized, no PII in analytics database\n- **Audit Logging**: All data access logged and monitored\n- **Data Minimization**: Only collect necessary fields, anonymize after 2 years\n- **User Control**: Opt-out available, data deletion on request\n\n### 6. Consultation\n- **DPO Review**: Approved with recommendations implemented\n- **Data Subjects Consulted**: No (but opt-out available)\n- **Supervisory Authority**: Not required to consult\n\n### 7. Sign-off\n- **Completed by**: Privacy Officer\n- **Date**: 2025-01-15\n- **Approved by**: DPO\n- **Review Date**: 2026-01-15 (annual review)\n```\n\n---\n\n## HIPAA (Health Insurance Portability and Accountability Act)\n\n### Overview\n\nHIPAA is a US federal law that protects the privacy and security of Protected Health Information (PHI). It applies to covered entities and business associates.\n\n**Covered Entities**:\n- Healthcare providers (hospitals, clinics, doctors)\n- Health plans (insurance companies)\n- Healthcare clearinghouses\n\n**Business Associates**:\n- Vendors that handle PHI on behalf of covered entities\n- Examples: EHR vendors, billing companies, cloud hosting providers\n\n**Penalties**:\n- Tier 1 (Unaware): $100-$50,000 per violation\n- Tier 4 (Willful neglect): $50,000+ per violation\n- Maximum: $1.5 million per year per violation type\n\n### HIPAA Rules\n\n```\n1. Privacy Rule\n - Protects privacy of PHI\n - Patient rights (access, amendment, accounting of disclosures)\n - Minimum necessary standard\n - Notice of Privacy Practices (NPP)\n\n2. Security Rule\n - Administrative safeguards (policies, training, risk assessment)\n - Physical safeguards (facility access, workstation security)\n - Technical safeguards (access control, encryption, audit logs)\n\n3. Breach Notification Rule\n - Notify individuals within 60 days of breach discovery\n - Notify HHS within 60 days (or immediately if >500 individuals)\n - Notify media if >500 individuals in same state/jurisdiction\n\n4. Enforcement Rule\n - Defines penalties and investigation procedures\n - Handled by Office for Civil Rights (OCR)\n```\n\n### Protected Health Information (PHI)\n\n**PHI Identifiers** (must be removed for de-identification):\n\n```\nDirect Identifiers:\n1. Names\n2. Geographic subdivisions smaller than state (except first 3 digits of ZIP if >20,000 people)\n3. Dates (except year) - birth, admission, discharge, death, age >89\n4. Phone numbers\n5. Fax numbers\n6. Email addresses\n7. Social Security Numbers\n8. Medical record numbers\n9. Health plan beneficiary numbers\n10. Account numbers\n11. Certificate/license numbers\n12. Vehicle identifiers (license plates, VINs)\n13. Device identifiers and serial numbers\n14. Web URLs\n15. IP addresses\n16. Biometric identifiers (fingerprints, retinal scans)\n17. Full-face photos and comparable images\n18. Any other unique identifying number, characteristic, or code\n\nExceptions (not considered PHI if no other identifiers):\n- Age if ≤89 years\n- First 3 digits of ZIP code (if ≥20,000 people)\n- Year only (no month/day)\n```\n\n### HIPAA Security Rule Safeguards\n\n**Administrative Safeguards**:\n\n```\nRequired:\n□ Security Management Process\n - Risk assessment (annual)\n - Risk management\n - Sanction policy\n - Information system activity review\n\n□ Assigned Security Responsibility\n - Designate security official\n\n□ Workforce Security\n - Authorization/supervision\n - Workforce clearance\n - Termination procedures\n\n□ Information Access Management\n - Access authorization\n - Access modification\n\n□ Security Awareness and Training\n - Security reminders\n - Protection from malware\n - Log-in monitoring\n - Password management\n\n□ Security Incident Procedures\n - Incident response and reporting\n\n□ Contingency Plan\n - Data backup plan\n - Disaster recovery plan\n - Emergency mode operation plan\n\n□ Evaluation\n - Periodic technical and non-technical evaluations\n\nAddressable:\n□ Business Associate Contracts\n□ Written Contract or Other Arrangement\n```\n\n**Physical Safeguards**:\n\n```\nRequired:\n□ Facility Access Controls\n - Contingency operations\n - Facility security plan\n - Access control and validation procedures\n - Maintenance records\n\n□ Workstation Use\n - Policies on appropriate use\n\n□ Workstation Security\n - Physical safeguards for workstations\n\n□ Device and Media Controls\n - Disposal (secure deletion/destruction)\n - Media re-use (sanitization)\n - Accountability (inventory)\n - Data backup and storage\n```\n\n**Technical Safeguards**:\n\n```\nRequired:\n□ Access Control\n - Unique user identification\n - Emergency access procedure\n - Automatic logoff (addressable)\n - Encryption and decryption (addressable)\n\n□ Audit Controls\n - Hardware, software, procedural mechanisms to record and examine activity\n\n□ Integrity\n - Mechanism to corroborate that PHI has not been altered or destroyed\n\n□ Person or Entity Authentication\n - Verify that person/entity is who they claim to be\n\n□ Transmission Security\n - Integrity controls (addressable)\n - Encryption (addressable)\n```\n\n### HIPAA Compliance Checklist\n\n```\nPrivacy Rule Compliance:\n□ Designate Privacy Officer\n□ Create and distribute Notice of Privacy Practices (NPP)\n□ Obtain patient authorizations for uses beyond treatment/payment/operations\n□ Implement minimum necessary standard\n□ Business Associate Agreements (BAA) with all vendors handling PHI\n□ Process for patient rights (access, amendment, accounting of disclosures)\n□ Privacy training for all workforce members\n\nSecurity Rule Compliance:\n□ Designate Security Officer\n□ Conduct annual risk assessment\n□ Implement administrative safeguards (policies, training, sanctions)\n□ Implement physical safeguards (facility access, workstation security, device disposal)\n□ Implement technical safeguards (access control, audit logs, encryption)\n□ Document all policies and procedures\n□ Security awareness training for all workforce members\n\nBreach Notification Compliance:\n□ Breach detection and assessment procedures\n□ Risk assessment methodology (4-factor analysis)\n□ Notification templates (individual, HHS, media)\n□ Breach log maintained\n□ 60-day notification timeline process\n\nBusiness Associate Management:\n□ BAA template with required provisions\n□ BAA signed with all business associates\n□ Business associate risk assessments\n□ Monitor business associate compliance\n```\n\n### HIPAA Risk Assessment\n\n**Risk Assessment Process**:\n\n```\n1. Scope Determination\n - Define boundaries (locations, systems, workforce)\n - Identify where ePHI is created, received, maintained, transmitted\n\n2. Data Collection\n - Asset inventory (hardware, software, data)\n - Network diagrams\n - Data flow diagrams\n - Current safeguards documentation\n\n3. Threat and Vulnerability Identification\n Threats:\n - Natural disasters (fire, flood, earthquake)\n - Environmental (power failure, temperature)\n - Human (intentional: hackers, malicious insiders; unintentional: errors)\n - Technical (hardware failure, software bugs, malware)\n\n Vulnerabilities:\n - Unpatched systems\n - Weak passwords\n - Missing encryption\n - Lack of physical security\n - Insufficient logging\n\n4. Current Security Measures Assessment\n - Document existing safeguards\n - Evaluate effectiveness\n - Identify gaps\n\n5. Likelihood and Impact Determination\n Likelihood: Low (0.1) | Medium (0.5) | High (0.9)\n Impact: Low (10) | Medium (50) | High (100)\n\n Risk Level = Likelihood × Impact\n - Low: \u003c10\n - Medium: 10-50\n - High: >50\n\n6. Risk Determination\n For each threat + vulnerability + asset combination\n\n7. Finalize Documentation\n - Risk assessment report\n - Risk register\n - Remediation plan with priorities\n\n8. Implement Risk Management\n - Implement safeguards to reduce risk\n - Document decisions and rationale\n - Accept residual risk\n\n9. Maintain Continuous Risk Management\n - Annual risk assessment\n - Update when significant changes occur\n```\n\n**HIPAA Risk Assessment Template**:\n\n```\nAsset: Electronic Health Records (EHR) System\nThreat: Ransomware Attack\nVulnerability: Outdated server OS (Windows Server 2012)\nCurrent Safeguards: Antivirus, firewall, network segmentation\n\nLikelihood: High (0.9) - Widespread ransomware campaigns targeting healthcare\nImpact: High (100) - Complete loss of access to patient records, treatment delays\n\nRisk Level: 90 (High)\n\nRecommended Action:\n1. Immediate: Upgrade to Windows Server 2022 (Priority 1)\n2. Short-term: Implement EDR solution (Priority 1)\n3. Ongoing: Offline backups tested monthly (Priority 2)\n\nRisk Owner: IT Director\nTarget Completion: 30 days\nResidual Risk: Medium (after implementation of mitigations)\n```\n\n---\n\n## PCI-DSS (Payment Card Industry Data Security Standard)\n\n### Overview\n\nPCI-DSS is a set of security standards for organizations that handle credit card information. Compliance is required by card brands (Visa, Mastercard, Amex, Discover).\n\n**Merchant Levels** (based on annual Visa transaction volume):\n- **Level 1**: >6 million transactions - Annual audit by QSA (Qualified Security Assessor)\n- **Level 2**: 1-6 million - Annual SAQ (Self-Assessment Questionnaire) + quarterly network scan\n- **Level 3**: 20,000-1 million e-commerce - Annual SAQ + quarterly scan\n- **Level 4**: \u003c20,000 e-commerce or \u003c1 million - Annual SAQ + quarterly scan\n\n**Fines**: $5,000-$100,000 per month for non-compliance (set by acquiring bank)\n\n### PCI-DSS Requirements\n\n**12 Requirements, 6 Control Objectives**:\n\n```\nBuild and Maintain a Secure Network:\n├─ Requirement 1: Install and maintain network security controls\n│ • Firewalls at network boundaries\n│ • Deny by default, allow by exception\n│ • No direct routes between untrusted networks and CDE\n│ • Stateful inspection\n│\n└─ Requirement 2: Apply secure configurations\n • Change default passwords and security parameters\n • Remove unnecessary accounts and services\n • Implement only one primary function per server\n • Enable only necessary services and protocols\n\nProtect Account Data:\n├─ Requirement 3: Protect stored account data\n│ • Keep data storage to minimum necessary\n│ • Do not store sensitive authentication data post-authorization (CVV, PIN, full track data)\n│ • Mask PAN when displayed (max first 6 and last 4 digits)\n│ • Render PAN unreadable (encryption, truncation, hashing, tokenization)\n│ • Protect encryption keys\n│\n└─ Requirement 4: Protect cardholder data with strong cryptography during transmission\n • Use strong cryptography (TLS 1.2+) for transmission over open, public networks\n • Never send unencrypted PANs by end-user messaging technologies\n • Protect wireless transmissions\n\nMaintain a Vulnerability Management Program:\n├─ Requirement 5: Protect all systems and networks from malicious software\n│ • Deploy anti-malware on all systems (especially where malware is common)\n│ • Ensure anti-malware is current and actively running\n│ • Periodic scans performed\n│\n└─ Requirement 6: Develop and maintain secure systems and software\n • Identify and address security vulnerabilities\n • Patch critical security patches within 30 days\n • Develop software securely (OWASP guidelines)\n • Prevent common coding vulnerabilities\n • Address vulnerabilities in bespoke and custom software\n\nImplement Strong Access Control Measures:\n├─ Requirement 7: Restrict access to system components and cardholder data by business need to know\n│ • Limit access based on need to know\n│ • Assign access based on job classification and function\n│ • Default \"deny-all\" setting\n│\n├─ Requirement 8: Identify users and authenticate access to system components\n│ • Assign unique ID to each person with access\n│ • Multi-factor authentication for all access into CDE\n│ • Strong authentication and password policies\n│ • No use of shared accounts\n│\n└─ Requirement 9: Restrict physical access to cardholder data\n • Appropriate facility entry controls\n • Distinguish between employees and visitors\n • Physically secure all media containing cardholder data\n • Destroy media when no longer needed\n • Protect devices that capture payment card data\n\nRegularly Monitor and Test Networks:\n├─ Requirement 10: Log and monitor all access to system components and cardholder data\n│ • Log all individual access to cardholder data\n│ • Log all actions by individuals with administrative access\n│ • Log all access to audit logs\n│ • Record at minimum: user ID, type of event, date/time, success/failure, origin, identity of affected data/system\n│ • Retain audit logs for at least 12 months (3 months immediately available)\n│ • Review logs daily\n│\n└─ Requirement 11: Test security of systems and networks regularly\n • Implement wireless scanning (quarterly)\n • Run internal and external vulnerability scans (quarterly + after significant changes)\n • Perform penetration testing (annually + after significant changes)\n • Implement intrusion detection/prevention systems\n • Implement file-integrity monitoring\n\nMaintain an Information Security Policy:\n└─ Requirement 12: Support information security with organizational policies and programs\n • Establish, publish, maintain, and disseminate information security policy\n • Implement risk assessment process (at least annually)\n • Usage policies for critical technologies (remote access, wireless, removable media)\n • Assign information security responsibilities to specific individuals\n • Security awareness training for all personnel\n • Screen potential personnel prior to hire\n • Maintain incident response plan\n```\n\n### Cardholder Data Environment (CDE)\n\n**CDE Scope**:\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Cardholder Data Environment (CDE) │\n│ │\n│ ┌────────────────────────────────────────────────────────┐ │\n│ │ Systems that Store, Process, or Transmit CHD │ │\n│ │ • Payment application │ │\n│ │ • Database with cardholder data │ │\n│ │ • Web server handling transactions │ │\n│ └────────────────────────────────────────────────────────┘ │\n│ │\n│ ┌────────────────────────────────────────────────────────┐ │\n│ │ Connected Systems (can impact security of CDE) │ │\n│ │ • Firewalls protecting CDE │ │\n│ │ • Jump servers with access to CDE │ │\n│ │ • Systems on same network segment │ │\n│ └────────────────────────────────────────────────────────┘ │\n└─────────────────────────────────────────────────────────────┘\n ↑\n Network Segmentation\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Out of Scope (Segregated) │\n│ • Corporate website (no payment processing) │\n│ • Internal applications (no access to CDE) │\n│ • Employee workstations (no CDE access) │\n└─────────────────────────────────────────────────────────────┘\n```\n\n**Scope Reduction Strategies**:\n\n1. **Tokenization**: Replace PAN with token, store tokens instead of PANs\n2. **Point-to-Point Encryption (P2PE)**: Encrypt at point of interaction, decrypt at processor\n3. **Network Segmentation**: Isolate CDE from other networks\n4. **Third-Party Payment Processors**: Use Stripe, PayPal, Braintree (shifts PCI burden)\n\n### PCI-DSS Compliance Example\n\n**Example: E-commerce Implementation**:\n\n```\nScenario: Online retailer processing credit cards\n\nApproach: Minimize PCI scope with third-party processor\n\nArchitecture:\n1. Use Stripe.js to collect payment information\n - Payment form hosted by Stripe (iframe)\n - Card data never touches your servers\n - Receive token from Stripe\n\n2. Your server processes order with token\n - Store token (not PAN) in database\n - Use token for charges, refunds\n\n3. PCI scope: Your JavaScript code only\n - No cardholder data stored/processed/transmitted by your servers\n - Reduced compliance burden (SAQ A instead of SAQ D)\n\nCompliance Requirements (SAQ A):\n□ Use only PCI-DSS validated third-party payment processor\n□ Cardholder data never stored/processed/transmitted by merchant systems\n□ HTTPS on payment pages\n□ Quarterly vulnerability scans of public-facing web servers\n□ Security policy and procedures\n□ Vendor management\n```\n\n**Full PCI Compliance Example (Level 1 Merchant)**:\n\n```python\n# Example: Secure credit card processing (if you must handle PANs)\n\nfrom cryptography.fernet import Fernet\nimport hashlib\nimport re\n\nclass PCICompliantPaymentProcessor:\n def __init__(self, encryption_key):\n self.cipher = Fernet(encryption_key)\n\n def validate_pan(self, pan):\n \"\"\"Validate PAN using Luhn algorithm\"\"\"\n # Remove spaces and dashes\n pan = re.sub(r'[\\s-]', '', pan)\n\n # Must be 13-19 digits\n if not re.match(r'^\\d{13,19}

Security & Compliance Expert Core Principles 1. Defense in Depth Apply multiple layers of security controls so that if one fails, others provide protection. Never rely on a single security mechanism. 2. Zero Trust Architecture Never trust, always verify. Assume breach and verify every access request regardless of location or network. 3. Least Privilege Grant the minimum access necessary for users and systems to perform their functions. Regularly review and revoke unused permissions. 4. Security by Design Integrate security requirements from the earliest stages of system design, not as an afte…

, pan):\n return False\n\n # Luhn check\n def luhn_check(card_num):\n digits = [int(d) for d in card_num]\n checksum = 0\n for i, d in enumerate(reversed(digits)):\n if i % 2 == 1:\n d *= 2\n if d > 9:\n d -= 9\n checksum += d\n return checksum % 10 == 0\n\n return luhn_check(pan)\n\n def encrypt_pan(self, pan):\n \"\"\"Encrypt PAN for storage (PCI Req 3.4)\"\"\"\n if not self.validate_pan(pan):\n raise ValueError(\"Invalid PAN\")\n\n # Encrypt PAN\n encrypted = self.cipher.encrypt(pan.encode())\n return encrypted\n\n def decrypt_pan(self, encrypted_pan):\n \"\"\"Decrypt PAN (only when necessary)\"\"\"\n decrypted = self.cipher.decrypt(encrypted_pan).decode()\n return decrypted\n\n def mask_pan(self, pan):\n \"\"\"Mask PAN for display (PCI Req 3.3)\"\"\"\n # Show first 6 and last 4 digits only\n if len(pan) \u003c 10:\n return '*' * len(pan)\n\n return pan[:6] + '*' * (len(pan) - 10) + pan[-4:]\n\n def hash_pan(self, pan):\n \"\"\"Create one-way hash of PAN for lookups\"\"\"\n # Use strong hash with salt\n salt = b'your-random-salt' # Should be unique per application\n return hashlib.pbkdf2_hmac('sha256', pan.encode(), salt, 100000)\n\n def log_access(self, user_id, action, result):\n \"\"\"Log all access to cardholder data (PCI Req 10)\"\"\"\n import datetime\n log_entry = {\n \"timestamp\": datetime.datetime.utcnow().isoformat(),\n \"user_id\": user_id,\n \"action\": action,\n \"result\": result,\n \"ip_address\": self.get_client_ip() # Implement this\n }\n # Write to tamper-proof log storage\n self.write_to_audit_log(log_entry)\n\n# Usage\nprocessor = PCICompliantPaymentProcessor(encryption_key=Fernet.generate_key())\n\n# Process payment\npan = \"4532015112830366\" # Test Visa card\nencrypted = processor.encrypt_pan(pan)\nmasked = processor.mask_pan(pan)\n\nprint(f\"Masked PAN: {masked}\") # Output: 453201******0366\n# NEVER log or display full PAN\n```\n\n---\n\n## Additional Compliance Frameworks\n\n### NIST 800-53 (Federal Systems)\n\n**Purpose**: Security controls for federal information systems and organizations\n\n**Control Families** (20 families):\n- AC: Access Control\n- AT: Awareness and Training\n- AU: Audit and Accountability\n- CA: Assessment, Authorization, and Monitoring\n- CM: Configuration Management\n- CP: Contingency Planning\n- IA: Identification and Authentication\n- IR: Incident Response\n- MA: Maintenance\n- MP: Media Protection\n- PE: Physical and Environmental Protection\n- PL: Planning\n- PM: Program Management\n- PS: Personnel Security\n- PT: PII Processing and Transparency\n- RA: Risk Assessment\n- SA: System and Services Acquisition\n- SC: System and Communications Protection\n- SI: System and Information Integrity\n- SR: Supply Chain Risk Management\n\n**Baselines**:\n- Low Impact: 125 controls\n- Moderate Impact: 325 controls\n- High Impact: 421 controls\n\n### FedRAMP (Federal Risk and Authorization Management Program)\n\n**Purpose**: Standardized approach to security assessment, authorization, and continuous monitoring for cloud products and services used by federal agencies\n\n**Authorization Levels**:\n- **Low Impact**: LI-SaaS (SaaS only), FIPS 199 Low\n- **Moderate Impact**: FIPS 199 Moderate (most common)\n- **High Impact**: FIPS 199 High (highly sensitive data)\n\n**Authorization Paths**:\n1. **JAB P-ATO** (Joint Authorization Board Provisional Authority to Operate): Government-wide authorization\n2. **Agency ATO**: Specific agency authorization\n3. **CSP Supplied**: CSP provides package, agency reviews\n\n### CCPA (California Consumer Privacy Act)\n\n**Purpose**: California state law giving consumers more control over personal information collected by businesses\n\n**Applicability**:\n- Businesses with $25M+ annual revenue\n- OR buy/sell personal information of 50,000+ consumers\n- OR derive 50%+ revenue from selling personal information\n\n**Consumer Rights**:\n1. Right to know what personal information is collected\n2. Right to know if personal information is sold or disclosed\n3. Right to say no to the sale of personal information\n4. Right to access personal information\n5. Right to equal service and price (no discrimination for exercising rights)\n6. Right to deletion\n\n**Requirements**:\n- \"Do Not Sell My Personal Information\" link on homepage\n- Privacy policy updates\n- Process for verifiable consumer requests\n- 45-day response time to requests\n- Reasonable security measures\n\n---\n\n## Multi-Framework Compliance Strategy\n\n### Control Mapping\n\nMap controls across frameworks to maximize efficiency:\n\n```\nExample: Multi-Factor Authentication (MFA)\n\nSOC 2: CC6.1 - Logical and physical access controls\nISO 27001: A.9.4.2 - Secure log-on procedures\nNIST CSF: PR.AC-7 - Users authenticated and managed\nHIPAA: § 164.312(d) - Person or entity authentication\nPCI-DSS: Req 8.3 - Secure all individual non-console administrative access and all remote access to the CDE using MFA\nGDPR: Article 32 - Appropriate technical and organizational measures\n\nImplementation:\n✓ Single MFA solution (e.g., Okta) satisfies all frameworks\n✓ Document control once, reference across multiple audits\n✓ Collect evidence once, use for multiple compliance requirements\n```\n\n### GRC Platform for Multi-Framework Compliance\n\n**GRC Tools**:\n- Vanta (automated SOC 2, ISO 27001, HIPAA)\n- Drata (similar to Vanta)\n- OneTrust (privacy and governance)\n- ServiceNow GRC\n- Archer (RSA)\n\n**Benefits**:\n- Automated evidence collection\n- Continuous compliance monitoring\n- Control mapping across frameworks\n- Audit trail documentation\n- Policy management\n- Risk assessment tracking\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":51686,"content_sha256":"6c45b1607e943322aaaf19a349a990179be09d220a6bc032319a02cd509d3d88"},{"filename":"reference/security-architecture.md","content":"# Security Architecture & Design\n\n## Zero Trust Architecture\n\n### Core Principles\n\nZero Trust is a security model based on the principle of \"never trust, always verify.\" It assumes that threats exist both inside and outside the network.\n\n**Foundational Tenets**:\n1. **Verify explicitly** - Always authenticate and authorize based on all available data points\n2. **Use least privilege access** - Limit user access with Just-In-Time and Just-Enough-Access (JIT/JEA)\n3. **Assume breach** - Minimize blast radius and segment access. Verify end-to-end encryption\n\n### Zero Trust Architecture Components\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Control Plane │\n│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │\n│ │ Identity │ │ Device │ │ Application │ │\n│ │ Management │ │ Management │ │ Registry │ │\n│ └──────────────┘ └──────────────┘ └──────────────┘ │\n│ │\n│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │\n│ │ Policy │ │ Threat │ │ Analytics │ │\n│ │ Engine │ │ Intelligence │ │ & Logging │ │\n│ └──────────────┘ └──────────────┘ └──────────────┘ │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Data Plane │\n│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │\n│ │ Policy │ │ Policy │ │ Policy │ │\n│ │ Enforcement │→ │ Enforcement │→ │ Enforcement │ │\n│ │ Point (PEP) │ │ Point (PEP) │ │ Point (PEP) │ │\n│ └──────────────┘ └──────────────┘ └──────────────┘ │\n│ ↓ ↓ ↓ │\n│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │\n│ │ Resource │ │ Resource │ │ Resource │ │\n│ │ (App/DB) │ │ (App/DB) │ │ (App/DB) │ │\n│ └──────────────┘ └──────────────┘ └──────────────┘ │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### Zero Trust Access Flow\n\n```\n1. User/Device requests access to resource\n ↓\n2. Policy Enforcement Point (PEP) intercepts request\n ↓\n3. PEP queries Policy Engine\n ↓\n4. Policy Engine evaluates:\n - Identity verification (MFA)\n - Device posture (compliant, patched, encrypted)\n - Location and network context\n - Resource sensitivity\n - Risk score (based on behavior analytics)\n ↓\n5. Policy Decision Point (PDP) makes decision:\n - Allow (with session time limit)\n - Deny\n - Allow with step-up authentication\n ↓\n6. Continuous verification during session\n - Monitor for anomalous behavior\n - Re-authenticate periodically\n - Revoke access if risk increases\n```\n\n### Zero Trust Implementation Roadmap\n\n**Phase 1: Foundation (Months 1-3)**\n- Implement strong identity and access management (IAM)\n- Deploy multi-factor authentication (MFA) everywhere\n- Create comprehensive asset inventory\n- Establish baseline logging and monitoring\n\n**Phase 2: Visibility (Months 4-6)**\n- Map all data flows and dependencies\n- Implement network traffic analysis\n- Deploy endpoint detection and response (EDR)\n- Establish user and entity behavior analytics (UEBA)\n\n**Phase 3: Segmentation (Months 7-9)**\n- Implement network micro-segmentation\n- Create security zones based on data sensitivity\n- Apply least privilege access policies\n- Implement application-layer controls\n\n**Phase 4: Automation (Months 10-12)**\n- Automate policy enforcement\n- Implement SOAR for incident response\n- Deploy continuous compliance monitoring\n- Integrate threat intelligence feeds\n\n**Phase 5: Optimization (Ongoing)**\n- Continuous policy refinement\n- Regular access reviews and certifications\n- Threat hunting and proactive defense\n- Measure and improve security posture\n\n---\n\n## Defense in Depth\n\n### Security Layers\n\n```\nLayer 7: User Education & Awareness\n ↓ (Social engineering, phishing)\nLayer 6: Physical Security\n ↓ (Access badges, surveillance, locks)\nLayer 5: Perimeter Security\n ↓ (Firewall, IDS/IPS, WAF)\nLayer 4: Network Security\n ↓ (Segmentation, VLANs, ACLs)\nLayer 3: Endpoint Security\n ↓ (EDR, antivirus, host firewall)\nLayer 2: Application Security\n ↓ (Input validation, authentication, secure coding)\nLayer 1: Data Security\n ↓ (Encryption, DLP, access controls)\n```\n\n### Security Control Types by Layer\n\n**Preventive Controls** (Stop attacks before they occur):\n- Firewalls and network segmentation\n- Multi-factor authentication\n- Encryption at rest and in transit\n- Secure coding practices\n- Access control lists (ACLs)\n- Security awareness training\n\n**Detective Controls** (Identify attacks when they occur):\n- Security Information and Event Management (SIEM)\n- Intrusion Detection Systems (IDS)\n- Log monitoring and analysis\n- File integrity monitoring (FIM)\n- Vulnerability scanning\n- User and Entity Behavior Analytics (UEBA)\n\n**Corrective Controls** (Fix issues after detection):\n- Incident response procedures\n- Patch management\n- Malware removal\n- Account lockout and password reset\n- Backup and recovery\n- Forensic analysis\n\n**Deterrent Controls** (Discourage attackers):\n- Warning banners\n- Security policies and consequences\n- Legal agreements and NDAs\n- Audit trails and accountability\n\n---\n\n## Secure Network Architecture\n\n### Network Segmentation Design\n\n```\nInternet\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ DMZ (Demilitarized Zone) │\n│ - Web servers (public-facing) │\n│ - Reverse proxies │\n│ - Email gateways │\n│ Security: WAF, DDoS protection, IDS │\n└─────────────────────────────────────────────────────────────┘\n ↓ (Firewall)\n┌─────────────────────────────────────────────────────────────┐\n│ Application Tier │\n│ - Application servers │\n│ - API gateways │\n│ - Microservices │\n│ Security: Application firewall, API security │\n└─────────────────────────────────────────────────────────────┘\n ↓ (Firewall)\n┌─────────────────────────────────────────────────────────────┐\n│ Data Tier │\n│ - Database servers │\n│ - Data warehouses │\n│ - File storage │\n│ Security: Database firewall, encryption, DLP │\n└─────────────────────────────────────────────────────────────┘\n ↓ (Firewall)\n┌─────────────────────────────────────────────────────────────┐\n│ Management Network (Separate VLAN) │\n│ - Jump servers/bastion hosts │\n│ - Monitoring systems │\n│ - Backup infrastructure │\n│ Security: PAM, MFA, session recording │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### Micro-segmentation Strategy\n\nTraditional segmentation creates large security zones. Micro-segmentation creates granular controls around individual workloads.\n\n**Benefits**:\n- Limits lateral movement\n- Reduces blast radius of breaches\n- Enables Zero Trust networking\n- Improves compliance (isolate regulated data)\n\n**Implementation Approaches**:\n\n1. **Network-based** (VLANs, ACLs, firewalls)\n - Pros: Mature technology, hardware-based\n - Cons: Static, difficult to manage at scale\n\n2. **Software-Defined** (SDN, NSX, Cisco ACI)\n - Pros: Dynamic, policy-based, scales well\n - Cons: Requires new infrastructure, complexity\n\n3. **Host-based** (iptables, Windows Firewall, Security Groups)\n - Pros: Granular, follows workloads, cloud-native\n - Cons: Requires agent management\n\n**Micro-segmentation Policy Example**:\n\n```yaml\n# Allow web tier to communicate with app tier only on port 443\nsource:\n tier: web\n environment: production\ndestination:\n tier: app\n environment: production\nprotocol: tcp\nport: 443\naction: allow\n\n# Deny all other traffic from web tier to app tier\nsource:\n tier: web\ndestination:\n tier: app\naction: deny\n```\n\n### Secure Remote Access Architecture\n\n```\nRemote Users\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Step 1: Identity Verification │\n│ - MFA (TOTP, push, biometric) │\n│ - Device posture check (patch level, encryption) │\n│ - Conditional access policies (location, risk score) │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Step 2: Secure Connection │\n│ Options: │\n│ A) VPN (IPsec, SSL VPN) - Network-level access │\n│ B) ZTNA (Zero Trust Network Access) - Application access │\n│ C) Privileged Access Workstation (PAW) for admins │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Step 3: Access Broker │\n│ - Evaluate access policies │\n│ - Grant least privilege access │\n│ - Establish session with time limit │\n│ - Monitor session for anomalies │\n└─────────────────────────────────────────────────────────────┘\n ↓\nCorporate Resources (Applications, Files, Databases)\n```\n\n**VPN vs. ZTNA Comparison**:\n\n| Aspect | VPN | ZTNA |\n|--------|-----|------|\n| Access model | Network-level | Application-level |\n| Trust model | Implicit trust once connected | Continuous verification |\n| Lateral movement | Possible | Prevented |\n| Deployment | On-premises appliance | Cloud-native service |\n| User experience | Full network access | Seamless app access |\n| Security | Perimeter-based | Identity-based |\n\n---\n\n## Cloud Security Architecture\n\n### Multi-Cloud Security Architecture\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Centralized Security Management │\n│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │\n│ │ SIEM │ │ CSPM │ │ CASB │ │ PAM │ │\n│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌──────────────────┬──────────────────┬──────────────────────┐\n│ AWS │ Azure │ GCP │\n├──────────────────┼──────────────────┼──────────────────────┤\n│ • Security Hub │ • Defender │ • Security Command │\n│ • GuardDuty │ • Sentinel │ Center │\n│ • IAM │ • Entra ID │ • Cloud IAM │\n│ • KMS │ • Key Vault │ • Cloud KMS │\n│ • WAF │ • WAF │ • Cloud Armor │\n│ • VPC Flow Logs │ • NSG Flow Logs │ • VPC Flow Logs │\n└──────────────────┴──────────────────┴──────────────────────┘\n```\n\n### Shared Responsibility Model\n\n**Cloud Provider Responsibilities** (Security OF the cloud):\n- Physical security of data centers\n- Hardware and infrastructure\n- Network infrastructure\n- Hypervisor and virtualization layer\n- Managed service security (e.g., RDS, DynamoDB)\n\n**Customer Responsibilities** (Security IN the cloud):\n- Data encryption and classification\n- Identity and access management (IAM)\n- Application security and patching\n- Network configuration and firewalls\n- Operating system security (for IaaS)\n- Compliance and governance\n\n**Shared Responsibilities** (varies by service model):\n- IaaS (e.g., EC2): Customer manages OS and above\n- PaaS (e.g., App Service): Customer manages application and data\n- SaaS (e.g., Office 365): Customer manages data and access policies\n\n### Cloud Security Best Practices\n\n**Identity & Access Management**:\n```bash\n# Enforce MFA for all users\naws iam create-virtual-mfa-device --virtual-mfa-device-name root-mfa\n\n# Use least privilege IAM policies\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [{\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": \"arn:aws:s3:::my-bucket/specific-prefix/*\"\n }]\n}\n\n# Enable IAM Access Analyzer\naws accessanalyzer create-analyzer --analyzer-name my-analyzer --type ACCOUNT\n\n# Rotate access keys regularly (max 90 days)\naws iam update-access-key --access-key-id AKIAIOSFODNN7EXAMPLE --status Inactive\n```\n\n**Data Encryption**:\n```bash\n# Enable S3 bucket encryption by default\naws s3api put-bucket-encryption \\\n --bucket my-bucket \\\n --server-side-encryption-configuration '{\n \"Rules\": [{\n \"ApplyServerSideEncryptionByDefault\": {\n \"SSEAlgorithm\": \"aws:kms\",\n \"KMSMasterKeyID\": \"arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012\"\n },\n \"BucketKeyEnabled\": true\n }]\n }'\n\n# Enable EBS encryption by default\naws ec2 enable-ebs-encryption-by-default --region us-east-1\n\n# Enable RDS encryption at rest\naws rds create-db-instance \\\n --db-instance-identifier mydb \\\n --storage-encrypted \\\n --kms-key-id arn:aws:kms:us-east-1:123456789012:key/12345678\n```\n\n**Network Security**:\n```bash\n# Create security group with minimal access\naws ec2 create-security-group \\\n --group-name my-app-sg \\\n --description \"App tier security group\" \\\n --vpc-id vpc-12345678\n\n# Only allow traffic from specific sources\naws ec2 authorize-security-group-ingress \\\n --group-id sg-12345678 \\\n --protocol tcp \\\n --port 443 \\\n --source-group sg-87654321 # Only from load balancer SG\n\n# Enable VPC Flow Logs\naws ec2 create-flow-logs \\\n --resource-type VPC \\\n --resource-ids vpc-12345678 \\\n --traffic-type ALL \\\n --log-destination-type s3 \\\n --log-destination arn:aws:s3:::my-flow-logs-bucket\n```\n\n**Monitoring & Logging**:\n```bash\n# Enable CloudTrail for all regions\naws cloudtrail create-trail \\\n --name my-trail \\\n --s3-bucket-name my-cloudtrail-bucket \\\n --is-multi-region-trail\n\n# Enable GuardDuty\naws guardduty create-detector --enable\n\n# Enable AWS Config\naws configservice put-configuration-recorder \\\n --configuration-recorder name=default,roleARN=arn:aws:iam::123456789012:role/config-role\n```\n\n### Container Security Architecture\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Build Time Security │\n│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │\n│ │ Base Image │→ │ Vulnerability│→ │ Image │ │\n│ │ Scanning │ │ Scanning │ │ Signing │ │\n│ └──────────────┘ └──────────────┘ └──────────────┘ │\n│ Tools: Trivy, Snyk, Clair, Anchore │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Registry Security │\n│ • Private registries (ECR, ACR, GCR, Harbor) │\n│ • Image signing and verification (Cosign, Notary) │\n│ • Access control (IAM, RBAC) │\n│ • Vulnerability scanning on push │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Runtime Security │\n│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │\n│ │ Admission │ │ Runtime │ │ Network │ │\n│ │ Control │ │ Protection │ │ Policies │ │\n│ └──────────────┘ └──────────────┘ └──────────────┘ │\n│ Tools: OPA, Falco, Sysdig, Calico │\n└─────────────────────────────────────────────────────────────┘\n```\n\n**Kubernetes Security Best Practices**:\n\n```yaml\n# 1. Use Pod Security Standards\napiVersion: v1\nkind: Namespace\nmetadata:\n name: production\n labels:\n pod-security.kubernetes.io/enforce: restricted\n pod-security.kubernetes.io/audit: restricted\n pod-security.kubernetes.io/warn: restricted\n\n# 2. Run containers as non-root\napiVersion: v1\nkind: Pod\nmetadata:\n name: secure-pod\nspec:\n securityContext:\n runAsNonRoot: true\n runAsUser: 1000\n fsGroup: 1000\n containers:\n - name: app\n image: myapp:1.0\n securityContext:\n allowPrivilegeEscalation: false\n capabilities:\n drop:\n - ALL\n readOnlyRootFilesystem: true\n\n# 3. Use Network Policies\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n name: app-network-policy\nspec:\n podSelector:\n matchLabels:\n app: web\n policyTypes:\n - Ingress\n - Egress\n ingress:\n - from:\n - podSelector:\n matchLabels:\n app: loadbalancer\n ports:\n - protocol: TCP\n port: 8080\n egress:\n - to:\n - podSelector:\n matchLabels:\n app: database\n ports:\n - protocol: TCP\n port: 5432\n\n# 4. Use Resource Limits\napiVersion: v1\nkind: Pod\nmetadata:\n name: resource-limited-pod\nspec:\n containers:\n - name: app\n image: myapp:1.0\n resources:\n limits:\n cpu: \"1\"\n memory: \"512Mi\"\n requests:\n cpu: \"500m\"\n memory: \"256Mi\"\n\n# 5. Enable audit logging\napiVersion: audit.k8s.io/v1\nkind: Policy\nrules:\n- level: Metadata\n resources:\n - group: \"\"\n resources: [\"secrets\", \"configmaps\"]\n- level: RequestResponse\n users: [\"system:serviceaccount:kube-system:*\"]\n```\n\n---\n\n## Data Security Architecture\n\n### Data Classification Framework\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Level 4: Highly Confidential (Top Secret) │\n│ • National security information │\n│ • Encryption: AES-256, encryption at rest AND in transit │\n│ • Access: Named individuals only, MFA + biometric │\n│ • Storage: Air-gapped systems, hardware encryption │\n│ • Retention: Indefinite or per legal requirements │\n└─────────────────────────────────────────────────────────────┘\n┌─────────────────────────────────────────────────────────────┐\n│ Level 3: Confidential (Restricted) │\n│ • PII, PHI, financial data, trade secrets │\n│ • Encryption: AES-256, encryption at rest and in transit │\n│ • Access: Role-based, MFA required, annual certification │\n│ • Storage: Encrypted databases, secure file shares │\n│ • Retention: Per compliance requirements (7 years) │\n└─────────────────────────────────────────────────────────────┘\n┌─────────────────────────────────────────────────────────────┐\n│ Level 2: Internal Use Only │\n│ • Internal documents, employee data, project plans │\n│ • Encryption: TLS in transit, optional at rest │\n│ • Access: All employees, SSO authentication │\n│ • Storage: Corporate file shares, intranet │\n│ • Retention: 3-5 years │\n└─────────────────────────────────────────────────────────────┘\n┌─────────────────────────────────────────────────────────────┐\n│ Level 1: Public │\n│ • Marketing materials, published documentation │\n│ • Encryption: Optional │\n│ • Access: Public │\n│ • Storage: Public website, public repositories │\n│ • Retention: Indefinite │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### Encryption Architecture\n\n**Encryption at Rest**:\n\n```\nApplication Layer Encryption (ALE)\n↓\nDatabase Layer Encryption (TDE - Transparent Data Encryption)\n↓\nFile System Encryption (dm-crypt, BitLocker, FileVault)\n↓\nDisk/Volume Encryption (LUKS, BitLocker)\n↓\nHardware Encryption (Self-Encrypting Drives - SEDs)\n```\n\n**Encryption in Transit**:\n\n```python\n# TLS 1.3 configuration (nginx)\nssl_protocols TLSv1.3;\nssl_ciphers 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256';\nssl_prefer_server_ciphers on;\nssl_session_cache shared:SSL:10m;\nssl_session_timeout 10m;\n\n# HSTS header (force HTTPS)\nadd_header Strict-Transport-Security \"max-age=31536000; includeSubDomains; preload\" always;\n\n# Certificate pinning (optional, advanced)\nadd_header Public-Key-Pins 'pin-sha256=\"base64+primary==\"; pin-sha256=\"base64+backup==\"; max-age=5184000; includeSubDomains';\n```\n\n**Key Management Architecture**:\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Key Management Service (KMS) │\n│ │\n│ ┌──────────────────────────────────────────────────────┐ │\n│ │ Master Keys (Customer Master Keys - CMKs) │ │\n│ │ - Stored in Hardware Security Module (HSM) │ │\n│ │ - Never leave HSM in plaintext │ │\n│ │ - Used to encrypt Data Encryption Keys (DEKs) │ │\n│ └──────────────────────────────────────────────────────┘ │\n│ ↓ │\n│ ┌──────────────────────────────────────────────────────┐ │\n│ │ Data Encryption Keys (DEKs) │ │\n│ │ - Generated per object/database/volume │ │\n│ │ - Encrypted by CMK (envelope encryption) │ │\n│ │ - Stored alongside encrypted data │ │\n│ └──────────────────────────────────────────────────────┘ │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Encrypted Data │\n│ - Application databases │\n│ - File storage │\n│ - Backups │\n└─────────────────────────────────────────────────────────────┘\n```\n\n**Envelope Encryption Example (AWS KMS)**:\n\n```python\nimport boto3\nimport base64\n\nkms_client = boto3.client('kms')\n\n# Generate data encryption key\nresponse = kms_client.generate_data_key(\n KeyId='arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012',\n KeySpec='AES_256'\n)\n\n# Plaintext DEK (use to encrypt data, then discard)\nplaintext_dek = response['Plaintext']\n\n# Encrypted DEK (store alongside encrypted data)\nencrypted_dek = response['CiphertextBlob']\n\n# Encrypt data with plaintext DEK\nfrom cryptography.fernet import Fernet\ncipher = Fernet(base64.urlsafe_b64encode(plaintext_dek))\nencrypted_data = cipher.encrypt(b\"Sensitive data\")\n\n# Store encrypted_data and encrypted_dek together\n# Discard plaintext_dek from memory\n\n# To decrypt later:\n# 1. Decrypt the DEK using KMS\ndecrypt_response = kms_client.decrypt(CiphertextBlob=encrypted_dek)\nplaintext_dek_decrypted = decrypt_response['Plaintext']\n\n# 2. Use DEK to decrypt data\ncipher = Fernet(base64.urlsafe_b64encode(plaintext_dek_decrypted))\ndecrypted_data = cipher.decrypt(encrypted_data)\n```\n\n### Data Loss Prevention (DLP) Architecture\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Data Discovery & Classification │\n│ • Scan repositories for sensitive data (PII, PHI, PCI) │\n│ • Apply classification labels automatically │\n│ • Tools: Microsoft Purview, Varonis, BigID │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Policy Enforcement Points │\n│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │\n│ │ Endpoint │ │ Network │ │ Cloud │ │\n│ │ DLP │ │ DLP │ │ DLP │ │\n│ └──────────────┘ └──────────────┘ └──────────────┘ │\n│ • Block file transfers with PII │\n│ • Prevent copy/paste of sensitive data │\n│ • Encrypt emails containing confidential data │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Monitoring & Alerting │\n│ • Log DLP policy violations │\n│ • Alert security team for high-risk events │\n│ • User education on policy violations │\n└─────────────────────────────────────────────────────────────┘\n```\n\n**DLP Policy Example**:\n\n```yaml\npolicy:\n name: \"Prevent PII Exfiltration\"\n description: \"Block transfer of SSNs via email or cloud storage\"\n\n content_detection:\n - type: pattern\n pattern: '\\d{3}-\\d{2}-\\d{4}' # SSN pattern\n confidence: high\n - type: keyword\n keywords: [\"SSN\", \"Social Security Number\"]\n proximity: 50 # characters\n\n actions:\n email:\n - block_send\n - encrypt_if_internal\n - notify_sender\n - alert_security_team\n\n cloud_storage:\n - block_upload\n - notify_user\n - log_incident\n\n endpoint:\n - block_copy_to_usb\n - block_print\n - allow_with_justification\n\n exceptions:\n - group: \"HR Department\"\n action: allow_with_audit\n - application: \"Payroll System\"\n action: allow\n```\n\n---\n\n## Identity & Access Management (IAM) Architecture\n\n### Authentication Architecture\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Identity Provider (IdP) │\n│ • Okta, Azure AD, Auth0, Google Workspace │\n│ • Central user directory (LDAP, AD) │\n│ • MFA enforcement │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Authentication Protocol │\n│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │\n│ │ SAML │ │ OAuth │ │ OIDC │ │\n│ │ 2.0 │ │ 2.0 │ │ (OpenID │ │\n│ │ │ │ │ │ Connect) │ │\n│ └──────────────┘ └──────────────┘ └──────────────┘ │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Applications & Services │\n│ • SaaS applications (Service Provider in SAML) │\n│ • Internal web applications │\n│ • APIs (OAuth 2.0 protected) │\n│ • Infrastructure (SSH, RDP via certificates) │\n└─────────────────────────────────────────────────────────────┘\n```\n\n**Multi-Factor Authentication (MFA) Methods**:\n\n```\nTier 1 (Most Secure):\n├─ Hardware Security Keys (FIDO2/WebAuthn: YubiKey, Titan)\n├─ Biometric (Face ID, Touch ID, Windows Hello)\n└─ Smart Cards with PKI\n\nTier 2 (Secure):\n├─ Authenticator Apps (TOTP: Google Authenticator, Authy)\n├─ Push Notifications (Duo, Okta Verify)\n└─ Mobile Device Certificates\n\nTier 3 (Less Secure, Avoid):\n├─ SMS One-Time Passcodes (vulnerable to SIM swapping)\n└─ Email Codes\n```\n\n### Authorization Models\n\n**Role-Based Access Control (RBAC)**:\n\n```yaml\n# Example: Enterprise application RBAC\nroles:\n - name: \"Admin\"\n permissions:\n - \"users:read\"\n - \"users:write\"\n - \"users:delete\"\n - \"settings:write\"\n - \"audit_logs:read\"\n\n - name: \"Manager\"\n permissions:\n - \"users:read\"\n - \"users:write\"\n - \"reports:read\"\n - \"reports:write\"\n\n - name: \"User\"\n permissions:\n - \"users:read_self\"\n - \"reports:read\"\n\n# User assignment\nusers:\n - email: \"[email protected]\"\n roles: [\"Admin\"]\n\n - email: \"[email protected]\"\n roles: [\"Manager\"]\n\n - email: \"[email protected]\"\n roles: [\"User\"]\n```\n\n**Attribute-Based Access Control (ABAC)**:\n\n```json\n{\n \"policy\": \"Allow read access to medical records\",\n \"effect\": \"Allow\",\n \"principal\": {\n \"attributes\": {\n \"department\": \"Healthcare\",\n \"role\": \"Doctor\",\n \"clearance_level\": \">=3\"\n }\n },\n \"resource\": {\n \"type\": \"MedicalRecord\",\n \"attributes\": {\n \"sensitivity\": \"High\"\n }\n },\n \"action\": \"read\",\n \"conditions\": {\n \"time_of_day\": \"business_hours\",\n \"location\": \"on_premises OR vpn_connected\",\n \"device_compliance\": \"compliant\"\n }\n}\n```\n\n**Relationship-Based Access Control (ReBAC)**:\n\n```python\n# Example: Document sharing platform\n# \"User can edit a document if they are the owner OR a collaborator\"\n\nrelationships = {\n \"document:123\": {\n \"owner\": \"user:alice\",\n \"collaborators\": [\"user:bob\", \"user:charlie\"]\n }\n}\n\ndef can_edit(user, document):\n doc_rels = relationships.get(document)\n return (\n user == doc_rels[\"owner\"] or\n user in doc_rels[\"collaborators\"]\n )\n\n# Using authorization service like Ory Keto or SpiceDB\n# Tuple format: \u003cobject>#\u003crelation>@\u003csubject>\n# \"document:123#owner@user:alice\"\n# \"document:123#collaborator@user:bob\"\n```\n\n### Privileged Access Management (PAM)\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Just-In-Time (JIT) Access │\n│ 1. User requests elevated access via portal │\n│ 2. Manager approves (or auto-approved if policy allows) │\n│ 3. User granted access for limited time (e.g., 4 hours) │\n│ 4. Access automatically revoked after time expires │\n│ 5. Session is recorded for audit │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Privileged Access Workstation (PAW) │\n│ • Hardened jump server / bastion host │\n│ • No internet access │\n│ • MFA required to access │\n│ • All sessions recorded │\n│ • Credential rotation after each session │\n└─────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────┐\n│ Target Systems │\n│ • Production databases │\n│ • Cloud admin consoles │\n│ • Network infrastructure │\n│ • Domain controllers │\n└─────────────────────────────────────────────────────────────┘\n```\n\n**PAM Best Practices**:\n\n1. **Eliminate standing privileges**: Use JIT access instead of permanent admin rights\n2. **Rotate credentials**: Auto-rotate privileged passwords after each session\n3. **Session monitoring**: Record all privileged sessions for audit and forensics\n4. **Break-glass procedures**: Emergency access when PAM is unavailable\n5. **Separate admin accounts**: Never use privileged accounts for regular tasks\n6. **Remove local admin rights**: Users should not have admin on their workstations\n\n---\n\n## Secure Software Development Lifecycle (SDLC)\n\nSee [application-security.md](./application-security.md) for detailed coverage of secure SDLC, DevSecOps, and application security practices.\n\n---\n\n## Security Architecture Review Checklist\n\n### Network Architecture Review\n- [ ] Network segmentation properly implemented (DMZ, app tier, data tier)\n- [ ] Firewall rules follow least privilege (deny by default)\n- [ ] No overly permissive security groups (0.0.0.0/0)\n- [ ] VPN or ZTNA for remote access (no direct RDP/SSH from internet)\n- [ ] Network traffic logging enabled (VPC Flow Logs, NSG Flow Logs)\n- [ ] DDoS protection enabled for public-facing services\n- [ ] WAF deployed for web applications\n- [ ] IDS/IPS deployed and tuned\n\n### Identity & Access Review\n- [ ] MFA enforced for all users\n- [ ] Privileged access managed (PAM solution in place)\n- [ ] No shared accounts or default credentials\n- [ ] Regular access reviews and certifications conducted\n- [ ] Least privilege access enforced (RBAC/ABAC)\n- [ ] Service accounts have minimal permissions\n- [ ] SSO implemented for applications\n- [ ] Password policy enforces complexity and rotation\n\n### Data Protection Review\n- [ ] Data classified and labeled\n- [ ] Encryption at rest for sensitive data (AES-256)\n- [ ] Encryption in transit (TLS 1.2+)\n- [ ] Key management using KMS or HSM\n- [ ] DLP policies enforced\n- [ ] Database activity monitoring enabled\n- [ ] Backups encrypted and tested regularly\n- [ ] Data retention policies enforced\n\n### Cloud Security Review\n- [ ] Cloud Security Posture Management (CSPM) enabled\n- [ ] Security services enabled (GuardDuty, Security Hub, Defender)\n- [ ] S3 buckets not publicly accessible (unless required)\n- [ ] CloudTrail/Activity Log enabled for all regions\n- [ ] Automated remediation for misconfigurations\n- [ ] Container images scanned for vulnerabilities\n- [ ] Secrets not hardcoded in code or config\n- [ ] Infrastructure as Code (IaC) security scanned\n\n### Monitoring & Detection Review\n- [ ] SIEM deployed and ingesting logs\n- [ ] Critical security events generate alerts\n- [ ] Log retention meets compliance requirements (typically 1 year)\n- [ ] EDR deployed on all endpoints\n- [ ] Network traffic monitored for anomalies\n- [ ] Threat intelligence feeds integrated\n- [ ] Regular threat hunting performed\n- [ ] Security metrics tracked and reported\n\n### Incident Response Review\n- [ ] Incident response plan documented and tested\n- [ ] Incident response team (CIRT) identified\n- [ ] Playbooks created for common scenarios\n- [ ] Forensic capabilities available\n- [ ] Communication plan for breaches\n- [ ] Regulatory notification procedures documented\n- [ ] Tabletop exercises conducted annually\n- [ ] Lessons learned process in place\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":45301,"content_sha256":"8ae471c1297bd776591d65f55cff6637a9c9284b1f72e93ad798fae52512aa1b"},{"filename":"reference/security-operations.md","content":"# Security Operations & Incident Response\n\n## Security Operations Center (SOC)\n\n### SOC Structure\n\n```\nTier 1: Alert Triage (L1 Analyst)\n├─ Monitor SIEM dashboards and security alerts\n├─ Perform initial triage and classification\n├─ Escalate confirmed incidents to Tier 2\n├─ Document all activities in ticketing system\n└─ Response Time: 15 minutes for critical alerts\n\nTier 2: Incident Investigation (L2 Analyst)\n├─ Deep investigation of escalated incidents\n├─ Contain threats and perform forensic analysis\n├─ Coordinate with IT teams for remediation\n├─ Escalate to Tier 3 for complex threats\n└─ Response Time: 1 hour for critical incidents\n\nTier 3: Threat Hunting & Advanced Analysis (L3 Analyst)\n├─ Proactive threat hunting\n├─ Advanced forensics and malware analysis\n├─ Create custom detection rules\n├─ Research emerging threats\n└─ Mentor junior analysts\n\nSOC Manager\n├─ Oversee SOC operations\n├─ Manage team performance and training\n├─ Report metrics to leadership\n├─ Coordinate with other departments\n└─ Budget and resource planning\n```\n\n### SIEM Configuration\n\n**Log Sources to Ingest**:\n\n```\nCritical Priority (Real-time):\n├─ Firewall logs (allow/deny, connections)\n├─ IDS/IPS alerts\n├─ EDR/antivirus alerts\n├─ Authentication logs (successes and failures)\n├─ VPN connections\n├─ Privileged account activity\n└─ Database access logs (for sensitive data)\n\nHigh Priority (Near real-time, \u003c5 min delay):\n├─ Web application logs (access, errors)\n├─ Cloud infrastructure logs (AWS CloudTrail, Azure Activity)\n├─ Email gateway logs (spam, malware detection)\n├─ DLP alerts\n└─ File integrity monitoring\n\nMedium Priority (15-30 min delay):\n├─ Application logs\n├─ DNS query logs\n├─ Proxy logs\n├─ Network flow data (NetFlow/IPFIX)\n└─ Patch management logs\n\nLow Priority (Hourly or daily):\n├─ Backup logs\n├─ System performance metrics\n└─ Non-security application logs\n```\n\n**Essential SIEM Use Cases**:\n\n```yaml\n# 1. Brute Force Attack Detection\nuse_case: \"Detect brute force login attempts\"\ndata_sources:\n - Windows Security Event Logs (Event ID 4625)\n - Linux auth logs\n - VPN logs\n - Application authentication logs\n\ndetection_logic: |\n More than 10 failed login attempts\n FROM same source IP\n TO same user account\n WITHIN 5-minute window\n\nactions:\n - Alert: High severity\n - Block source IP (automatic via firewall integration)\n - Notify account owner\n - Create incident ticket\n\n# 2. Unusual Privileged Account Activity\nuse_case: \"Detect anomalous admin account usage\"\ndata_sources:\n - Active Directory logs\n - Unix/Linux sudo logs\n - PAM session logs\n\ndetection_logic: |\n Privileged account login\n OUTSIDE business hours (8 AM - 6 PM)\n OR FROM unusual location\n OR ON unusual system\n\nactions:\n - Alert: Critical severity\n - Require MFA step-up authentication\n - Notify security team and account owner\n - Create incident ticket\n\n# 3. Data Exfiltration Detection\nuse_case: \"Detect large outbound data transfers\"\ndata_sources:\n - Firewall logs\n - Proxy logs\n - DLP alerts\n - Cloud storage logs\n\ndetection_logic: |\n Outbound data transfer > 1 GB\n TO external destination\n FROM single user/system\n WITHIN 1-hour window\n\nactions:\n - Alert: High severity\n - Block connection if still active\n - Investigate user/system activity\n - Check for data classification violations\n\n# 4. Malware Detection\nuse_case: \"Detect malware execution\"\ndata_sources:\n - EDR alerts\n - Antivirus logs\n - Process execution logs (Sysmon)\n - Network connections\n\ndetection_logic: |\n Malware signature match\n OR suspicious process execution (PowerShell obfuscation)\n OR connection to known C2 IP\n OR file hash matches threat intelligence\n\nactions:\n - Alert: Critical severity\n - Isolate endpoint from network (EDR integration)\n - Kill malicious process\n - Collect forensic artifacts\n - Create incident ticket\n\n# 5. Insider Threat - Abnormal File Access\nuse_case: \"Detect abnormal access to sensitive files\"\ndata_sources:\n - File server audit logs\n - Database query logs\n - SharePoint access logs\n\ndetection_logic: |\n User accesses > 100 files\n CONTAINING sensitive data (SSN, credit card, PHI)\n WITHIN 1-hour window\n WHERE user has no recent history of accessing these files\n\nactions:\n - Alert: High severity\n - Notify manager and security team\n - Investigate user activity\n - Check for USB device insertion\n - Review data transfer logs\n```\n\n### Threat Hunting\n\n**Threat Hunting Process**:\n\n```\n1. Hypothesis Generation\n ├─ Based on threat intelligence (e.g., \"APT group targeting our industry\")\n ├─ Based on recent attacks (e.g., \"Check for Log4Shell exploitation attempts\")\n └─ Based on anomalies (e.g., \"Unusual PowerShell activity in environment\")\n\n2. Investigation\n ├─ Query SIEM and EDR for indicators\n ├─ Analyze logs for suspicious patterns\n ├─ Review network traffic\n └─ Examine endpoint artifacts\n\n3. Discovery\n ├─ Confirm presence or absence of threat\n ├─ Document findings\n └─ Assess impact if threat found\n\n4. Response\n ├─ Containment and eradication if threat confirmed\n ├─ Create detection rule for future prevention\n └─ Share findings with team\n\n5. Continuous Improvement\n ├─ Update threat intelligence\n ├─ Refine detection rules\n └─ Document lessons learned\n```\n\n**Example Threat Hunt: Living Off the Land (LOLBins)**\n\n```bash\n# Hypothesis: Attackers using native Windows tools for malicious activity\n\n# Hunt 1: Suspicious PowerShell execution\n# SIEM query to find encoded PowerShell commands\nindex=windows EventCode=4688\nNewProcessName=\"*powershell.exe\"\nCommandLine=\"*-enc*\" OR CommandLine=\"*-encodedcommand*\"\n| stats count by Computer, User, CommandLine\n| where count > 0\n\n# Hunt 2: Unusual certutil usage (commonly used to download malware)\nindex=windows EventCode=4688\nNewProcessName=\"*certutil.exe\"\nCommandLine=\"*-urlcache*\" OR CommandLine=\"*-decode*\"\n| stats count by Computer, User, CommandLine\n\n# Hunt 3: WMIC used for lateral movement\nindex=windows EventCode=4688\nNewProcessName=\"*wmic.exe\"\nCommandLine=\"*/node:*\"\n| stats count by Computer, User, CommandLine\n\n# Hunt 4: BITSAdmin downloading files\nindex=windows EventCode=4688\nNewProcessName=\"*bitsadmin.exe\"\nCommandLine=\"*/transfer*\"\n| stats count by Computer, User, CommandLine\n\n# Hunt 5: Malicious use of regsvr32\nindex=windows EventCode=4688\nNewProcessName=\"*regsvr32.exe\"\nCommandLine=\"*/s*\" AND CommandLine=\"*http*\"\n| stats count by Computer, User, CommandLine\n```\n\n---\n\n## Incident Response\n\n### Incident Response Lifecycle\n\n```\n1. Preparation\n ↓\n2. Detection & Analysis\n ↓\n3. Containment\n ↓\n4. Eradication\n ↓\n5. Recovery\n ↓\n6. Post-Incident Activity\n```\n\n### Incident Response Plan Structure\n\n```markdown\n# Incident Response Plan\n\n## 1. Preparation\n\n### Incident Response Team (CIRT)\n\n| Role | Name | Contact | Responsibilities |\n|------|------|---------|-----------------|\n| Incident Commander | Jane Doe | +1-555-0101 | Overall coordination |\n| Security Lead | John Smith | +1-555-0102 | Technical investigation |\n| IT Lead | Bob Johnson | +1-555-0103 | System remediation |\n| Communications | Alice Brown | +1-555-0104 | Internal/external comms |\n| Legal | Carol White | +1-555-0105 | Legal implications |\n| HR | Dave Lee | +1-555-0106 | Insider threats |\n\n### Tools and Resources\n\n- SIEM: Splunk (https://siem.company.com)\n- EDR: CrowdStrike (https://falcon.crowdstrike.com)\n- Ticketing: Jira Service Desk (security-incidents project)\n- Communication: Dedicated Slack channel #incident-response\n- Forensic workstation: Located in SOC, admin laptop with encrypted drive\n- Incident response jump bag: USB with tools, clean OS images, cables\n\n### Contact Information\n\n- Internal IT Help Desk: x5000\n- Security Team On-Call: +1-555-SECURITY\n- Legal Department: [email protected]\n- PR/Communications: [email protected]\n- Cyber Insurance: PolicyCo, +1-800-CYBER-INSURE, Policy #12345\n- External IR Firm: MandiantFire, +1-888-RESPOND\n- Law Enforcement: FBI Cyber Division, Agent Smith, +1-202-555-CYBER\n\n## 2. Detection & Analysis\n\n### Incident Classification\n\n| Severity | Definition | Examples | Response Time |\n|----------|-----------|----------|---------------|\n| P0 - Critical | Active breach, data exfiltration, ransomware | Active data theft, ransomware encryption, complete system compromise | Immediate (24/7) |\n| P1 - High | Confirmed malware, unauthorized access | Malware on critical system, confirmed intrusion | 1 hour |\n| P2 - Medium | Suspicious activity requiring investigation | Potential malware, failed intrusion attempt | 4 hours |\n| P3 - Low | Policy violation, informational | Minor policy violation, phishing email (no click) | 24 hours |\n\n### Initial Assessment Questions\n\nWhen receiving an incident report, gather:\n\n1. **What happened?** (Description of the incident)\n2. **When did it occur?** (Date and time)\n3. **Who discovered it?** (Reporter name and contact)\n4. **Which systems are affected?** (Hostnames, IP addresses)\n5. **What is the current status?** (Ongoing, contained, resolved)\n6. **What data is at risk?** (PII, PHI, financial, IP)\n7. **Has law enforcement been notified?** (Yes/No)\n8. **What immediate actions were taken?** (System isolated, account disabled)\n\n### Incident Documentation\n\nCreate ticket in Jira with:\n- Incident ID (auto-generated)\n- Classification (P0-P3)\n- Timeline of events\n- Systems affected\n- Actions taken\n- Evidence collected\n- Next steps\n\n## 3. Containment\n\n### Short-term Containment (Stop the Bleeding)\n\n**Network-Based Containment**:\n```bash\n# Isolate compromised system (via firewall)\n# Block inbound and outbound traffic except to/from SOC analyst workstation\niptables -A INPUT -s \u003cSOC_IP> -j ACCEPT\niptables -A OUTPUT -d \u003cSOC_IP> -j ACCEPT\niptables -P INPUT DROP\niptables -P OUTPUT DROP\n\n# Block malicious IP at perimeter firewall\n# (Use firewall management interface or API)\n\n# Disable compromised user account\n# Active Directory\nDisable-ADAccount -Identity compromised_user\n\n# Linux\nusermod -L compromised_user\n```\n\n**Endpoint-Based Containment**:\n```bash\n# Using EDR (CrowdStrike example via API)\ncurl -X POST \"https://api.crowdstrike.com/devices/v2/actions/contain\" \\\n -H \"Authorization: Bearer $FALCON_TOKEN\" \\\n -d '{\"ids\": [\"device_id_here\"], \"action_parameters\": []}'\n\n# Kill malicious process\n# Windows\ntaskkill /F /IM malware.exe /T\n\n# Linux\npkill -9 -f malware\n```\n\n**Account-Based Containment**:\n```bash\n# Reset password and revoke sessions\n# Azure AD\nRevoke-AzureADUserAllRefreshToken -ObjectId [email protected]\n\n# Force password change on next login\nSet-ADUser -Identity compromised_user -ChangePasswordAtLogon $true\n\n# Disable API keys/tokens\n# (Application-specific, e.g., AWS IAM)\naws iam delete-access-key --user-name compromised_user --access-key-id AKIA...\n```\n\n### Long-term Containment\n\n- Patch vulnerable systems\n- Implement compensating controls (WAF rules, additional monitoring)\n- Rebuild compromised systems from clean images\n- Update detection rules to prevent recurrence\n\n## 4. Eradication\n\n### Malware Removal\n\n```bash\n# Identify all affected systems\n# Search EDR for same malware hash or C2 communications\n\n# Remove malware from each system\n# Preferred: Reimage from clean backup\n# If reimaging not possible:\n# - Use EDR to quarantine/delete malicious files\n# - Remove persistence mechanisms (registry, scheduled tasks, services)\n# - Clear cached credentials\n\n# Windows: Remove scheduled task\nschtasks /Delete /TN \"Malicious Task\" /F\n\n# Windows: Remove registry persistence\nreg delete \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\" /v \"Malware\" /f\n\n# Linux: Remove cron job\ncrontab -e # Remove malicious line\n```\n\n### Vulnerability Remediation\n\n```bash\n# Patch vulnerable systems\n# Ubuntu/Debian\napt-get update && apt-get upgrade -y\n\n# RHEL/CentOS\nyum update -y\n\n# Windows (via PowerShell)\nInstall-WindowsUpdate -AcceptAll -AutoReboot\n\n# Application-specific (e.g., Log4Shell)\n# Upgrade Log4j to 2.17.1+\n# Set JVM option: -Dlog4j2.formatMsgNoLookups=true\n```\n\n### Credential Reset\n\n```bash\n# Force password reset for all potentially compromised accounts\n# Generate list of users who logged in during breach window\n\n# Bulk password reset (Azure AD example)\n$users = Get-AzureADUser -All $true | Where-Object {$_.UserPrincipalName -like \"*@company.com\"}\nforeach ($user in $users) {\n Set-AzureADUser -ObjectId $user.ObjectId -PasswordPolicies \"DisablePasswordExpiration\" -Password (ConvertTo-SecureString \"TempPassword123!\" -AsPlainText -Force)\n Set-AzureADUser -ObjectId $user.ObjectId -ForceChangePasswordNextLogin $true\n}\n\n# Rotate service account credentials\n# Rotate API keys and tokens\n# Rotate database passwords\n# Rotate encryption keys (where feasible)\n```\n\n## 5. Recovery\n\n### System Restoration\n\n```bash\n# Restore from clean backup (verified malware-free)\n# Validate backup integrity\nsha256sum backup.tar.gz\n# Compare to known good hash\n\n# Restore data\ntar -xzf backup.tar.gz -C /restore/location\n\n# Rebuild from golden image (preferred for compromised systems)\n# Deploy fresh OS from trusted source\n# Apply all patches\n# Reinstall applications\n# Restore data only (not configurations that may contain backdoors)\n```\n\n### Validation Testing\n\nBefore returning systems to production:\n\n```\n□ Antivirus/EDR scan shows clean\n□ No outbound connections to malicious IPs\n□ File integrity monitoring shows no unexpected changes\n□ No unauthorized user accounts or scheduled tasks\n□ All patches applied\n□ Passwords rotated\n□ System logs reviewed for anomalies\n□ Functionality testing completed\n□ Monitoring/alerting configured\n```\n\n### Return to Normal Operations\n\n- Gradual restoration (not all systems at once)\n- Enhanced monitoring for 30 days post-incident\n- User communication about password resets\n- Document all changes made\n\n## 6. Post-Incident Activity\n\n### Post-Incident Review (PIR)\n\n**Within 5 business days of incident closure, conduct PIR meeting**\n\nAttendees: CIRT members, affected business units, leadership\n\nAgenda:\n1. Incident timeline review\n2. What went well?\n3. What could be improved?\n4. Root cause analysis\n5. Action items for improvement\n\n### Incident Report Template\n\n```markdown\n# Incident Report: [Incident ID]\n\n## Executive Summary\nBrief non-technical summary of what happened, impact, and resolution.\n\n## Incident Details\n- **Incident ID**: INC-2025-001\n- **Severity**: P1 (High)\n- **Detected**: 2025-01-15 14:23 UTC\n- **Contained**: 2025-01-15 16:45 UTC\n- **Resolved**: 2025-01-17 10:00 UTC\n- **Total Duration**: 44 hours\n\n## Timeline\n| Time (UTC) | Event |\n|-----------|-------|\n| 2025-01-15 14:23 | SIEM alert: Unusual outbound traffic from web server |\n| 2025-01-15 14:30 | Analyst confirms malware on web-01.company.com |\n| 2025-01-15 14:45 | Server isolated from network |\n| 2025-01-15 15:00 | CIRT activated, incident commander assigned |\n| 2025-01-15 16:00 | Root cause identified: Unpatched Log4Shell vuln |\n| 2025-01-15 16:45 | All vulnerable servers patched and restarted |\n| 2025-01-16 09:00 | Forensic analysis completed |\n| 2025-01-17 10:00 | Systems restored, monitoring in place, incident closed |\n\n## Root Cause\nApache web server running vulnerable version of Log4j (2.14.1) was exploited\nvia crafted HTTP User-Agent header. Patch released on 2021-12-10 was not\napplied due to lack of automated patch management.\n\n## Impact Assessment\n- **Systems Affected**: 3 web servers (web-01, web-02, web-03)\n- **Data Compromised**: None confirmed\n- **Downtime**: 12 hours (web services offline during remediation)\n- **Financial Impact**: Estimated $50,000 (12 hours downtime × $4,200/hour)\n- **Customers Affected**: None (no data breach)\n- **Regulatory**: No breach notification required\n\n## Actions Taken\n1. Isolated affected servers from network\n2. Captured forensic images\n3. Analyzed malware (CobaltStrike beacon)\n4. Identified 3 vulnerable systems\n5. Patched Log4j on all servers\n6. Rebuilt servers from clean images\n7. Deployed WAF rule to block exploit attempts\n8. Reset all service account passwords\n\n## Lessons Learned\n\n### What Went Well\n- SIEM alert fired immediately\n- CIRT responded within 15 minutes\n- Isolation prevented lateral movement\n- Backups were recent and intact\n\n### What Could Be Improved\n- Patch management process too slow (vulnerability was 1 month old)\n- No vulnerability scanning for application dependencies\n- Incident response playbook for ransomware needed update\n\n## Recommendations\n1. **Implement automated patch management** (Priority: High, Owner: IT, Due: 2025-02-15)\n - Deploy Patch Manager to automate patching\n - SLA: Critical patches within 7 days\n\n2. **Add SCA scanning to CI/CD** (Priority: High, Owner: AppSec, Due: 2025-02-28)\n - Use Snyk or similar to scan for vulnerable dependencies\n - Block deployments with critical vulnerabilities\n\n3. **Update incident response playbooks** (Priority: Medium, Owner: Security, Due: 2025-03-15)\n - Add ransomware playbook\n - Add supply chain attack playbook\n - Conduct tabletop exercise\n\n4. **Enhance vulnerability scanning** (Priority: Medium, Owner: Security, Due: 2025-03-01)\n - Configure Nessus to scan for application vulnerabilities\n - Integrate with vulnerability management workflow\n\n## Regulatory Reporting\n- **GDPR Breach Notification**: Not required (no personal data compromised)\n- **State Breach Laws**: Not required\n- **Cyber Insurance**: Notified on 2025-01-15, claim filed\n\n## Sign-off\n- **Incident Commander**: Jane Doe, 2025-01-18\n- **CISO**: John Smith, 2025-01-18\n```\n\n---\n\n## Security Metrics & KPIs\n\n### SOC Metrics\n\n```yaml\nDetection Metrics:\n - name: \"Mean Time to Detect (MTTD)\"\n formula: \"Time from incident occurrence to detection\"\n target: \"\u003c1 hour for critical incidents\"\n measurement: \"Automated via SIEM\"\n\n - name: \"Alert Volume\"\n formula: \"Total alerts per day/week/month\"\n target: \"Trending down (improving signal-to-noise)\"\n measurement: \"SIEM dashboard\"\n\n - name: \"False Positive Rate\"\n formula: \"(False positives / Total alerts) × 100\"\n target: \"\u003c20%\"\n measurement: \"Track in ticketing system\"\n\nResponse Metrics:\n - name: \"Mean Time to Respond (MTTR)\"\n formula: \"Time from detection to initial response\"\n target: \"P0: \u003c15 min, P1: \u003c1 hour, P2: \u003c4 hours\"\n measurement: \"Ticket timestamps\"\n\n - name: \"Mean Time to Contain (MTTC)\"\n formula: \"Time from detection to containment\"\n target: \"P0: \u003c1 hour, P1: \u003c4 hours\"\n measurement: \"Ticket timestamps\"\n\n - name: \"Mean Time to Resolve (MTTR)\"\n formula: \"Time from detection to incident closure\"\n target: \"P0: \u003c72 hours, P1: \u003c7 days\"\n measurement: \"Ticket timestamps\"\n\nEffectiveness Metrics:\n - name: \"Incidents by Severity\"\n formula: \"Count of P0/P1/P2/P3 incidents per month\"\n target: \"Zero P0, minimal P1 incidents\"\n measurement: \"Ticket reports\"\n\n - name: \"Repeat Incidents\"\n formula: \"(Repeat incidents / Total incidents) × 100\"\n target: \"\u003c5%\"\n measurement: \"Track root causes in tickets\"\n\n - name: \"SLA Compliance\"\n formula: \"(Incidents meeting SLA / Total incidents) × 100\"\n target: \">95%\"\n measurement: \"Automated via ticketing system\"\n\nTeam Metrics:\n - name: \"Analyst Utilization\"\n formula: \"Hours on incidents / Total work hours\"\n target: \"60-80% (balance investigation and improvement)\"\n measurement: \"Time tracking\"\n\n - name: \"Training Completion\"\n formula: \"(Analysts completing training / Total analysts) × 100\"\n target: \"100% quarterly\"\n measurement: \"LMS reporting\"\n\n - name: \"Threat Hunts Conducted\"\n formula: \"Number of proactive threat hunts per month\"\n target: \"Minimum 4 hunts per month\"\n measurement: \"Track in project board\"\n```\n\n### Sample SOC Dashboard\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Security Operations Dashboard - January 2025 │\n├─────────────────────────────────────────────────────────────┤\n│ Detection & Response Times │\n│ ┌─────────────┬─────────────┬─────────────┬─────────────┐ │\n│ │ MTTD │ MTTR │ MTTC │ MTT-Resolve │ │\n│ │ 42 min │ 18 min │ 2.1 hours │ 15 hours │ │\n│ │ ↓ 12% MoM │ ↓ 5% MoM │ → 0% MoM │ ↓ 20% MoM │ │\n│ └─────────────┴─────────────┴─────────────┴─────────────┘ │\n│ │\n│ Incident Volume (January 2025) │\n│ ┌─────────────┬─────────────┬─────────────┬─────────────┐ │\n│ │ Critical │ High │ Medium │ Low │ │\n│ │ 2 (P0) │ 12 (P1) │ 45 (P2) │ 87 (P3) │ │\n│ └─────────────┴─────────────┴─────────────┴─────────────┘ │\n│ │\n│ Alert Metrics │\n│ Total Alerts: 15,234 │ False Positives: 2,841 (18.6%) │\n│ True Positives: 146 │ Under Investigation: 23 │\n│ │\n│ Top Attack Vectors │\n│ 1. Phishing (62 incidents) │\n│ 2. Brute force login (31 incidents) │\n│ 3. Malware (18 incidents) │\n│ 4. Vulnerability exploitation (12 incidents) │\n│ 5. Insider threat (2 incidents) │\n│ │\n│ Threat Hunting │\n│ Hunts Conducted: 5 │ Threats Found: 1 │ New Rules: 3 │\n│ │\n│ SLA Compliance: 97.3% (Target: >95%) │\n└─────────────────────────────────────────────────────────────┘\n```\n\n---\n\n## Tabletop Exercises\n\n### Ransomware Tabletop Exercise\n\n**Objective**: Test incident response procedures for ransomware attack\n\n**Duration**: 90 minutes\n\n**Participants**:\n- Incident Commander\n- Security team\n- IT team\n- Legal\n- Communications\n- Executive sponsor\n\n**Scenario**:\n\n```\nWednesday, 9:00 AM:\nThe IT help desk receives multiple calls from users reporting that files are\nencrypted and they see a ransom note demanding $500,000 in Bitcoin.\n\nInitial Investigation:\n- 50+ workstations affected across 3 departments\n- Ransomware appears to be spreading\n- Backup server also appears to be encrypted\n- Ransom note gives 48-hour deadline\n\nYour Task:\nRespond to this incident using your incident response plan.\n```\n\n**Exercise Flow**:\n\n```\nInject 1 (0:00): Initial notification\n- Question: Who do you notify first?\n- Question: What immediate containment actions do you take?\n- Expected: Activate CIRT, isolate network segments, disable VPN\n\nInject 2 (0:15): Scope determination\n- Update: EDR shows 127 affected systems, ransomware is REvil variant\n- Question: How do you determine the full scope?\n- Question: Do you pay the ransom?\n- Expected: Query EDR for all infected systems, check backups, legal consult\n\nInject 3 (0:30): Backup assessment\n- Update: Backup server encrypted, but offline backups from 48 hours ago exist\n- Question: How do you verify backup integrity?\n- Question: What is your recovery strategy?\n- Expected: Test restore from offline backups, prioritize critical systems\n\nInject 4 (0:45): External communication\n- Update: News outlet calls asking about a data breach\n- Question: What do you tell them?\n- Question: Do you need to notify regulators?\n- Expected: Escalate to communications team, assess breach notification requirements\n\nInject 5 (1:00): Recovery decisions\n- Update: Backups verified clean, recovery will take 3-5 days\n- Question: What is your recovery priority order?\n- Question: How do you prevent reinfection?\n- Expected: Restore critical systems first, implement enhanced monitoring, patch vulnerabilities\n\nInject 6 (1:15): Post-incident\n- Question: What improvements are needed to prevent recurrence?\n- Question: What metrics will you track?\n- Expected: Better backup strategy, EDR on all systems, security awareness training\n```\n\n**Facilitator Notes**:\n- Pause after each inject for discussion\n- Ask probing questions to test knowledge\n- Document gaps in procedures or knowledge\n- Create action items for improvements\n\n**After Action Report**:\n\n```markdown\n## Ransomware Tabletop Exercise - After Action Report\n\n### Strengths\n- Team quickly activated CIRT\n- Network isolation performed correctly\n- Good understanding of legal/regulatory requirements\n- Clear communication during exercise\n\n### Areas for Improvement\n1. **Backup Strategy**\n - Current: Backups stored online, vulnerable to ransomware\n - Recommendation: Implement 3-2-1 backup strategy (3 copies, 2 media types, 1 offsite)\n - Owner: IT Manager\n - Due: 2025-03-01\n\n2. **Incident Response Playbook**\n - Current: Generic IR plan, lacks ransomware-specific procedures\n - Recommendation: Create ransomware playbook with decision trees\n - Owner: Security Manager\n - Due: 2025-02-15\n\n3. **Executive Decision Making**\n - Current: Unclear who has authority to approve ransom payment\n - Recommendation: Define authority matrix in IR plan\n - Owner: CISO\n - Due: 2025-02-01\n\n4. **Communication Templates**\n - Current: No pre-approved external communication templates\n - Recommendation: Create templates for customers, media, regulators\n - Owner: Communications Director\n - Due: 2025-02-15\n\n### Next Steps\n- Schedule follow-up tabletop in 6 months\n- Conduct technical drill (actual backup restoration test)\n- Update incident response plan based on lessons learned\n```\n\n---\n\n## Playbooks\n\n### Phishing Email Response Playbook\n\n```markdown\n## Phishing Email Response Playbook\n\n### Trigger\nUser reports suspicious email via \"Report Phishing\" button or to [email protected]\n\n### Severity Classification\n- **P1 (High)**: User clicked link or entered credentials\n- **P2 (Medium)**: User opened attachment\n- **P3 (Low)**: User did not interact with email\n\n### Response Steps\n\n#### Step 1: Triage (Within 15 minutes)\n□ Review reported email\n□ Classify severity (P1/P2/P3)\n□ Check email gateway logs for delivery count\n ```bash\n # Exchange example\n Get-MessageTrace -SenderAddress \"[email protected]\" -StartDate (Get-Date).AddHours(-24)\n ```\n\n#### Step 2: Analysis\n□ Analyze email headers (sender IP, SPF/DKIM/DMARC results)\n□ Check URLs in email (use URL sandbox like urlscan.io)\n□ Analyze attachments (upload to VirusTotal, do not execute)\n□ Search threat intelligence for IOCs (AlienVault OTX, VirusTotal)\n\n#### Step 3: Containment\n□ Delete email from all mailboxes\n ```powershell\n # Office 365 example\n $SearchName = \"Phishing Campaign - evil.com\"\n New-ComplianceSearch -Name $SearchName -ExchangeLocation All -ContentMatchQuery '(subject:\"Invoice 12345\") AND (from:[email protected])'\n Start-ComplianceSearch -Identity $SearchName\n # After search completes:\n New-ComplianceSearchAction -SearchName $SearchName -Purge -PurgeType HardDelete\n ```\n\n□ Block sender domain/IP at email gateway\n□ Block malicious URLs at web proxy/firewall\n\n#### Step 4: Credential Reset (If P1 - User Clicked/Entered Credentials)\n□ Force password reset for affected user\n ```powershell\n Set-ADUser -Identity affected_user -ChangePasswordAtLogon $true\n ```\n□ Revoke active sessions\n ```powershell\n Revoke-AzureADUserAllRefreshToken -ObjectId [email protected]\n ```\n□ Monitor account for suspicious activity (24-48 hours)\n□ Enable additional logging on account\n\n#### Step 5: Malware Scan (If P2 - User Opened Attachment)\n□ Isolate endpoint (if not already quarantined by EDR)\n□ Run full antivirus/EDR scan\n□ Check for IOCs from attachment analysis\n□ If malware found, follow Malware Incident Playbook\n\n#### Step 6: User Communication\n□ Notify affected users that email was malicious\n□ Thank users who reported (reinforce positive behavior)\n□ If credentials reset, provide instructions\n□ For P3 (no interaction), no additional user action needed\n\n#### Step 7: Documentation\n□ Update incident ticket with:\n - Email headers and content\n - Number of recipients\n - Number who clicked/opened\n - IOCs identified\n - Actions taken\n□ Add IOCs to threat intelligence platform\n□ Create detection rules for similar emails\n\n#### Step 8: Prevention\n□ Update email gateway rules to block similar emails\n□ Add sender domain to blacklist\n□ If widespread campaign, send security awareness notice\n□ Consider additional user training if many users clicked\n```\n\nThis comprehensive security operations and incident response guide provides SOC teams with the structure, processes, and playbooks needed to detect, respond to, and recover from security incidents effectively.\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":29843,"content_sha256":"3a718152e1a3b9717dbd7d10772005486c551ee42c463d30f13b9deae2e96b9d"},{"filename":"reference/threat-modeling-risk.md","content":"# Threat Modeling & Risk Assessment\n\n## Threat Modeling Methodologies\n\n### STRIDE Threat Model\n\nSTRIDE is a threat modeling framework developed by Microsoft that categorizes threats into six types.\n\n**STRIDE Acronym**:\n\n```\nS - Spoofing Identity\n • Impersonating a user or system\n • Examples: Stolen credentials, session hijacking, phishing\n • Mitigation: Strong authentication (MFA), certificate validation\n\nT - Tampering with Data\n • Unauthorized modification of data\n • Examples: SQL injection, man-in-the-middle attacks, config manipulation\n • Mitigation: Input validation, encryption, digital signatures, integrity checks\n\nR - Repudiation\n • Denying an action was performed\n • Examples: User denies making a purchase, admin denies configuration change\n • Mitigation: Audit logging, digital signatures, non-repudiation mechanisms\n\nI - Information Disclosure\n • Exposing confidential information\n • Examples: Data breaches, information leakage, insufficient encryption\n • Mitigation: Encryption, access controls, data classification, DLP\n\nD - Denial of Service\n • Making a system unavailable\n • Examples: DDoS attacks, resource exhaustion, infinite loops\n • Mitigation: Rate limiting, load balancing, DDoS protection, capacity planning\n\nE - Elevation of Privilege\n • Gaining unauthorized capabilities\n • Examples: Privilege escalation, exploiting vulnerabilities, bypassing access controls\n • Mitigation: Least privilege, input validation, security updates, RBAC\n```\n\n**STRIDE Threat Modeling Process**:\n\n```\nStep 1: Create Data Flow Diagram (DFD)\n┌──────────┐ HTTPS ┌──────────┐ SQL ┌──────────┐\n│ User │ ──────────────────>│ Web │ ────────────> │ Database │\n│ (Browser)│ │ Server │ │ Server │\n└──────────┘ └──────────┘ └──────────┘\n │\n │ HTTPS\n ▼\n ┌──────────┐\n │ Auth │\n │ Service │\n └──────────┘\n\nStep 2: Identify Trust Boundaries\n- Between User and Web Server (internet)\n- Between Web Server and Database (internal network)\n- Between Web Server and Auth Service\n\nStep 3: Apply STRIDE to Each Element\n\nWeb Server:\n├─ Spoofing: Attacker impersonates web server\n│ └─ Mitigation: TLS certificate, HSTS\n├─ Tampering: Attacker modifies web server code\n│ └─ Mitigation: File integrity monitoring, immutable infrastructure\n├─ Repudiation: Admin denies making config change\n│ └─ Mitigation: Audit logging of all admin actions\n├─ Information Disclosure: Web server exposes sensitive data in errors\n│ └─ Mitigation: Custom error pages, no stack traces in production\n├─ Denial of Service: Attacker overwhelms web server\n│ └─ Mitigation: Rate limiting, WAF, DDoS protection\n└─ Elevation of Privilege: Attacker gains admin access to web server\n └─ Mitigation: Least privilege, patch management, hardening\n\nStep 4: Apply STRIDE to Each Data Flow\n\nUser → Web Server (HTTPS):\n├─ Spoofing: Man-in-the-middle attack\n│ └─ Mitigation: TLS 1.3, certificate pinning\n├─ Tampering: Attacker modifies data in transit\n│ └─ Mitigation: TLS encryption\n├─ Repudiation: User denies sending request\n│ └─ Mitigation: Session logging with IP address\n├─ Information Disclosure: Credentials leaked in transit\n│ └─ Mitigation: TLS encryption, no credentials in URLs\n├─ Denial of Service: Request flooding\n│ └─ Mitigation: Rate limiting per IP, CAPTCHA\n└─ Elevation of Privilege: Session hijacking\n └─ Mitigation: HTTPOnly/Secure cookies, session timeout\n\nStep 5: Document Threats and Mitigations\n\n| Threat ID | STRIDE Category | Threat Description | Risk Level | Mitigation | Status |\n|-----------|----------------|-------------------|-----------|-----------|--------|\n| T-001 | Spoofing | Attacker intercepts login and reuses credentials | High | Implement MFA | Implemented |\n| T-002 | Tampering | SQL injection in search field | Critical | Parameterized queries, WAF | Implemented |\n| T-003 | Information Disclosure | Database credentials in config file | High | Use secrets manager | Pending |\n```\n\n### PASTA Threat Model\n\n**PASTA** (Process for Attack Simulation and Threat Analysis) is a risk-centric threat modeling framework.\n\n**7 Stages**:\n\n```\nStage 1: Define Business Objectives\n- Identify business goals and security objectives\n- Example: \"Maintain customer trust by protecting payment information\"\n\nStage 2: Define Technical Scope\n- Identify software components, infrastructure, actors\n- Create architecture diagrams\n- Example: Web app, database, payment processor integration\n\nStage 3: Application Decomposition\n- Create detailed data flow diagrams\n- Identify trust boundaries\n- Document APIs, protocols, data formats\n\nStage 4: Threat Analysis\n- Identify threat actors (who might attack?)\n- Analyze attack vectors (how might they attack?)\n- Use threat intelligence feeds\n- Example threat actors: Cybercriminals seeking payment data, competitors, malicious insiders\n\nStage 5: Vulnerability and Weakness Analysis\n- Review known vulnerabilities (CVEs)\n- Code review findings\n- Penetration test results\n- Example: OWASP Top 10 vulnerabilities\n\nStage 6: Attack Modeling\n- Create attack trees showing how attacks could succeed\n- Simulate attack paths\n- Assess likelihood and impact\n\nExample Attack Tree:\nCompromise Payment Data\n├─ AND: Exploit SQL Injection\n│ ├─ Find vulnerable input field\n│ └─ Bypass WAF\n└─ OR: Social Engineering\n ├─ Phish developer for credentials\n └─ Insider threat\n\nStage 7: Risk and Impact Analysis\n- Calculate risk scores\n- Prioritize threats\n- Recommend countermeasures\n- Create remediation roadmap\n```\n\n### Attack Trees\n\nAttack trees visually represent the ways a security goal can be compromised.\n\n**Example: Steal Customer Data**\n\n```\n [Steal Customer Data]\n │\n ┌───────────────────┼───────────────────┐\n │ │ │\n [Network Attack] [Application] [Physical Access]\n │ Vulnerability │\n │ │ │\n ┌───┴───┐ ┌───┴───┐ ┌───┴───┐\n │ │ │ │ │ │\n [MITM] [Sniff] [SQLi] [XSS] [Steal] [Dumpster]\n [Laptop] [Diving]\n\nAND node: Both children must succeed\nOR node: Any child can succeed (default)\n\nLeaf nodes:\n- MITM (Man-in-the-Middle): Likelihood: Low, Cost: Medium\n- SQLi (SQL Injection): Likelihood: Medium, Cost: Low\n- XSS (Cross-Site Scripting): Likelihood: High, Cost: Low\n- Steal Laptop: Likelihood: Medium, Cost: Low\n- Dumpster Diving: Likelihood: Low, Cost: Very Low\n```\n\n**Attack Tree Analysis**:\n\n```python\nclass AttackTreeNode:\n def __init__(self, name, likelihood=0, cost=0, impact=0, node_type=\"OR\"):\n self.name = name\n self.likelihood = likelihood # 0-1 scale\n self.cost = cost # Attacker cost (low, medium, high)\n self.impact = impact # Defender impact if successful (1-10 scale)\n self.node_type = node_type # AND or OR\n self.children = []\n\n def add_child(self, child):\n self.children.append(child)\n\n def calculate_likelihood(self):\n \"\"\"Calculate likelihood of attack path success\"\"\"\n if not self.children:\n return self.likelihood\n\n if self.node_type == \"OR\":\n # OR node: Probability that at least one child succeeds\n # P(A OR B) = P(A) + P(B) - P(A)*P(B)\n combined = 0\n for child in self.children:\n child_likelihood = child.calculate_likelihood()\n combined = combined + child_likelihood - (combined * child_likelihood)\n return combined\n\n elif self.node_type == \"AND\":\n # AND node: Probability that all children succeed\n # P(A AND B) = P(A) * P(B)\n combined = 1.0\n for child in self.children:\n combined *= child.calculate_likelihood()\n return combined\n\n# Example attack tree\nroot = AttackTreeNode(\"Steal Customer Data\", node_type=\"OR\")\n\n# Network attacks\nnetwork = AttackTreeNode(\"Network Attack\", node_type=\"OR\")\nnetwork.add_child(AttackTreeNode(\"MITM\", likelihood=0.1, cost=\"medium\", impact=9))\nnetwork.add_child(AttackTreeNode(\"Packet Sniffing\", likelihood=0.05, cost=\"low\", impact=9))\n\n# Application vulnerabilities\napp = AttackTreeNode(\"Exploit Application\", node_type=\"OR\")\napp.add_child(AttackTreeNode(\"SQL Injection\", likelihood=0.3, cost=\"low\", impact=10))\napp.add_child(AttackTreeNode(\"XSS\", likelihood=0.4, cost=\"low\", impact=6))\n\n# Physical access\nphysical = AttackTreeNode(\"Physical Access\", node_type=\"AND\")\nphysical.add_child(AttackTreeNode(\"Bypass Physical Security\", likelihood=0.2, cost=\"medium\", impact=10))\nphysical.add_child(AttackTreeNode(\"Access Database Server\", likelihood=0.5, cost=\"low\", impact=10))\n\nroot.add_child(network)\nroot.add_child(app)\nroot.add_child(physical)\n\noverall_likelihood = root.calculate_likelihood()\nprint(f\"Overall likelihood of successful attack: {overall_likelihood:.2%}\")\n# Output: Overall likelihood of successful attack: 60.94%\n```\n\n---\n\n## Risk Assessment Frameworks\n\n### Quantitative Risk Assessment\n\n**Single Loss Expectancy (SLE)**:\n```\nSLE = Asset Value × Exposure Factor\n\nExample:\n- Asset: Customer database\n- Asset Value: $5,000,000\n- Exposure Factor: 0.8 (80% of value lost in a breach)\n- SLE = $5,000,000 × 0.8 = $4,000,000\n```\n\n**Annualized Rate of Occurrence (ARO)**:\n```\nARO = Expected number of times threat will occur per year\n\nExample:\n- Threat: Data breach\n- Historical data: 1 breach every 5 years\n- ARO = 1/5 = 0.2\n```\n\n**Annualized Loss Expectancy (ALE)**:\n```\nALE = SLE × ARO\n\nExample:\n- SLE = $4,000,000\n- ARO = 0.2\n- ALE = $4,000,000 × 0.2 = $800,000\n\nInterpretation: Expected to lose $800,000 per year from this risk\n```\n\n**Cost-Benefit Analysis**:\n```\nCost-Benefit = ALE (before) - ALE (after) - Cost of Control\n\nExample:\n- ALE before control: $800,000\n- ALE after implementing DLP and encryption: $100,000 (reduced likelihood to 0.025)\n- Annual cost of controls: $150,000\n\nCost-Benefit = $800,000 - $100,000 - $150,000 = $550,000\n\nPositive value → Control is cost-effective\nNegative value → Control costs more than risk reduction\n```\n\n**Quantitative Risk Assessment Example**:\n\n```python\nclass QuantitativeRiskAssessment:\n def __init__(self, asset_value, exposure_factor, aro):\n self.asset_value = asset_value\n self.exposure_factor = exposure_factor # 0-1\n self.aro = aro # Annual Rate of Occurrence\n\n def calculate_sle(self):\n \"\"\"Single Loss Expectancy\"\"\"\n return self.asset_value * self.exposure_factor\n\n def calculate_ale(self):\n \"\"\"Annualized Loss Expectancy\"\"\"\n return self.calculate_sle() * self.aro\n\n def cost_benefit_analysis(self, control_cost, new_aro):\n \"\"\"Determine if control is cost-effective\"\"\"\n ale_before = self.calculate_ale()\n ale_after = self.calculate_sle() * new_aro\n annual_savings = ale_before - ale_after\n net_benefit = annual_savings - control_cost\n\n return {\n \"ale_before\": ale_before,\n \"ale_after\": ale_after,\n \"annual_savings\": annual_savings,\n \"control_cost\": control_cost,\n \"net_benefit\": net_benefit,\n \"roi_percent\": (net_benefit / control_cost * 100) if control_cost > 0 else 0,\n \"recommendation\": \"Implement\" if net_benefit > 0 else \"Do not implement\"\n }\n\n# Example: Assess risk of ransomware attack\nra = QuantitativeRiskAssessment(\n asset_value=10_000_000, # Value of systems + downtime cost\n exposure_factor=0.6, # 60% impact (some data recoverable from backups)\n aro=0.15 # 15% chance per year (once every 6-7 years)\n)\n\nprint(f\"SLE: ${ra.calculate_sle():,.0f}\")\nprint(f\"ALE: ${ra.calculate_ale():,.0f}\")\n\n# Evaluate EDR solution that reduces ARO from 0.15 to 0.02\nresult = ra.cost_benefit_analysis(\n control_cost=200_000, # Annual cost of EDR\n new_aro=0.02 # Reduced to 2% chance per year\n)\n\nprint(f\"\\nControl Cost-Benefit Analysis:\")\nprint(f\"ALE Before: ${result['ale_before']:,.0f}\")\nprint(f\"ALE After: ${result['ale_after']:,.0f}\")\nprint(f\"Annual Savings: ${result['annual_savings']:,.0f}\")\nprint(f\"Net Benefit: ${result['net_benefit']:,.0f}\")\nprint(f\"ROI: {result['roi_percent']:.1f}%\")\nprint(f\"Recommendation: {result['recommendation']}\")\n\n# Output:\n# SLE: $6,000,000\n# ALE: $900,000\n#\n# Control Cost-Benefit Analysis:\n# ALE Before: $900,000\n# ALE After: $120,000\n# Annual Savings: $780,000\n# Net Benefit: $580,000\n# ROI: 290.0%\n# Recommendation: Implement\n```\n\n### Qualitative Risk Assessment\n\n**Risk Matrix (Likelihood × Impact)**:\n\n```\nImpact →\n │ 1-Minimal │ 2-Minor │ 3-Moderate│ 4-Major │5-Catastrophic│\nL │ │ │ │ │ │\ni 1 │ Low │ Low │ Low │ Medium │ Medium │\nk │ │ │ │ │ │\ne 2 │ Low │ Low │ Medium │ High │ High │\nl │ │ │ │ │ │\ni 3 │ Low │ Medium │ Medium │ High │ Critical │\nh │ │ │ │ │ │\no 4 │ Medium │ High │ High │ Critical │ Critical │\no │ │ │ │ │ │\nd 5 │ Medium │ High │ Critical │ Critical │ Critical │\n↓ │ │ │ │ │ │\n\nRisk Levels:\n- Low: Accept risk, monitor\n- Medium: Mitigate within 90 days\n- High: Mitigate within 30 days\n- Critical: Immediate mitigation required\n```\n\n**Likelihood Scale**:\n\n```\n5 - Almost Certain (>75% probability in next 12 months)\n • Known active exploits\n • High attacker motivation\n • Easy to exploit\n\n4 - Likely (50-75% probability)\n • Exploits available\n • Moderate attacker motivation\n • Moderate exploit difficulty\n\n3 - Possible (25-50% probability)\n • Some exploits available\n • Some attacker motivation\n • Some technical barriers\n\n2 - Unlikely (5-25% probability)\n • No known exploits\n • Low attacker motivation\n • Significant technical barriers\n\n1 - Rare (\u003c5% probability)\n • Theoretical only\n • No attacker motivation\n • Extremely difficult to exploit\n```\n\n**Impact Scale**:\n\n```\n5 - Catastrophic\n • >$10M financial loss\n • Complete business disruption >1 week\n • Massive data breach (>1M records)\n • Permanent reputation damage\n • Regulatory penalties >$1M\n • Potential legal/criminal liability\n\n4 - Major\n • $1M-$10M financial loss\n • Significant business disruption (3-7 days)\n • Large data breach (100K-1M records)\n • Severe reputation damage\n • Regulatory penalties $100K-$1M\n\n3 - Moderate\n • $100K-$1M financial loss\n • Moderate business disruption (1-3 days)\n • Medium data breach (1K-100K records)\n • Moderate reputation damage\n • Regulatory penalties $10K-$100K\n\n2 - Minor\n • $10K-$100K financial loss\n • Minor business disruption (\u003c1 day)\n • Small data breach (\u003c1K records)\n • Limited reputation damage\n • Regulatory penalties \u003c$10K\n\n1 - Minimal\n • \u003c$10K financial loss\n • Negligible business disruption\n • No data breach\n • No reputation damage\n • No regulatory impact\n```\n\n**Qualitative Risk Assessment Example**:\n\n```python\nclass QualitativeRiskAssessment:\n def __init__(self):\n self.risk_matrix = {\n (1, 1): \"Low\", (1, 2): \"Low\", (1, 3): \"Low\", (1, 4): \"Medium\", (1, 5): \"Medium\",\n (2, 1): \"Low\", (2, 2): \"Low\", (2, 3): \"Medium\", (2, 4): \"High\", (2, 5): \"High\",\n (3, 1): \"Low\", (3, 2): \"Medium\", (3, 3): \"Medium\", (3, 4): \"High\", (3, 5): \"Critical\",\n (4, 1): \"Medium\", (4, 2): \"High\", (4, 3): \"High\", (4, 4): \"Critical\", (4, 5): \"Critical\",\n (5, 1): \"Medium\", (5, 2): \"High\", (5, 3): \"Critical\", (5, 4): \"Critical\", (5, 5): \"Critical\"\n }\n\n def assess_risk(self, likelihood, impact):\n \"\"\"\n likelihood: 1-5 (Rare to Almost Certain)\n impact: 1-5 (Minimal to Catastrophic)\n \"\"\"\n risk_level = self.risk_matrix.get((likelihood, impact), \"Unknown\")\n\n risk_score = likelihood * impact\n\n if risk_level == \"Critical\":\n action = \"Immediate mitigation required\"\n timeline = \"24-48 hours\"\n elif risk_level == \"High\":\n action = \"Mitigate within 30 days\"\n timeline = \"30 days\"\n elif risk_level == \"Medium\":\n action = \"Mitigate within 90 days\"\n timeline = \"90 days\"\n else: # Low\n action = \"Accept risk, monitor\"\n timeline = \"Ongoing monitoring\"\n\n return {\n \"likelihood\": likelihood,\n \"impact\": impact,\n \"risk_score\": risk_score,\n \"risk_level\": risk_level,\n \"action\": action,\n \"timeline\": timeline\n }\n\n# Example assessments\nqra = QualitativeRiskAssessment()\n\n# Scenario 1: Unpatched critical vulnerability in public-facing web server\nrisk1 = qra.assess_risk(likelihood=5, impact=4)\nprint(\"Risk 1: Unpatched critical vulnerability\")\nprint(f\" Risk Level: {risk1['risk_level']}\")\nprint(f\" Action: {risk1['action']}\")\nprint(f\" Timeline: {risk1['timeline']}\\n\")\n\n# Scenario 2: Phishing attack targeting employees\nrisk2 = qra.assess_risk(likelihood=4, impact=3)\nprint(\"Risk 2: Phishing attack\")\nprint(f\" Risk Level: {risk2['risk_level']}\")\nprint(f\" Action: {risk2['action']}\")\nprint(f\" Timeline: {risk2['timeline']}\\n\")\n\n# Scenario 3: Laptop theft with encrypted data\nrisk3 = qra.assess_risk(likelihood=2, impact=2)\nprint(\"Risk 3: Laptop theft (encrypted)\")\nprint(f\" Risk Level: {risk3['risk_level']}\")\nprint(f\" Action: {risk3['action']}\")\nprint(f\" Timeline: {risk3['timeline']}\")\n```\n\n---\n\n## Threat Intelligence\n\n### Threat Intelligence Sources\n\n**Open Source Threat Intelligence (OSINT)**:\n\n```\nFree Sources:\n├─ MITRE ATT&CK Framework (https://attack.mitre.org)\n│ • Tactics, techniques, and procedures (TTPs) of threat actors\n│ • 14 tactics, 200+ techniques\n│ • Platform-specific matrices (Enterprise, Mobile, ICS)\n│\n├─ CVE/NVD (https://nvd.nist.gov)\n│ • Common Vulnerabilities and Exposures\n│ • CVSS scores and descriptions\n│ • Exploit availability\n│\n├─ AlienVault OTX (https://otx.alienvault.com)\n│ • Community-driven threat intelligence\n│ • Indicators of Compromise (IOCs)\n│ • Threat pulses and reports\n│\n├─ Abuse.ch (https://abuse.ch)\n│ • Malware samples and IOCs\n│ • Feodo Tracker (banking trojans)\n│ • URLhaus (malicious URLs)\n│ • ThreatFox (IOC database)\n│\n├─ CISA Alerts (https://www.cisa.gov/news-events/cybersecurity-advisories)\n│ • US government cybersecurity advisories\n│ • Critical vulnerabilities and exploits\n│ • Recommended mitigations\n│\n└─ VirusTotal (https://www.virustotal.com)\n • File and URL scanning\n • Community comments and IOCs\n • Behavioral analysis\n\nCommercial Sources:\n├─ Recorded Future\n├─ Mandiant Threat Intelligence\n├─ CrowdStrike Falcon Intelligence\n├─ FireEye iSIGHT\n├─ Anomali ThreatStream\n└─ ThreatQuotient\n```\n\n### MITRE ATT&CK Framework\n\n**14 Tactics** (Why - the adversary's tactical goal):\n\n```\n1. Reconnaissance\n - Gather information for planning\n - Examples: Active scanning, phishing for info, OSINT\n\n2. Resource Development\n - Establish resources for operations\n - Examples: Acquire infrastructure, develop capabilities, compromise accounts\n\n3. Initial Access\n - Get into the network\n - Examples: Phishing, exploit public-facing app, valid accounts\n\n4. Execution\n - Run malicious code\n - Examples: Command/scripting, user execution, system services\n\n5. Persistence\n - Maintain foothold\n - Examples: Boot/logon autostart, create account, scheduled tasks\n\n6. Privilege Escalation\n - Gain higher-level permissions\n - Examples: Valid accounts, exploitation, abuse elevation control\n\n7. Defense Evasion\n - Avoid detection\n - Examples: Disable security tools, obfuscate code, masquerading\n\n8. Credential Access\n - Steal credentials\n - Examples: Brute force, credential dumping, keylogging\n\n9. Discovery\n - Learn about the environment\n - Examples: System/network discovery, file/directory discovery\n\n10. Lateral Movement\n - Move through environment\n - Examples: Remote services, remote desktop, internal spearphishing\n\n11. Collection\n - Gather data of interest\n - Examples: Data from local system, clipboard data, screen capture\n\n12. Command and Control (C2)\n - Communicate with compromised systems\n - Examples: Web protocols, encrypted channels, proxy\n\n13. Exfiltration\n - Steal data\n - Examples: Exfiltration over C2, automated exfiltration, scheduled transfer\n\n14. Impact\n - Disrupt availability or integrity\n - Examples: Data destruction, ransomware, resource hijacking\n```\n\n**Example ATT&CK Mapping**:\n\n```yaml\nattack_scenario: \"Ransomware Attack\"\n\nkill_chain:\n - tactic: Initial Access\n technique: T1566.001 - Phishing: Spearphishing Attachment\n description: User opens malicious email attachment\n detection:\n - Email gateway scanning\n - User awareness training\n - Sandboxing attachments\n mitigation:\n - Email filtering (SPF, DMARC, DKIM)\n - Disable macros by default\n - User training on identifying phishing\n\n - tactic: Execution\n technique: T1204.002 - User Execution: Malicious File\n description: User executes malicious payload\n detection:\n - EDR behavioral analysis\n - Application whitelisting alerts\n mitigation:\n - Application whitelisting\n - Least privilege (no admin rights)\n - EDR solution\n\n - tactic: Persistence\n technique: T1547.001 - Boot or Logon Autostart: Registry Run Keys\n description: Malware creates registry key for persistence\n detection:\n - Monitor registry modifications\n - Sysmon Event ID 13\n mitigation:\n - Registry monitoring\n - File integrity monitoring\n\n - tactic: Privilege Escalation\n technique: T1068 - Exploitation for Privilege Escalation\n description: Exploit CVE-2021-34527 (PrintNightmare)\n detection:\n - Vulnerability scanning\n - EDR exploit detection\n mitigation:\n - Patch management (critical updates within 7 days)\n - Disable Print Spooler if not needed\n\n - tactic: Defense Evasion\n technique: T1562.001 - Impair Defenses: Disable or Modify Tools\n description: Ransomware disables antivirus\n detection:\n - Monitor security tool status\n - SIEM alert on AV service stop\n mitigation:\n - Tamper protection enabled\n - Security service monitoring\n\n - tactic: Credential Access\n technique: T1003.001 - OS Credential Dumping: LSASS Memory\n description: Dump credentials from memory using Mimikatz\n detection:\n - EDR detects LSASS access\n - Credential Guard\n mitigation:\n - Credential Guard\n - Protected Process Light (PPL) for LSASS\n - Restrict debug privileges\n\n - tactic: Discovery\n technique: T1083 - File and Directory Discovery\n description: Enumerate file shares for valuable data\n detection:\n - Monitor SMB traffic patterns\n - Unusual file access patterns\n mitigation:\n - Least privilege file share access\n - Network segmentation\n\n - tactic: Lateral Movement\n technique: T1021.001 - Remote Services: Remote Desktop Protocol\n description: Move to additional systems via RDP\n detection:\n - Monitor RDP connections (Event ID 4624 Type 10)\n - Unusual lateral movement patterns\n mitigation:\n - Network segmentation\n - MFA for RDP\n - Limit RDP access\n\n - tactic: Collection\n technique: T1005 - Data from Local System\n description: Identify valuable files for encryption\n detection:\n - File access monitoring\n - Data classification alerts\n mitigation:\n - DLP solution\n - File access auditing\n\n - tactic: Command and Control\n technique: T1071.001 - Application Layer Protocol: Web Protocols\n description: Communicate with C2 server over HTTPS\n detection:\n - Monitor outbound HTTPS to suspicious IPs\n - DNS monitoring for C2 domains\n mitigation:\n - Web proxy with SSL inspection\n - DNS filtering\n - Egress firewall rules\n\n - tactic: Impact\n technique: T1486 - Data Encrypted for Impact\n description: Encrypt files and demand ransom\n detection:\n - Rapid file modification alerts\n - Unusual encryption activity\n mitigation:\n - Offline backups tested regularly\n - File integrity monitoring\n - Honey files (canary files that trigger alerts)\n - Immutable backups\n```\n\n---\n\n## Vulnerability Management\n\n### Vulnerability Scoring (CVSS)\n\n**CVSS v3.1 Metrics**:\n\n```\nBase Score Metrics (Intrinsic characteristics):\n\nAttack Vector (AV):\n├─ Network (N): 0.85 - Exploitable remotely\n├─ Adjacent (A): 0.62 - Local network required\n├─ Local (L): 0.55 - Local access required\n└─ Physical (P): 0.20 - Physical access required\n\nAttack Complexity (AC):\n├─ Low (L): 0.77 - No specialized conditions\n└─ High (H): 0.44 - Special conditions required\n\nPrivileges Required (PR):\n├─ None (N): 0.85 - No privileges needed\n├─ Low (L): 0.62 - Basic user privileges\n└─ High (H): 0.27 - Admin privileges required\n\nUser Interaction (UI):\n├─ None (N): 0.85 - No user interaction needed\n└─ Required (R): 0.62 - User must perform action\n\nScope (S):\n├─ Unchanged (U): Impact limited to vulnerable component\n└─ Changed (C): Impact extends beyond vulnerable component\n\nImpact Metrics (C/I/A):\nConfidentiality (C):\n├─ None (N): 0 - No information disclosure\n├─ Low (L): 0.22 - Some information disclosed\n└─ High (H): 0.56 - Total information disclosure\n\nIntegrity (I):\n├─ None (N): 0 - No integrity impact\n├─ Low (L): 0.22 - Limited modification possible\n└─ High (H): 0.56 - Total compromise of integrity\n\nAvailability (A):\n├─ None (N): 0 - No availability impact\n├─ Low (L): 0.22 - Reduced performance\n└─ High (H): 0.56 - Total loss of availability\n\nCVSS Score Ranges:\n- 0.0: None\n- 0.1-3.9: Low\n- 4.0-6.9: Medium\n- 7.0-8.9: High\n- 9.0-10.0: Critical\n```\n\n**Example CVSS Scoring**:\n\n```\nVulnerability: CVE-2021-44228 (Log4Shell)\n\nAttack Vector: Network (N) - Exploitable via network\nAttack Complexity: Low (L) - Easy to exploit\nPrivileges Required: None (N) - No authentication needed\nUser Interaction: None (N) - No user interaction required\nScope: Changed (C) - Can affect other components\nConfidentiality: High (H) - Full system access\nIntegrity: High (H) - Complete system compromise\nAvailability: High (H) - Can cause DoS\n\nCVSS Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H\nCVSS Base Score: 10.0 (Critical)\n\nExploitability Score: 3.9\nImpact Score: 6.0\n```\n\n### Vulnerability Prioritization\n\n**CVSS + Context-Based Prioritization**:\n\n```python\nclass VulnerabilityPrioritization:\n def __init__(self):\n self.severity_weights = {\n \"critical\": 10,\n \"high\": 7,\n \"medium\": 4,\n \"low\": 1\n }\n\n def calculate_priority_score(self, vuln):\n \"\"\"\n Calculate priority score based on CVSS + business context\n \"\"\"\n # Base CVSS score (0-10)\n cvss_score = vuln.get(\"cvss_score\", 0)\n\n # Exploitability factors\n exploit_available = 1.5 if vuln.get(\"exploit_available\") else 1.0\n exploit_in_wild = 2.0 if vuln.get(\"exploit_in_wild\") else 1.0\n\n # Asset criticality (1-5 scale)\n asset_criticality = vuln.get(\"asset_criticality\", 3)\n\n # Exposure (1-3 scale)\n exposure_map = {\n \"internet_facing\": 3,\n \"internal\": 2,\n \"isolated\": 1\n }\n exposure = exposure_map.get(vuln.get(\"exposure\", \"internal\"), 2)\n\n # Data sensitivity (1-3 scale)\n data_sensitivity_map = {\n \"highly_confidential\": 3, # PII, PHI, financial\n \"confidential\": 2, # Internal data\n \"public\": 1\n }\n data_sensitivity = data_sensitivity_map.get(vuln.get(\"data_sensitivity\", \"confidential\"), 2)\n\n # Compensating controls (0.5-1.0 multiplier)\n has_controls = 0.5 if vuln.get(\"compensating_controls\") else 1.0\n\n # Calculate weighted priority score\n priority_score = (\n cvss_score *\n exploit_available *\n exploit_in_wild *\n (asset_criticality / 3) *\n (exposure / 2) *\n (data_sensitivity / 2) *\n has_controls\n )\n\n # Determine priority level and SLA\n if priority_score >= 14:\n priority = \"P0\"\n sla_days = 1\n elif priority_score >= 10:\n priority = \"P1\"\n sla_days = 7\n elif priority_score >= 6:\n priority = \"P2\"\n sla_days = 30\n else:\n priority = \"P3\"\n sla_days = 90\n\n return {\n \"priority_score\": round(priority_score, 2),\n \"priority_level\": priority,\n \"sla_days\": sla_days,\n \"rationale\": self._generate_rationale(vuln, priority_score)\n }\n\n def _generate_rationale(self, vuln, priority_score):\n factors = []\n if vuln.get(\"cvss_score\", 0) >= 9.0:\n factors.append(\"Critical CVSS score\")\n if vuln.get(\"exploit_in_wild\"):\n factors.append(\"Active exploitation in wild\")\n if vuln.get(\"exploit_available\"):\n factors.append(\"Public exploit available\")\n if vuln.get(\"exposure\") == \"internet_facing\":\n factors.append(\"Internet-facing system\")\n if vuln.get(\"asset_criticality\", 0) >= 4:\n factors.append(\"Critical business system\")\n if vuln.get(\"data_sensitivity\") == \"highly_confidential\":\n factors.append(\"Contains sensitive data\")\n\n return \"; \".join(factors) if factors else \"Standard risk assessment\"\n\n# Example vulnerability assessments\nvp = VulnerabilityPrioritization()\n\n# Scenario 1: Log4Shell on internet-facing application server\nvuln1 = {\n \"cve\": \"CVE-2021-44228\",\n \"cvss_score\": 10.0,\n \"exploit_available\": True,\n \"exploit_in_wild\": True,\n \"asset_criticality\": 5,\n \"exposure\": \"internet_facing\",\n \"data_sensitivity\": \"highly_confidential\",\n \"compensating_controls\": False\n}\n\nresult1 = vp.calculate_priority_score(vuln1)\nprint(\"Vulnerability 1: Log4Shell on production web server\")\nprint(f\" Priority Score: {result1['priority_score']}\")\nprint(f\" Priority Level: {result1['priority_level']}\")\nprint(f\" SLA: Patch within {result1['sla_days']} day(s)\")\nprint(f\" Rationale: {result1['rationale']}\\n\")\n\n# Scenario 2: Medium severity vuln on internal dev server with WAF protection\nvuln2 = {\n \"cve\": \"CVE-2023-12345\",\n \"cvss_score\": 6.5,\n \"exploit_available\": False,\n \"exploit_in_wild\": False,\n \"asset_criticality\": 2,\n \"exposure\": \"internal\",\n \"data_sensitivity\": \"confidential\",\n \"compensating_controls\": True # WAF blocking exploit\n}\n\nresult2 = vp.calculate_priority_score(vuln2)\nprint(\"Vulnerability 2: Medium CVSS on internal dev server\")\nprint(f\" Priority Score: {result2['priority_score']}\")\nprint(f\" Priority Level: {result2['priority_level']}\")\nprint(f\" SLA: Patch within {result2['sla_days']} days\")\nprint(f\" Rationale: {result2['rationale']}\")\n```\n\n---\n\n## Penetration Testing\n\n### Penetration Test Types\n\n```\n1. Black Box Testing\n - No prior knowledge of system\n - Simulates external attacker\n - Tests external defenses\n - Longest time required\n\n2. Gray Box Testing\n - Partial knowledge (e.g., user account)\n - Simulates malicious insider or compromised account\n - Most common type\n - Balanced approach\n\n3. White Box Testing (Clear Box)\n - Full knowledge (code, architecture, credentials)\n - Most comprehensive testing\n - Shortest time required\n - Identifies maximum vulnerabilities\n\n4. Red Team Exercise\n - Realistic attack simulation\n - Multi-vector attacks\n - Tests detection and response\n - Blue team (defenders) may or may not be aware\n\n5. Purple Team Exercise\n - Red team + Blue team collaboration\n - Improve detection and response\n - Knowledge sharing\n - Continuous improvement focus\n```\n\n### Penetration Testing Methodology\n\n```\nPhase 1: Planning and Reconnaissance\n├─ Define scope (IP ranges, domains, out-of-scope systems)\n├─ Rules of engagement (testing windows, contacts, escalation)\n├─ Passive reconnaissance (OSINT, DNS, WHOIS)\n└─ Active reconnaissance (port scanning, service enumeration)\n\nPhase 2: Scanning and Enumeration\n├─ Port scanning (nmap, masscan)\n├─ Service version detection\n├─ Vulnerability scanning (Nessus, OpenVAS)\n├─ Web application scanning (Burp Suite, OWASP ZAP)\n└─ Enumerate users, shares, services\n\nPhase 3: Gaining Access (Exploitation)\n├─ Exploit vulnerabilities (Metasploit, custom exploits)\n├─ Password attacks (brute force, dictionary, password spraying)\n├─ Social engineering (phishing, pretexting)\n├─ Web application attacks (SQLi, XSS, CSRF)\n└─ Wireless attacks (WPA2 cracking, rogue AP)\n\nPhase 4: Maintaining Access\n├─ Install backdoors\n├─ Create persistent access mechanisms\n├─ Establish command and control (C2)\n└─ Privilege escalation\n\nPhase 5: Lateral Movement\n├─ Network enumeration\n├─ Credential harvesting (Mimikatz, password reuse)\n├─ Pivot to other systems\n└─ Escalate to domain admin or crown jewels\n\nPhase 6: Covering Tracks (Clean Up)\n├─ Remove tools and artifacts\n├─ Clear logs (for red team exercises only)\n└─ Document all actions for client\n\nPhase 7: Reporting\n├─ Executive summary\n├─ Technical findings with CVSS scores\n├─ Evidence (screenshots, logs)\n├─ Remediation recommendations\n├─ Risk ratings\n└─ Retest scope\n```\n\n### Common Penetration Testing Tools\n\n```\nReconnaissance:\n├─ nmap - Network scanner\n├─ masscan - Fast port scanner\n├─ theHarvester - Email/subdomain discovery\n├─ Shodan - Internet-connected device search\n├─ Recon-ng - Web reconnaissance framework\n└─ OSINT Framework - OSINT collection\n\nVulnerability Scanning:\n├─ Nessus - Commercial vulnerability scanner\n├─ OpenVAS - Open source vulnerability scanner\n├─ Nikto - Web server scanner\n└─ SQLmap - SQL injection scanner\n\nExploitation:\n├─ Metasploit Framework - Exploitation framework\n├─ Exploit-DB - Exploit database\n├─ Social Engineer Toolkit (SET) - Social engineering\n└─ Cobalt Strike - Commercial red team platform\n\nWeb Application Testing:\n├─ Burp Suite Pro - Web security testing\n├─ OWASP ZAP - Web app scanner\n├─ Acunetix - Web vulnerability scanner\n└─ Nikto - Web server scanner\n\nPassword Attacks:\n├─ John the Ripper - Password cracker\n├─ Hashcat - Advanced password recovery\n├─ Hydra - Network login cracker\n├─ CrackMapExec - Post-exploitation tool\n└─ Mimikatz - Credential extraction\n\nPost-Exploitation:\n├─ PowerShell Empire - Post-exploitation framework\n├─ BloodHound - AD attack path analysis\n├─ Responder - LLMNR/NBT-NS poisoning\n└─ Impacket - Network protocol toolkit\n\nWireless:\n├─ Aircrack-ng - WiFi security auditing\n├─ Kismet - Wireless network detector\n└─ Wifite - Automated wireless attack tool\n```\n\n---\n\n## Security Assessment Deliverables\n\n### Penetration Test Report Template\n\n```markdown\n# Penetration Test Report\n\n## Executive Summary\n\n**Client**: Acme Corporation\n**Test Date**: January 15-19, 2025\n**Test Type**: External and Internal Penetration Test (Gray Box)\n**Scope**: Production web applications and internal network (10.0.0.0/16)\n**Tester**: [Red Team Company]\n\n### Key Findings\n\n**Critical Risk**: 2 findings\n**High Risk**: 5 findings\n**Medium Risk**: 12 findings\n**Low Risk**: 8 findings\n**Informational**: 6 findings\n\n### Summary\n\nThe penetration test identified several critical vulnerabilities that could allow\nan attacker to gain unauthorized access to sensitive customer data. The most\ncritical finding is an SQL injection vulnerability in the customer portal that\nallows full database access without authentication.\n\n**Recommendations (Priority)**:\n1. CRITICAL: Patch SQL injection vulnerability within 24 hours\n2. CRITICAL: Disable TLS 1.0/1.1 on all systems within 7 days\n3. HIGH: Implement MFA for all user accounts within 30 days\n4. HIGH: Patch Log4Shell vulnerability on application servers within 7 days\n\n## Technical Findings\n\n### Critical Finding 1: SQL Injection in Customer Portal\n\n**Severity**: Critical (CVSS 9.8)\n**Category**: Web Application Security\n**Affected System**: https://portal.acme.com/search\n**CVE**: N/A (Custom application)\n\n#### Description\nThe customer portal's search functionality is vulnerable to SQL injection due to\ninsufficient input validation. An attacker can inject arbitrary SQL commands to\nextract sensitive data from the database, including customer PII and credit card\ninformation.\n\n#### Proof of Concept\n```\nRequest:\nGET /search?query=' UNION SELECT username,password FROM users-- HTTP/1.1\nHost: portal.acme.com\n\nResponse:\n[List of all usernames and hashed passwords]\n```\n\n#### Impact\n- Complete database compromise\n- Exfiltration of 500,000+ customer records containing PII\n- Compliance violations (GDPR, PCI-DSS)\n- Potential regulatory fines\n\n#### Remediation\n1. **Immediate** (within 24 hours):\n - Take search feature offline OR\n - Implement input validation to reject SQL metacharacters\n - Deploy WAF rule to block SQL injection attempts\n\n2. **Short-term** (within 7 days):\n - Rewrite queries using parameterized statements (prepared statements)\n - Implement least privilege database accounts for application\n - Enable database query logging\n\n3. **Long-term**:\n - Conduct secure code review of entire application\n - Implement SAST scanning in CI/CD pipeline\n - Security awareness training for developers\n\n#### References\n- OWASP SQL Injection: https://owasp.org/www-community/attacks/SQL_Injection\n- CWE-89: Improper Neutralization of Special Elements used in an SQL Command\n\n---\n\n### High Finding 1: Outdated TLS Configuration\n\n**Severity**: High (CVSS 7.5)\n**Category**: Cryptography\n**Affected Systems**: All web servers (15 systems)\n\n#### Description\nWeb servers support deprecated TLS 1.0 and TLS 1.1 protocols, which have known\ncryptographic weaknesses. These protocols are vulnerable to BEAST and POODLE attacks.\n\n#### Proof of Concept\n```bash\n$ nmap --script ssl-enum-ciphers -p 443 portal.acme.com\n\nPORT STATE SERVICE\n443/tcp open https\n| ssl-enum-ciphers:\n| TLSv1.0:\n| ciphers:\n| TLS_RSA_WITH_3DES_EDE_CBC_SHA (weak)\n```\n\n#### Impact\n- Man-in-the-middle attacks possible\n- Decryption of encrypted traffic\n- Compliance violations (PCI-DSS requires TLS 1.2+)\n\n#### Remediation\n1. Disable TLS 1.0 and TLS 1.1 on all web servers\n2. Enable TLS 1.2 and TLS 1.3 only\n3. Configure strong cipher suites (ECDHE, AES-GCM)\n4. Enable HSTS header (Strict-Transport-Security)\n\nExample nginx configuration:\n```nginx\nssl_protocols TLSv1.2 TLSv1.3;\nssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';\nssl_prefer_server_ciphers on;\nadd_header Strict-Transport-Security \"max-age=31536000; includeSubDomains\" always;\n```\n\n---\n\n[Additional findings...]\n\n## Appendix A: Scope and Methodology\n\n### Scope\n**In Scope**:\n- External web applications (*.acme.com)\n- Internal network (10.0.0.0/16)\n- Wireless networks (guest and corporate)\n\n**Out of Scope**:\n- Production database servers (testing allowed, disruption prohibited)\n- Third-party SaaS applications\n- Physical security testing\n- Social engineering attacks\n\n### Methodology\nTesting followed the OWASP Testing Guide v4 and PTES (Penetration Testing Execution Standard).\n\n### Testing Windows\n- External testing: 24/7\n- Internal testing: Monday-Friday, 9 AM - 5 PM EST\n- No testing on holidays\n\n## Appendix B: Tools Used\n- Nmap 7.94 - Network scanning\n- Burp Suite Pro 2023.12 - Web application testing\n- Metasploit Framework 6.3 - Exploitation\n- SQLmap 1.8 - SQL injection testing\n- Nessus 10.6 - Vulnerability scanning\n\n## Appendix C: Risk Rating Methodology\n\nRisk ratings use CVSS v3.1 base scores with environmental adjustments:\n- Critical: 9.0-10.0\n- High: 7.0-8.9\n- Medium: 4.0-6.9\n- Low: 0.1-3.9\n```\n\n---\n\n## Continuous Risk Management\n\n### Risk Register Maintenance\n\n```yaml\nrisk_id: R-042\ntitle: \"Ransomware Attack on Production Infrastructure\"\ncategory: \"Cybersecurity\"\nowner: \"CISO\"\nstatus: \"Open\"\n\nthreat:\n actor: \"Organized cybercriminal group\"\n motivation: \"Financial gain\"\n capability: \"High (commodity ransomware widely available)\"\n\nvulnerability:\n description: \"Unpatched servers, no EDR, limited backup testing\"\n cvss_score: 8.5\n\nlikelihood:\n qualitative: \"Likely (4/5)\"\n quantitative_aro: 0.3\n justification: \"Healthcare sector heavily targeted, recent incidents at peers\"\n\nimpact:\n qualitative: \"Catastrophic (5/5)\"\n quantitative_sle: \"$8,000,000\"\n justification: \"3-5 day downtime, patient care disruption, ransom demand, recovery costs\"\n\nrisk_score:\n qualitative: 20 # 4 × 5 = Critical\n quantitative_ale: \"$2,400,000\" # $8M × 0.3\n\nrisk_response: \"Mitigate\"\n\ncontrols:\n existing:\n - \"Daily backups to cloud storage\"\n - \"Antivirus on all endpoints\"\n - \"Firewall segmentation\"\n\n planned:\n - control: \"Deploy EDR solution (CrowdStrike)\"\n cost: \"$150,000/year\"\n completion_date: \"2025-03-01\"\n risk_reduction: \"ARO from 0.3 to 0.05\"\n\n - control: \"Implement offline, immutable backups\"\n cost: \"$75,000 setup + $30,000/year\"\n completion_date: \"2025-02-15\"\n risk_reduction: \"SLE from $8M to $2M\"\n\n - control: \"Patch management automation\"\n cost: \"$50,000 setup + $20,000/year\"\n completion_date: \"2025-02-01\"\n risk_reduction: \"ARO from 0.3 to 0.1\"\n\nresidual_risk:\n qualitative: \"Medium (2 × 3 = 6)\"\n quantitative_ale: \"$100,000\" # $2M × 0.05\n acceptable: true\n justification: \"ALE reduced by 95%, within risk appetite\"\n\nnext_review_date: \"2025-07-01\"\nlast_updated: \"2025-01-15\"\n```\n\n### Risk Appetite Statement\n\n```\nBoard-Approved Risk Appetite (Annual):\n\nFinancial Loss:\n├─ Per incident: Maximum $1M\n├─ Annual aggregate: Maximum $5M\n└─ Unacceptable: >$10M single event\n\nData Breach:\n├─ Acceptable: \u003c1,000 records of non-sensitive data\n├─ Tolerable: 1,000-10,000 records with notification\n└─ Unacceptable: >10,000 records OR any PHI/PII\n\nDowntime:\n├─ Acceptable: \u003c4 hours per month\n├─ Tolerable: 4-24 hours with business continuity\n└─ Unacceptable: >24 hours of critical systems\n\nCompliance:\n├─ Acceptable: Minor findings that don't impact certification\n├─ Tolerable: Moderate findings with 90-day remediation\n└─ Unacceptable: Major findings, loss of certification, regulatory fines\n\nReputation:\n├─ Acceptable: Local media coverage, contained impact\n├─ Tolerable: National media coverage, customer churn \u003c5%\n└─ Unacceptable: Congressional investigation, >20% customer churn\n```\n\nThis risk appetite guides all risk acceptance decisions. Any risk exceeding\n\"tolerable\" thresholds must be escalated to the Board for explicit acceptance.\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":44595,"content_sha256":"d072e18bd87e4b412cf42b94fc57bcd71ad8aa9c153ca0f755e9c3d34a7547a6"},{"filename":"scripts/risk_calculator.py","content":"#!/usr/bin/env python3\n\"\"\"\nRisk Assessment Calculator\n\nCalculates risk scores using both qualitative and quantitative methodologies.\nSupports risk matrix, ALE calculations, and cost-benefit analysis for controls.\n\nUsage:\n python risk_calculator.py --interactive\n python risk_calculator.py risks.csv\n python risk_calculator.py risks.csv --output risk_report.csv\n\"\"\"\n\nimport argparse\nimport csv\nimport json\nfrom dataclasses import dataclass\nfrom typing import List, Dict, Optional\nfrom datetime import datetime\n\n\n@dataclass\nclass Risk:\n \"\"\"Risk assessment data class\"\"\"\n id: str\n name: str\n asset_value: float\n exposure_factor: float\n aro: float # Annualized Rate of Occurrence\n likelihood_qualitative: int # 1-5 scale\n impact_qualitative: int # 1-5 scale\n category: str\n owner: str\n\n\nclass RiskCalculator:\n \"\"\"Risk assessment calculator with multiple methodologies\"\"\"\n\n # Risk matrix: (likelihood, impact) -> risk_level\n RISK_MATRIX = {\n (1, 1): \"Low\", (1, 2): \"Low\", (1, 3): \"Low\", (1, 4): \"Medium\", (1, 5): \"Medium\",\n (2, 1): \"Low\", (2, 2): \"Low\", (2, 3): \"Medium\", (2, 4): \"High\", (2, 5): \"High\",\n (3, 1): \"Low\", (3, 2): \"Medium\", (3, 3): \"Medium\", (3, 4): \"High\", (3, 5): \"Critical\",\n (4, 1): \"Medium\", (4, 2): \"High\", (4, 3): \"High\", (4, 4): \"Critical\", (4, 5): \"Critical\",\n (5, 1): \"Medium\", (5, 2): \"High\", (5, 3): \"Critical\", (5, 4): \"Critical\", (5, 5): \"Critical\"\n }\n\n SLA_DAYS = {\n \"Critical\": 1,\n \"High\": 7,\n \"Medium\": 30,\n \"Low\": 90\n }\n\n def __init__(self):\n self.risks: List[Risk] = []\n\n def calculate_quantitative(self, risk: Risk) -> Dict:\n \"\"\"Calculate quantitative risk metrics (SLE, ALE)\"\"\"\n sle = risk.asset_value * risk.exposure_factor\n ale = sle * risk.aro\n\n return {\n \"sle\": round(sle, 2),\n \"ale\": round(ale, 2)\n }\n\n def calculate_qualitative(self, risk: Risk) -> Dict:\n \"\"\"Calculate qualitative risk metrics\"\"\"\n risk_score = risk.likelihood_qualitative * risk.impact_qualitative\n risk_level = self.RISK_MATRIX.get(\n (risk.likelihood_qualitative, risk.impact_qualitative),\n \"Unknown\"\n )\n sla_days = self.SLA_DAYS.get(risk_level, 90)\n\n return {\n \"risk_score\": risk_score,\n \"risk_level\": risk_level,\n \"sla_days\": sla_days\n }\n\n def cost_benefit_analysis(self, risk: Risk, control_cost: float, new_aro: float) -> Dict:\n \"\"\"Perform cost-benefit analysis for a security control\"\"\"\n quant = self.calculate_quantitative(risk)\n ale_before = quant[\"ale\"]\n\n # Calculate ALE after control\n ale_after = (risk.asset_value * risk.exposure_factor) * new_aro\n\n annual_savings = ale_before - ale_after\n net_benefit = annual_savings - control_cost\n\n roi = (net_benefit / control_cost * 100) if control_cost > 0 else 0\n\n return {\n \"ale_before\": round(ale_before, 2),\n \"ale_after\": round(ale_after, 2),\n \"annual_savings\": round(annual_savings, 2),\n \"control_cost\": control_cost,\n \"net_benefit\": round(net_benefit, 2),\n \"roi_percent\": round(roi, 2),\n \"recommendation\": \"Implement\" if net_benefit > 0 else \"Do not implement\",\n \"payback_period_years\": round(control_cost / annual_savings, 2) if annual_savings > 0 else float('inf')\n }\n\n def add_risk(self, risk: Risk):\n \"\"\"Add risk to assessment\"\"\"\n self.risks.append(risk)\n\n def generate_report(self) -> List[Dict]:\n \"\"\"Generate comprehensive risk report\"\"\"\n report = []\n\n for risk in self.risks:\n quant = self.calculate_quantitative(risk)\n qual = self.calculate_qualitative(risk)\n\n report.append({\n \"Risk ID\": risk.id,\n \"Risk Name\": risk.name,\n \"Category\": risk.category,\n \"Owner\": risk.owner,\n \"Asset Value\": f\"${risk.asset_value:,.0f}\",\n \"Exposure Factor\": f\"{risk.exposure_factor:.0%}\",\n \"ARO\": f\"{risk.aro:.2f}\",\n \"SLE\": f\"${quant['sle']:,.0f}\",\n \"ALE\": f\"${quant['ale']:,.0f}\",\n \"Likelihood\": risk.likelihood_qualitative,\n \"Impact\": risk.impact_qualitative,\n \"Risk Score\": qual[\"risk_score\"],\n \"Risk Level\": qual[\"risk_level\"],\n \"Remediation SLA\": f\"{qual['sla_days']} days\"\n })\n\n # Sort by ALE (descending)\n report.sort(key=lambda x: float(x[\"ALE\"].replace(\"$\", \"\").replace(\",\", \"\")), reverse=True)\n\n return report\n\n def generate_summary(self) -> Dict:\n \"\"\"Generate summary statistics\"\"\"\n if not self.risks:\n return {}\n\n total_ale = sum(self.calculate_quantitative(r)[\"ale\"] for r in self.risks)\n\n risk_levels = {\"Critical\": 0, \"High\": 0, \"Medium\": 0, \"Low\": 0}\n for risk in self.risks:\n qual = self.calculate_qualitative(risk)\n risk_levels[qual[\"risk_level\"]] = risk_levels.get(qual[\"risk_level\"], 0) + 1\n\n top_risks = sorted(\n [(r, self.calculate_quantitative(r)[\"ale\"]) for r in self.risks],\n key=lambda x: x[1],\n reverse=True\n )[:5]\n\n return {\n \"total_risks\": len(self.risks),\n \"total_ale\": round(total_ale, 2),\n \"risk_levels\": risk_levels,\n \"top_5_risks\": [(r.name, round(ale, 2)) for r, ale in top_risks]\n }\n\n\ndef load_risks_from_csv(filename: str) -> List[Risk]:\n \"\"\"Load risks from CSV file\"\"\"\n risks = []\n\n with open(filename, 'r') as f:\n reader = csv.DictReader(f)\n for row in reader:\n risk = Risk(\n id=row['id'],\n name=row['name'],\n asset_value=float(row['asset_value']),\n exposure_factor=float(row['exposure_factor']),\n aro=float(row['aro']),\n likelihood_qualitative=int(row['likelihood']),\n impact_qualitative=int(row['impact']),\n category=row['category'],\n owner=row['owner']\n )\n risks.append(risk)\n\n return risks\n\n\ndef save_report_to_csv(report: List[Dict], filename: str):\n \"\"\"Save risk report to CSV file\"\"\"\n if not report:\n print(\"No data to save\")\n return\n\n with open(filename, 'w', newline='') as f:\n writer = csv.DictWriter(f, fieldnames=report[0].keys())\n writer.writeheader()\n writer.writerows(report)\n\n print(f\"Report saved to {filename}\")\n\n\ndef interactive_mode():\n \"\"\"Interactive risk assessment mode\"\"\"\n calculator = RiskCalculator()\n\n print(\"=\" * 60)\n print(\"Risk Assessment Calculator - Interactive Mode\")\n print(\"=\" * 60)\n\n while True:\n print(\"\\nOptions:\")\n print(\"1. Add new risk\")\n print(\"2. Calculate cost-benefit for control\")\n print(\"3. Generate risk report\")\n print(\"4. View summary\")\n print(\"5. Exit\")\n\n choice = input(\"\\nEnter choice (1-5): \").strip()\n\n if choice == \"1\":\n print(\"\\n--- Add New Risk ---\")\n risk_id = input(\"Risk ID: \").strip()\n name = input(\"Risk Name: \").strip()\n asset_value = float(input(\"Asset Value ($): \"))\n exposure_factor = float(input(\"Exposure Factor (0-1): \"))\n aro = float(input(\"Annual Rate of Occurrence (0-1): \"))\n likelihood = int(input(\"Likelihood (1-5): \"))\n impact = int(input(\"Impact (1-5): \"))\n category = input(\"Category: \").strip()\n owner = input(\"Owner: \").strip()\n\n risk = Risk(risk_id, name, asset_value, exposure_factor, aro,\n likelihood, impact, category, owner)\n calculator.add_risk(risk)\n\n quant = calculator.calculate_quantitative(risk)\n qual = calculator.calculate_qualitative(risk)\n\n print(f\"\\n✓ Risk added successfully!\")\n print(f\" SLE: ${quant['sle']:,.0f}\")\n print(f\" ALE: ${quant['ale']:,.0f}\")\n print(f\" Risk Level: {qual['risk_level']}\")\n print(f\" Remediation SLA: {qual['sla_days']} days\")\n\n elif choice == \"2\":\n if not calculator.risks:\n print(\"No risks added yet. Please add a risk first.\")\n continue\n\n print(\"\\n--- Cost-Benefit Analysis ---\")\n print(\"Available risks:\")\n for i, risk in enumerate(calculator.risks, 1):\n print(f\"{i}. {risk.name} (ID: {risk.id})\")\n\n risk_idx = int(input(\"Select risk number: \")) - 1\n if risk_idx \u003c 0 or risk_idx >= len(calculator.risks):\n print(\"Invalid selection\")\n continue\n\n risk = calculator.risks[risk_idx]\n control_cost = float(input(\"Annual cost of control ($): \"))\n new_aro = float(input(\"New ARO after control (0-1): \"))\n\n cba = calculator.cost_benefit_analysis(risk, control_cost, new_aro)\n\n print(f\"\\n--- Cost-Benefit Analysis Results ---\")\n print(f\"ALE Before Control: ${cba['ale_before']:,.0f}\")\n print(f\"ALE After Control: ${cba['ale_after']:,.0f}\")\n print(f\"Annual Savings: ${cba['annual_savings']:,.0f}\")\n print(f\"Control Cost: ${cba['control_cost']:,.0f}\")\n print(f\"Net Benefit: ${cba['net_benefit']:,.0f}\")\n print(f\"ROI: {cba['roi_percent']:.1f}%\")\n print(f\"Payback Period: {cba['payback_period_years']:.2f} years\")\n print(f\"Recommendation: {cba['recommendation']}\")\n\n elif choice == \"3\":\n if not calculator.risks:\n print(\"No risks added yet. Please add a risk first.\")\n continue\n\n report = calculator.generate_report()\n print(\"\\n\" + \"=\" * 120)\n print(\"Risk Assessment Report\")\n print(\"=\" * 120)\n\n # Print header\n headers = list(report[0].keys())\n print(\"|\".join(f\"{h:^15}\" for h in headers))\n print(\"-\" * 120)\n\n # Print rows\n for row in report:\n print(\"|\".join(f\"{str(v):^15}\" for v in row.values()))\n\n elif choice == \"4\":\n summary = calculator.generate_summary()\n if not summary:\n print(\"No risks added yet. Please add a risk first.\")\n continue\n\n print(\"\\n\" + \"=\" * 60)\n print(\"Risk Assessment Summary\")\n print(\"=\" * 60)\n print(f\"Total Risks: {summary['total_risks']}\")\n print(f\"Total ALE: ${summary['total_ale']:,.0f}\")\n print(f\"\\nRisk Level Distribution:\")\n for level, count in summary['risk_levels'].items():\n print(f\" {level}: {count}\")\n print(f\"\\nTop 5 Risks by ALE:\")\n for name, ale in summary['top_5_risks']:\n print(f\" {name}: ${ale:,.0f}\")\n\n elif choice == \"5\":\n print(\"Exiting...\")\n break\n\n else:\n print(\"Invalid choice. Please enter 1-5.\")\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Risk Assessment Calculator\")\n parser.add_argument('input_file', nargs='?', help='CSV file containing risk data')\n parser.add_argument('--output', '-o', help='Output CSV file for risk report')\n parser.add_argument('--interactive', '-i', action='store_true',\n help='Run in interactive mode')\n parser.add_argument('--control-cost', type=float,\n help='Cost of control for cost-benefit analysis')\n parser.add_argument('--new-aro', type=float,\n help='New ARO after control implementation')\n\n args = parser.parse_args()\n\n if args.interactive:\n interactive_mode()\n return\n\n if not args.input_file:\n print(\"Error: Please provide an input file or use --interactive mode\")\n parser.print_help()\n return\n\n # Load risks from CSV\n try:\n risks = load_risks_from_csv(args.input_file)\n calculator = RiskCalculator()\n\n for risk in risks:\n calculator.add_risk(risk)\n\n print(f\"Loaded {len(risks)} risks from {args.input_file}\")\n\n # Generate report\n report = calculator.generate_report()\n\n # Display summary\n summary = calculator.generate_summary()\n print(\"\\n\" + \"=\" * 60)\n print(\"Risk Assessment Summary\")\n print(\"=\" * 60)\n print(f\"Total Risks: {summary['total_risks']}\")\n print(f\"Total ALE: ${summary['total_ale']:,.0f}\")\n print(f\"\\nRisk Level Distribution:\")\n for level, count in summary['risk_levels'].items():\n if count > 0:\n print(f\" {level}: {count}\")\n\n print(f\"\\nTop 5 Risks by ALE:\")\n for name, ale in summary['top_5_risks']:\n print(f\" {name}: ${ale:,.0f}\")\n\n # Save report if output file specified\n if args.output:\n save_report_to_csv(report, args.output)\n\n print(\"\\nRisk Report:\")\n print(\"-\" * 120)\n for risk_data in report[:10]: # Show top 10\n print(f\"{risk_data['Risk ID']}: {risk_data['Risk Name']}\")\n print(f\" ALE: {risk_data['ALE']} | Risk Level: {risk_data['Risk Level']} | \"\n f\"SLA: {risk_data['Remediation SLA']}\")\n\n except FileNotFoundError:\n print(f\"Error: File '{args.input_file}' not found\")\n except Exception as e:\n print(f\"Error: {e}\")\n\n\nif __name__ == \"__main__\":\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":13709,"content_sha256":"db5fd62fe95fdaaa9894d5cbd2e4fceadfa2f3d9188beb8f95948bcb55645518"},{"filename":"scripts/vuln_prioritizer.py","content":"#!/usr/bin/env python3\n\"\"\"\nVulnerability Prioritization Tool\n\nPrioritizes vulnerabilities based on CVSS score combined with business context\nfactors such as asset criticality, exposure, exploit availability, and compensating controls.\n\nUsage:\n python vuln_prioritizer.py vulnerabilities.csv\n python vuln_prioritizer.py vulnerabilities.csv --output prioritized.csv\n python vuln_prioritizer.py --interactive\n\"\"\"\n\nimport argparse\nimport csv\nfrom dataclasses import dataclass\nfrom typing import List, Dict\nfrom datetime import datetime, timedelta\n\n\n@dataclass\nclass Vulnerability:\n \"\"\"Vulnerability data class\"\"\"\n cve_id: str\n title: str\n cvss_score: float\n affected_system: str\n asset_criticality: int # 1-5 scale\n exposure: str # internet_facing, internal, isolated\n data_sensitivity: str # highly_confidential, confidential, public\n exploit_available: bool\n exploit_in_wild: bool\n compensating_controls: bool\n discovered_date: str\n\n\nclass VulnerabilityPrioritizer:\n \"\"\"Vulnerability prioritization engine\"\"\"\n\n EXPOSURE_WEIGHT = {\n \"internet_facing\": 3,\n \"internal\": 2,\n \"isolated\": 1\n }\n\n DATA_SENSITIVITY_WEIGHT = {\n \"highly_confidential\": 3, # PII, PHI, financial\n \"confidential\": 2,\n \"public\": 1\n }\n\n SLA_MAPPING = {\n \"P0\": 1, # Critical - patch within 24-48 hours\n \"P1\": 7, # High - patch within 7 days\n \"P2\": 30, # Medium - patch within 30 days\n \"P3\": 90 # Low - patch within 90 days\n }\n\n def __init__(self):\n self.vulnerabilities: List[Vulnerability] = []\n\n def calculate_priority_score(self, vuln: Vulnerability) -> float:\n \"\"\"\n Calculate priority score based on CVSS + business context\n\n Formula:\n Priority Score = CVSS × exploit_multiplier × asset_multiplier × exposure_multiplier × data_sensitivity_multiplier × controls_multiplier\n \"\"\"\n\n # Base CVSS score (0-10)\n cvss_score = vuln.cvss_score\n\n # Exploit multipliers\n exploit_available_mult = 1.5 if vuln.exploit_available else 1.0\n exploit_in_wild_mult = 2.0 if vuln.exploit_in_wild else 1.0\n\n # Asset criticality multiplier (1-5 scale normalized)\n asset_mult = vuln.asset_criticality / 3.0\n\n # Exposure multiplier\n exposure_mult = self.EXPOSURE_WEIGHT.get(vuln.exposure, 2) / 2.0\n\n # Data sensitivity multiplier\n data_sens_mult = self.DATA_SENSITIVITY_WEIGHT.get(vuln.data_sensitivity, 2) / 2.0\n\n # Compensating controls reduction\n controls_mult = 0.5 if vuln.compensating_controls else 1.0\n\n # Calculate final priority score\n priority_score = (\n cvss_score *\n exploit_available_mult *\n exploit_in_wild_mult *\n asset_mult *\n exposure_mult *\n data_sens_mult *\n controls_mult\n )\n\n return priority_score\n\n def determine_priority_level(self, priority_score: float) -> str:\n \"\"\"Determine priority level (P0-P3) based on score\"\"\"\n if priority_score >= 14:\n return \"P0\" # Critical\n elif priority_score >= 10:\n return \"P1\" # High\n elif priority_score >= 6:\n return \"P2\" # Medium\n else:\n return \"P3\" # Low\n\n def calculate_due_date(self, vuln: Vulnerability, priority_level: str) -> str:\n \"\"\"Calculate patch due date based on priority level\"\"\"\n sla_days = self.SLA_MAPPING.get(priority_level, 90)\n discovered = datetime.strptime(vuln.discovered_date, \"%Y-%m-%d\")\n due_date = discovered + timedelta(days=sla_days)\n return due_date.strftime(\"%Y-%m-%d\")\n\n def generate_rationale(self, vuln: Vulnerability, priority_score: float) -> str:\n \"\"\"Generate human-readable rationale for prioritization\"\"\"\n factors = []\n\n if vuln.cvss_score >= 9.0:\n factors.append(\"Critical CVSS score\")\n elif vuln.cvss_score >= 7.0:\n factors.append(\"High CVSS score\")\n\n if vuln.exploit_in_wild:\n factors.append(\"Active exploitation in wild\")\n\n if vuln.exploit_available:\n factors.append(\"Public exploit available\")\n\n if vuln.exposure == \"internet_facing\":\n factors.append(\"Internet-facing system\")\n\n if vuln.asset_criticality >= 4:\n factors.append(\"Critical business system\")\n\n if vuln.data_sensitivity == \"highly_confidential\":\n factors.append(\"Contains sensitive data (PII/PHI)\")\n\n if vuln.compensating_controls:\n factors.append(\"Compensating controls in place (WAF/IPS)\")\n\n return \"; \".join(factors) if factors else \"Standard risk assessment\"\n\n def add_vulnerability(self, vuln: Vulnerability):\n \"\"\"Add vulnerability to assessment\"\"\"\n self.vulnerabilities.append(vuln)\n\n def generate_report(self) -> List[Dict]:\n \"\"\"Generate prioritized vulnerability report\"\"\"\n report = []\n\n for vuln in self.vulnerabilities:\n priority_score = self.calculate_priority_score(vuln)\n priority_level = self.determine_priority_level(priority_score)\n due_date = self.calculate_due_date(vuln, priority_level)\n rationale = self.generate_rationale(vuln, priority_score)\n\n report.append({\n \"CVE ID\": vuln.cve_id,\n \"Title\": vuln.title,\n \"Affected System\": vuln.affected_system,\n \"CVSS Score\": f\"{vuln.cvss_score:.1f}\",\n \"Priority Score\": f\"{priority_score:.2f}\",\n \"Priority Level\": priority_level,\n \"SLA Days\": self.SLA_MAPPING[priority_level],\n \"Discovered\": vuln.discovered_date,\n \"Due Date\": due_date,\n \"Exploit Available\": \"Yes\" if vuln.exploit_available else \"No\",\n \"Active Exploitation\": \"Yes\" if vuln.exploit_in_wild else \"No\",\n \"Asset Criticality\": vuln.asset_criticality,\n \"Exposure\": vuln.exposure,\n \"Data Sensitivity\": vuln.data_sensitivity,\n \"Compensating Controls\": \"Yes\" if vuln.compensating_controls else \"No\",\n \"Rationale\": rationale\n })\n\n # Sort by priority score (descending)\n report.sort(key=lambda x: float(x[\"Priority Score\"]), reverse=True)\n\n return report\n\n def generate_summary(self) -> Dict:\n \"\"\"Generate summary statistics\"\"\"\n if not self.vulnerabilities:\n return {}\n\n priority_counts = {\"P0\": 0, \"P1\": 0, \"P2\": 0, \"P3\": 0}\n\n for vuln in self.vulnerabilities:\n priority_score = self.calculate_priority_score(vuln)\n priority_level = self.determine_priority_level(priority_score)\n priority_counts[priority_level] += 1\n\n # Count exploitable vulnerabilities\n exploitable = sum(1 for v in self.vulnerabilities if v.exploit_available)\n actively_exploited = sum(1 for v in self.vulnerabilities if v.exploit_in_wild)\n\n # Count by exposure\n internet_facing = sum(1 for v in self.vulnerabilities if v.exposure == \"internet_facing\")\n\n return {\n \"total_vulnerabilities\": len(self.vulnerabilities),\n \"priority_distribution\": priority_counts,\n \"exploitable_count\": exploitable,\n \"actively_exploited_count\": actively_exploited,\n \"internet_facing_count\": internet_facing\n }\n\n\ndef load_vulnerabilities_from_csv(filename: str) -> List[Vulnerability]:\n \"\"\"Load vulnerabilities from CSV file\"\"\"\n vulnerabilities = []\n\n with open(filename, 'r') as f:\n reader = csv.DictReader(f)\n for row in reader:\n vuln = Vulnerability(\n cve_id=row['cve_id'],\n title=row['title'],\n cvss_score=float(row['cvss_score']),\n affected_system=row['affected_system'],\n asset_criticality=int(row['asset_criticality']),\n exposure=row['exposure'],\n data_sensitivity=row['data_sensitivity'],\n exploit_available=row['exploit_available'].lower() == 'true',\n exploit_in_wild=row['exploit_in_wild'].lower() == 'true',\n compensating_controls=row['compensating_controls'].lower() == 'true',\n discovered_date=row['discovered_date']\n )\n vulnerabilities.append(vuln)\n\n return vulnerabilities\n\n\ndef save_report_to_csv(report: List[Dict], filename: str):\n \"\"\"Save vulnerability report to CSV file\"\"\"\n if not report:\n print(\"No data to save\")\n return\n\n with open(filename, 'w', newline='') as f:\n writer = csv.DictWriter(f, fieldnames=report[0].keys())\n writer.writeheader()\n writer.writerows(report)\n\n print(f\"✓ Report saved to {filename}\")\n\n\ndef interactive_mode():\n \"\"\"Interactive vulnerability prioritization mode\"\"\"\n prioritizer = VulnerabilityPrioritizer()\n\n print(\"=\" * 60)\n print(\"Vulnerability Prioritization Tool - Interactive Mode\")\n print(\"=\" * 60)\n\n while True:\n print(\"\\nOptions:\")\n print(\"1. Add new vulnerability\")\n print(\"2. Generate prioritization report\")\n print(\"3. View summary statistics\")\n print(\"4. Exit\")\n\n choice = input(\"\\nEnter choice (1-4): \").strip()\n\n if choice == \"1\":\n print(\"\\n--- Add New Vulnerability ---\")\n cve_id = input(\"CVE ID (e.g., CVE-2021-44228): \").strip()\n title = input(\"Title: \").strip()\n cvss_score = float(input(\"CVSS Score (0-10): \"))\n affected_system = input(\"Affected System: \").strip()\n asset_criticality = int(input(\"Asset Criticality (1-5, 5=most critical): \"))\n\n print(\"\\nExposure:\")\n print(\" 1. internet_facing\")\n print(\" 2. internal\")\n print(\" 3. isolated\")\n exposure_choice = input(\"Select (1-3): \")\n exposure_map = {\"1\": \"internet_facing\", \"2\": \"internal\", \"3\": \"isolated\"}\n exposure = exposure_map.get(exposure_choice, \"internal\")\n\n print(\"\\nData Sensitivity:\")\n print(\" 1. highly_confidential (PII/PHI/Financial)\")\n print(\" 2. confidential\")\n print(\" 3. public\")\n sens_choice = input(\"Select (1-3): \")\n sens_map = {\"1\": \"highly_confidential\", \"2\": \"confidential\", \"3\": \"public\"}\n data_sensitivity = sens_map.get(sens_choice, \"confidential\")\n\n exploit_available = input(\"Public exploit available? (yes/no): \").lower() == \"yes\"\n exploit_in_wild = input(\"Active exploitation in wild? (yes/no): \").lower() == \"yes\"\n compensating_controls = input(\"Compensating controls in place? (yes/no): \").lower() == \"yes\"\n discovered_date = input(\"Discovered date (YYYY-MM-DD): \").strip()\n\n vuln = Vulnerability(\n cve_id, title, cvss_score, affected_system, asset_criticality,\n exposure, data_sensitivity, exploit_available, exploit_in_wild,\n compensating_controls, discovered_date\n )\n prioritizer.add_vulnerability(vuln)\n\n # Calculate and display priority\n priority_score = prioritizer.calculate_priority_score(vuln)\n priority_level = prioritizer.determine_priority_level(priority_score)\n due_date = prioritizer.calculate_due_date(vuln, priority_level)\n rationale = prioritizer.generate_rationale(vuln, priority_score)\n\n print(f\"\\n✓ Vulnerability added successfully!\")\n print(f\" Priority Score: {priority_score:.2f}\")\n print(f\" Priority Level: {priority_level}\")\n print(f\" SLA: Patch within {prioritizer.SLA_MAPPING[priority_level]} days\")\n print(f\" Due Date: {due_date}\")\n print(f\" Rationale: {rationale}\")\n\n elif choice == \"2\":\n if not prioritizer.vulnerabilities:\n print(\"No vulnerabilities added yet. Please add a vulnerability first.\")\n continue\n\n report = prioritizer.generate_report()\n\n print(\"\\n\" + \"=\" * 150)\n print(\"Vulnerability Prioritization Report\")\n print(\"=\" * 150)\n print(f\"{'CVE ID':\u003c20} {'System':\u003c25} {'CVSS':\u003c6} {'Priority':\u003c10} {'Level':\u003c7} {'Due Date':\u003c12} {'Rationale':\u003c50}\")\n print(\"-\" * 150)\n\n for row in report:\n print(f\"{row['CVE ID']:\u003c20} \"\n f\"{row['Affected System']:\u003c25} \"\n f\"{row['CVSS Score']:\u003c6} \"\n f\"{row['Priority Score']:\u003c10} \"\n f\"{row['Priority Level']:\u003c7} \"\n f\"{row['Due Date']:\u003c12} \"\n f\"{row['Rationale']:\u003c50}\")\n\n elif choice == \"3\":\n summary = prioritizer.generate_summary()\n if not summary:\n print(\"No vulnerabilities added yet. Please add a vulnerability first.\")\n continue\n\n print(\"\\n\" + \"=\" * 60)\n print(\"Vulnerability Summary\")\n print(\"=\" * 60)\n print(f\"Total Vulnerabilities: {summary['total_vulnerabilities']}\")\n print(f\"\\nPriority Distribution:\")\n for level, count in summary['priority_distribution'].items():\n print(f\" {level}: {count}\")\n print(f\"\\nExploitability:\")\n print(f\" Public exploits available: {summary['exploitable_count']}\")\n print(f\" Active exploitation: {summary['actively_exploited_count']}\")\n print(f\"\\nExposure:\")\n print(f\" Internet-facing systems: {summary['internet_facing_count']}\")\n\n elif choice == \"4\":\n print(\"Exiting...\")\n break\n\n else:\n print(\"Invalid choice. Please enter 1-4.\")\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Vulnerability Prioritization Tool\")\n parser.add_argument('input_file', nargs='?', help='CSV file containing vulnerability data')\n parser.add_argument('--output', '-o', help='Output CSV file for prioritized report')\n parser.add_argument('--interactive', '-i', action='store_true',\n help='Run in interactive mode')\n parser.add_argument('--filter-level', choices=['P0', 'P1', 'P2', 'P3'],\n help='Filter to show only specified priority level')\n\n args = parser.parse_args()\n\n if args.interactive:\n interactive_mode()\n return\n\n if not args.input_file:\n print(\"Error: Please provide an input file or use --interactive mode\")\n parser.print_help()\n return\n\n try:\n vulnerabilities = load_vulnerabilities_from_csv(args.input_file)\n prioritizer = VulnerabilityPrioritizer()\n\n for vuln in vulnerabilities:\n prioritizer.add_vulnerability(vuln)\n\n print(f\"✓ Loaded {len(vulnerabilities)} vulnerabilities from {args.input_file}\")\n\n # Generate report\n report = prioritizer.generate_report()\n\n # Filter if requested\n if args.filter_level:\n report = [r for r in report if r['Priority Level'] == args.filter_level]\n\n # Display summary\n summary = prioritizer.generate_summary()\n print(\"\\n\" + \"=\" * 60)\n print(\"Vulnerability Summary\")\n print(\"=\" * 60)\n print(f\"Total Vulnerabilities: {summary['total_vulnerabilities']}\")\n print(f\"\\nPriority Distribution:\")\n for level, count in summary['priority_distribution'].items():\n print(f\" {level}: {count}\")\n print(f\"\\nExploitability:\")\n print(f\" Public exploits available: {summary['exploitable_count']}\")\n print(f\" Active exploitation: {summary['actively_exploited_count']}\")\n\n # Display top prioritized vulnerabilities\n print(\"\\n\" + \"=\" * 150)\n print(\"Top Prioritized Vulnerabilities\")\n print(\"=\" * 150)\n print(f\"{'CVE ID':\u003c20} {'System':\u003c30} {'CVSS':\u003c6} {'Priority':\u003c10} {'Level':\u003c7} {'Due Date':\u003c12}\")\n print(\"-\" * 150)\n\n for row in report[:15]: # Show top 15\n print(f\"{row['CVE ID']:\u003c20} \"\n f\"{row['Affected System']:\u003c30} \"\n f\"{row['CVSS Score']:\u003c6} \"\n f\"{row['Priority Score']:\u003c10} \"\n f\"{row['Priority Level']:\u003c7} \"\n f\"{row['Due Date']:\u003c12}\")\n\n # Save report if output file specified\n if args.output:\n save_report_to_csv(report, args.output)\n\n except FileNotFoundError:\n print(f\"Error: File '{args.input_file}' not found\")\n except Exception as e:\n print(f\"Error: {e}\")\n\n\nif __name__ == \"__main__\":\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":16795,"content_sha256":"c21509925701e49e895c09bef9789d205623b7f711583d55517462f05de563e4"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"Security & Compliance Expert","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Core Principles","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"1. Defense in Depth","type":"text"}]},{"type":"paragraph","content":[{"text":"Apply multiple layers of security controls so that if one fails, others provide protection. Never rely on a single security mechanism.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2. Zero Trust Architecture","type":"text"}]},{"type":"paragraph","content":[{"text":"Never trust, always verify. Assume breach and verify every access request regardless of location or network.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3. Least Privilege","type":"text"}]},{"type":"paragraph","content":[{"text":"Grant the minimum access necessary for users and systems to perform their functions. Regularly review and revoke unused permissions.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"4. Security by Design","type":"text"}]},{"type":"paragraph","content":[{"text":"Integrate security requirements from the earliest stages of system design, not as an afterthought.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"5. Continuous Monitoring","type":"text"}]},{"type":"paragraph","content":[{"text":"Implement ongoing monitoring and alerting to detect anomalies and security events in real-time.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"6. Risk-Based Approach","type":"text"}]},{"type":"paragraph","content":[{"text":"Prioritize security efforts based on risk assessment, focusing resources on the most critical assets and likely threats.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"7. Compliance as Foundation","type":"text"}]},{"type":"paragraph","content":[{"text":"Use compliance frameworks as a baseline, but go beyond minimum requirements to achieve actual security.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"8. Incident Readiness","type":"text"}]},{"type":"paragraph","content":[{"text":"Prepare for security incidents through planning, testing, and regular tabletop exercises. Assume compromise will occur.","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Security & Compliance Lifecycle","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 1: Assess & Plan","type":"text"}]},{"type":"paragraph","content":[{"text":"Objective","type":"text","marks":[{"type":"strong"}]},{"text":": Understand current security posture and compliance requirements","type":"text"}]},{"type":"paragraph","content":[{"text":"Activities","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conduct security assessments and gap analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Identify compliance requirements (SOC2, ISO27001, GDPR, HIPAA, PCI-DSS)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Perform risk assessments and threat modeling","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Define security policies and standards","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Establish security governance structure","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Create security roadmap with prioritized initiatives","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Deliverables","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Risk register with prioritized risks","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Compliance gap analysis report","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security architecture documentation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security policies and procedures","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security roadmap and budget","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 2: Design & Architect","type":"text"}]},{"type":"paragraph","content":[{"text":"Objective","type":"text","marks":[{"type":"strong"}]},{"text":": Design secure systems and architectures","type":"text"}]},{"type":"paragraph","content":[{"text":"Activities","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design defense-in-depth architectures","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement Zero Trust network architecture","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design identity and access management (IAM) systems","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Architect data protection and encryption solutions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design secure CI/CD pipelines","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Create threat models for applications and systems","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Define security controls and compensating controls","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Deliverables","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security architecture diagrams","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Threat models (STRIDE, PASTA, or attack trees)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Data flow diagrams with security boundaries","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Encryption and key management design","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"IAM design with RBAC/ABAC models","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security control matrix","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 3: Implement & Harden","type":"text"}]},{"type":"paragraph","content":[{"text":"Objective","type":"text","marks":[{"type":"strong"}]},{"text":": Deploy security controls and harden systems","type":"text"}]},{"type":"paragraph","content":[{"text":"Activities","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement security controls (preventive, detective, corrective)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Configure security tools (SIEM, EDR, CASB, WAF, IDS/IPS)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Harden operating systems and applications","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement encryption at rest and in transit","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Deploy multi-factor authentication (MFA)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Configure logging and monitoring","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement data loss prevention (DLP)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Set up vulnerability management program","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Deliverables","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Hardening baselines and configuration standards","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Deployed security tools and controls","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Encryption implementation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"MFA deployment","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security monitoring dashboards","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Vulnerability management procedures","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 4: Monitor & Detect","type":"text"}]},{"type":"paragraph","content":[{"text":"Objective","type":"text","marks":[{"type":"strong"}]},{"text":": Continuously monitor for threats and anomalies","type":"text"}]},{"type":"paragraph","content":[{"text":"Activities","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Monitor security logs and events (SIEM)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Analyze security alerts and anomalies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conduct threat hunting","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Perform vulnerability scanning and penetration testing","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Monitor compliance controls","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Track security metrics and KPIs","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Review access logs and privileged account activity","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Analyze threat intelligence feeds","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Deliverables","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security operations center (SOC) runbooks","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Alert triage and escalation procedures","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Threat hunting playbooks","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Vulnerability scan reports","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Penetration test reports","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security metrics dashboard","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Compliance monitoring reports","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 5: Respond & Recover","type":"text"}]},{"type":"paragraph","content":[{"text":"Objective","type":"text","marks":[{"type":"strong"}]},{"text":": Respond to security incidents and recover operations","type":"text"}]},{"type":"paragraph","content":[{"text":"Activities","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Execute incident response plan","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Contain and eradicate threats","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Perform forensic analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Recover affected systems","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conduct post-incident reviews","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Update security controls based on lessons learned","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Report incidents to stakeholders and regulators","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Improve detection rules and response procedures","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Deliverables","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Incident response reports","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Forensic analysis findings","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Root cause analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Remediation plans","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Updated incident response playbooks","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Regulatory breach notifications (if required)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Post-incident review and recommendations","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 6: Audit & Improve","type":"text"}]},{"type":"paragraph","content":[{"text":"Objective","type":"text","marks":[{"type":"strong"}]},{"text":": Validate compliance and continuously improve security","type":"text"}]},{"type":"paragraph","content":[{"text":"Activities","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conduct internal audits","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Prepare for external audits (SOC2, ISO27001)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Perform compliance assessments","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Review and update security policies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conduct security training and awareness programs","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Perform tabletop exercises and disaster recovery drills","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Update risk assessments","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement security improvements","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Deliverables","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Audit reports (internal and external)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SOC2 Type II report","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ISO27001 certification","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Compliance attestations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Updated policies and procedures","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Training completion metrics","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tabletop exercise results","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Continuous improvement plan","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Decision Frameworks","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"1. Risk Assessment Framework","type":"text"}]},{"type":"paragraph","content":[{"text":"When to use","type":"text","marks":[{"type":"strong"}]},{"text":": Evaluating security risks and prioritizing mitigation efforts","type":"text"}]},{"type":"paragraph","content":[{"text":"Process","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"1. Identify Assets\n - What systems, data, and services need protection?\n - What is the business value of each asset?\n - Who are the asset owners?\n\n2. Identify Threats\n - What threat actors might target these assets? (nation-state, cybercriminals, insiders)\n - What are their motivations? (financial gain, espionage, disruption)\n - What are current threat trends?\n\n3. Identify Vulnerabilities\n - What weaknesses exist in systems or processes?\n - What security controls are missing or ineffective?\n - What are known CVEs affecting your systems?\n\n4. Calculate Risk\n Risk = Likelihood × Impact\n\n Likelihood scale (1-5):\n 1 = Rare (\u003c 5% chance in 1 year)\n 2 = Unlikely (5-25%)\n 3 = Possible (25-50%)\n 4 = Likely (50-75%)\n 5 = Almost Certain (> 75%)\n\n Impact scale (1-5):\n 1 = Minimal (\u003c $10K loss, no data breach)\n 2 = Minor ($10K-$100K, limited data exposure)\n 3 = Moderate ($100K-$1M, significant data breach)\n 4 = Major ($1M-$10M, extensive data breach, regulatory fines)\n 5 = Catastrophic (> $10M, business-threatening)\n\n Risk Score = Likelihood × Impact (max 25)\n\n5. Prioritize Risks\n - Critical: Risk score 15-25 (immediate action)\n - High: Risk score 10-14 (action within 30 days)\n - Medium: Risk score 5-9 (action within 90 days)\n - Low: Risk score 1-4 (monitor and accept)\n\n6. Determine Risk Response\n - Mitigate: Implement controls to reduce risk\n - Accept: Document acceptance if risk is within tolerance\n - Transfer: Use insurance or third-party services\n - Avoid: Eliminate the activity that creates risk","type":"text"}]},{"type":"paragraph","content":[{"text":"Output","type":"text","marks":[{"type":"strong"}]},{"text":": Risk register with prioritized risks and mitigation plans","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2. Security Control Selection","type":"text"}]},{"type":"paragraph","content":[{"text":"When to use","type":"text","marks":[{"type":"strong"}]},{"text":": Choosing appropriate security controls for identified risks","type":"text"}]},{"type":"paragraph","content":[{"text":"Framework","type":"text","marks":[{"type":"strong"}]},{"text":": Use NIST CSF categories or CIS Controls","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"NIST CSF Functions:\n1. Identify (ID)\n - Asset Management\n - Risk Assessment\n - Governance\n\n2. Protect (PR)\n - Access Control\n - Data Security\n - Protective Technology\n\n3. Detect (DE)\n - Anomalies and Events\n - Security Monitoring\n - Detection Processes\n\n4. Respond (RS)\n - Response Planning\n - Communications\n - Analysis and Mitigation\n\n5. Recover (RC)\n - Recovery Planning\n - Improvements\n - Communications\n\nControl Types:\n- Preventive: Stop incidents before they occur (MFA, firewalls, encryption)\n- Detective: Identify incidents when they occur (SIEM, IDS, log monitoring)\n- Corrective: Fix issues after detection (patching, incident response)\n- Deterrent: Discourage attackers (security policies, warnings)\n- Compensating: Alternative controls when primary controls aren't feasible\n\nSelection Criteria:\n1. Does it address the identified risk?\n2. Is it cost-effective? (Control cost \u003c Risk value)\n3. Is it technically feasible?\n4. Does it meet compliance requirements?\n5. Can we maintain and monitor it?","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3. Compliance Framework Selection","type":"text"}]},{"type":"paragraph","content":[{"text":"When to use","type":"text","marks":[{"type":"strong"}]},{"text":": Determining which compliance frameworks to implement","type":"text"}]},{"type":"paragraph","content":[{"text":"Decision Tree","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"What type of organization are you?\n\n├─ SaaS/Cloud Service Provider\n│ ├─ Selling to enterprises? → SOC2 Type II (required)\n│ ├─ International customers? → ISO27001 (strongly recommended)\n│ ├─ Handling health data? → HIPAA + HITRUST\n│ └─ Handling payment cards? → PCI-DSS\n\n├─ Healthcare Provider/Payer\n│ ├─ U.S.-based → HIPAA (required)\n│ ├─ International → HIPAA + GDPR\n│ └─ Plus: HITRUST for comprehensive framework\n\n├─ Financial Services\n│ ├─ U.S. banks → GLBA, SOX (if public)\n│ ├─ Payment processing → PCI-DSS (required)\n│ ├─ International → ISO27001, local regulations\n│ └─ Plus: NIST CSF for framework\n\n├─ E-commerce/Retail\n│ ├─ Accept credit cards → PCI-DSS (required)\n│ ├─ EU customers → GDPR (required)\n│ ├─ California customers → CCPA\n│ └─ B2B sales → SOC2 Type II\n\n└─ General Enterprise\n ├─ Selling to enterprises → SOC2 Type II\n ├─ Want broad recognition → ISO27001\n ├─ Government contracts → FedRAMP, NIST 800-53\n └─ Industry-specific → Check sector regulations\n\nMulti-Framework Strategy:\n- Start with: SOC2 or ISO27001 (choose one as foundation)\n- Add: Data privacy regulations (GDPR, CCPA) as needed\n- Layer on: Industry-specific requirements","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"4. Incident Severity Classification","type":"text"}]},{"type":"paragraph","content":[{"text":"When to use","type":"text","marks":[{"type":"strong"}]},{"text":": Triaging and responding to security incidents","type":"text"}]},{"type":"paragraph","content":[{"text":"Severity Levels","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"P0 - Critical (Immediate Response)\n- Active breach with data exfiltration occurring\n- Ransomware encryption in progress\n- Complete system outage of critical services\n- Unauthorized access to production databases\n- Response: Engage CIRT immediately, executive notification, 24/7 effort\n\nP1 - High (Response within 1 hour)\n- Confirmed malware on critical systems\n- Attempted unauthorized access to sensitive data\n- DDoS attack affecting availability\n- Significant vulnerability with active exploits\n- Response: Engage CIRT, manager notification, work until contained\n\nP2 - Medium (Response within 4 hours)\n- Malware on non-critical systems\n- Suspicious account activity\n- Policy violations with security impact\n- Vulnerability requiring patching\n- Response: Security team investigation, business hours\n\nP3 - Low (Response within 24 hours)\n- Failed login attempts (below threshold)\n- Minor policy violations\n- Informational security events\n- Response: Standard queue, document findings\n\nClassification Factors:\n1. Data confidentiality impact (PHI, PII, financial, IP)\n2. System availability impact (revenue, operations)\n3. Data integrity impact (corruption, unauthorized changes)\n4. Number of affected systems/users\n5. Regulatory reporting requirements","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"5. Vulnerability Prioritization","type":"text"}]},{"type":"paragraph","content":[{"text":"When to use","type":"text","marks":[{"type":"strong"}]},{"text":": Prioritizing vulnerability remediation","type":"text"}]},{"type":"paragraph","content":[{"text":"Framework","type":"text","marks":[{"type":"strong"}]},{"text":": Enhanced CVSS with business context","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"Base CVSS Score × Business Context Multiplier = Priority Score\n\nCVSS Severity Ranges:\n- Critical: 9.0-10.0\n- High: 7.0-8.9\n- Medium: 4.0-6.9\n- Low: 0.1-3.9\n\nBusiness Context Multipliers:\n- Internet-facing production system: 2.0×\n- Internal production system: 1.5×\n- Systems with sensitive data: 1.5×\n- Development/test environment: 0.5×\n- Active exploit in the wild: 2.0×\n- Compensating controls in place: 0.7×\n\nPriority Levels:\n- P0 (Critical): Score ≥ 14 → Patch within 24-48 hours\n- P1 (High): Score 10-13.9 → Patch within 7 days\n- P2 (Medium): Score 6-9.9 → Patch within 30 days\n- P3 (Low): Score \u003c 6 → Patch within 90 days or accept risk\n\nAdditional Considerations:\n- Can the system be isolated/segmented?\n- Are there effective detective controls?\n- What is the patching complexity/risk?\n- Is there a vendor patch available?","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"6. Third-Party Risk Assessment","type":"text"}]},{"type":"paragraph","content":[{"text":"When to use","type":"text","marks":[{"type":"strong"}]},{"text":": Evaluating security risks of vendors and partners","type":"text"}]},{"type":"paragraph","content":[{"text":"Assessment Framework","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"1. Categorize Vendor Risk Level\n\nLow Risk (Minimal assessment):\n- No access to systems or data\n- Limited integration\n- Non-critical service\n→ Simple questionnaire\n\nMedium Risk (Standard assessment):\n- Limited system access\n- Non-sensitive data access\n- Important but not critical service\n→ Security questionnaire + evidence review\n\nHigh Risk (Comprehensive assessment):\n- Production system access\n- Sensitive data processing\n- Critical service dependency\n→ Full assessment + audit reports + pen test\n\nCritical Risk (Extensive assessment):\n- Full production access\n- PHI/PII processing\n- Business-critical dependency\n→ On-site audit + continuous monitoring + SLA\n\n2. Assessment Components\n\nFor Medium/High/Critical vendors:\n□ Security questionnaire (SIG, CAIQ, or custom)\n□ Compliance certifications (SOC2, ISO27001)\n□ Insurance certificates (cyber liability)\n□ Security policies and procedures\n□ Incident response plan\n□ Disaster recovery/business continuity plan\n□ Data processing agreement (DPA)\n□ Penetration test results (for high/critical)\n□ Right to audit clause in contract\n\n3. Ongoing Monitoring\n\n- Annual reassessment\n- Monitor for breaches/incidents\n- Review security updates and patches\n- Track compliance certification renewals\n- Conduct periodic audits (for critical vendors)\n\n4. Vendor Risk Score\n\nCalculate score (0-100):\n- Security maturity: 40 points\n- Compliance certifications: 20 points\n- Incident history: 15 points\n- Financial stability: 15 points\n- References and reputation: 10 points\n\nAction based on score:\n- 80-100: Approved\n- 60-79: Approved with conditions\n- 40-59: Requires remediation plan\n- \u003c 40: Do not engage","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Key Security Frameworks & Standards","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"NIST Cybersecurity Framework (CSF)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Purpose","type":"text","marks":[{"type":"strong"}]},{"text":": Risk-based framework for improving cybersecurity","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Structure","type":"text","marks":[{"type":"strong"}]},{"text":": 5 Functions, 23 Categories, 108 Subcategories","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Best for","type":"text","marks":[{"type":"strong"}]},{"text":": General organizations, government contractors","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Maturity model","type":"text","marks":[{"type":"strong"}]},{"text":": Tier 1 (Partial) to Tier 4 (Adaptive)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"CIS Critical Security Controls","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Purpose","type":"text","marks":[{"type":"strong"}]},{"text":": Prioritized set of actions for cyber defense","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Structure","type":"text","marks":[{"type":"strong"}]},{"text":": 18 Controls with Implementation Groups (IG1, IG2, IG3)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Best for","type":"text","marks":[{"type":"strong"}]},{"text":": Practical implementation guidance","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Focus","type":"text","marks":[{"type":"strong"}]},{"text":": Defense against common attack patterns","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"ISO/IEC 27001","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Purpose","type":"text","marks":[{"type":"strong"}]},{"text":": International standard for information security management","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Structure","type":"text","marks":[{"type":"strong"}]},{"text":": 14 domains, 114 controls (Annex A)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Best for","type":"text","marks":[{"type":"strong"}]},{"text":": International recognition, formal certification","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Requirements","type":"text","marks":[{"type":"strong"}]},{"text":": ISMS (Information Security Management System)","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":"Purpose","type":"text","marks":[{"type":"strong"}]},{"text":": Service organization controls for security and availability","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Structure","type":"text","marks":[{"type":"strong"}]},{"text":": Trust Service Criteria (Security, Availability, Confidentiality, Processing Integrity, Privacy)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Best for","type":"text","marks":[{"type":"strong"}]},{"text":": SaaS companies, cloud service providers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Audit","type":"text","marks":[{"type":"strong"}]},{"text":": 3-12 month observation period","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"NIST 800-53","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Purpose","type":"text","marks":[{"type":"strong"}]},{"text":": Security controls for federal systems","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Structure","type":"text","marks":[{"type":"strong"}]},{"text":": 20 families, 1000+ controls","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Best for","type":"text","marks":[{"type":"strong"}]},{"text":": Government contractors, FedRAMP","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Baselines","type":"text","marks":[{"type":"strong"}]},{"text":": Low, Moderate, High impact systems","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"GDPR (General Data Protection Regulation)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Purpose","type":"text","marks":[{"type":"strong"}]},{"text":": EU data privacy regulation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Scope","type":"text","marks":[{"type":"strong"}]},{"text":": Any organization processing EU residents' data","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Requirements","type":"text","marks":[{"type":"strong"}]},{"text":": Lawful basis, consent, data subject rights, breach notification","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Penalties","type":"text","marks":[{"type":"strong"}]},{"text":": Up to 4% of global revenue or €20M","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"HIPAA (Health Insurance Portability and Accountability Act)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Purpose","type":"text","marks":[{"type":"strong"}]},{"text":": Protect health information (PHI)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Scope","type":"text","marks":[{"type":"strong"}]},{"text":": Healthcare providers, payers, business associates","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Requirements","type":"text","marks":[{"type":"strong"}]},{"text":": Administrative, Physical, Technical safeguards","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Penalties","type":"text","marks":[{"type":"strong"}]},{"text":": $100-$50,000 per violation, criminal charges possible","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"PCI-DSS (Payment Card Industry Data Security Standard)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Purpose","type":"text","marks":[{"type":"strong"}]},{"text":": Protect cardholder data","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Structure","type":"text","marks":[{"type":"strong"}]},{"text":": 12 requirements, 6 control objectives","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Scope","type":"text","marks":[{"type":"strong"}]},{"text":": Any organization storing, processing, or transmitting card data","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Levels","type":"text","marks":[{"type":"strong"}]},{"text":": Based on transaction volume (Level 1-4)","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Core Security Domains","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"1. Identity & Access Management (IAM)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Authentication mechanisms (MFA, SSO, passwordless)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Authorization models (RBAC, ABAC, ReBAC)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Privileged access management (PAM)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Identity governance and administration (IGA)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Directory services (Active Directory, LDAP, Okta, Auth0)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2. Network Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Network segmentation and micro-segmentation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Firewalls (next-gen, WAF, application-layer)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Intrusion detection/prevention (IDS/IPS)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"VPN and secure remote access","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Zero Trust network architecture (ZTNA)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"DDoS protection","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3. Data Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Encryption at rest and in transit (AES-256, TLS 1.3)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Key management (KMS, HSM)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Data classification and labeling","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Data loss prevention (DLP)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Database security (encryption, masking, tokenization)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Secrets management (Vault, AWS Secrets Manager)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"4. Application Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Secure SDLC and DevSecOps","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SAST (Static Application Security Testing)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"DAST (Dynamic Application Security Testing)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SCA (Software Composition Analysis)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Secure code review","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"OWASP Top 10 mitigation","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"5. Cloud Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Cloud security posture management (CSPM)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Cloud access security broker (CASB)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Container security (image scanning, runtime protection)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Serverless security","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Infrastructure as Code (IaC) security scanning","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Multi-cloud security architecture","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"6. Endpoint Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Endpoint detection and response (EDR)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Antivirus and anti-malware","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Host-based firewalls","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Device encryption (BitLocker, FileVault)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mobile device management (MDM)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Patch management","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"7. Security Operations","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security Information and Event Management (SIEM)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security Orchestration, Automation, and Response (SOAR)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Threat intelligence platforms (TIP)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Threat hunting","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Vulnerability management","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Penetration testing and red teaming","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"8. Incident Response","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Incident response plan and playbooks","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Computer forensics and investigation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Malware analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Threat containment and eradication","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Post-incident review and lessons learned","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Regulatory breach notification","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"9. Governance, Risk & Compliance (GRC)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security policies and procedures","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Risk assessment and management","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Compliance management and auditing","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security awareness training","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Vendor risk management","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Business continuity and disaster recovery","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Security Metrics & KPIs","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Risk & Compliance Metrics","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Number of critical/high risks open","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Risk remediation time (mean time to remediate)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Compliance audit findings (open/closed)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Compliance control effectiveness rate","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Policy acknowledgment completion rate","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Training completion rate","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Vulnerability Management Metrics","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mean time to detect (MTTD) vulnerabilities","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mean time to patch (MTTP)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Vulnerability backlog (total open, by severity)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Patch compliance rate (% systems patched within SLA)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Vulnerability recurrence rate","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Incident Response Metrics","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mean time to detect (MTTD) incidents","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mean time to respond (MTTR)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mean time to contain (MTTC)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mean time to recover (MTTR)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Number of incidents by severity","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Incident recurrence rate","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"False positive rate","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Security Operations Metrics","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SIEM alert volume (total, by severity)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Alert triage time","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Alert false positive rate","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security tool coverage (% assets monitored)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Threat hunting coverage (% environment reviewed)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Penetration test findings","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Access Management Metrics","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"MFA adoption rate","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Privileged account review completion rate","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Access certification completion rate","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Orphaned account count","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Password policy compliance rate","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Failed login attempt rate","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Awareness & Culture Metrics","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Phishing simulation click rate","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security training completion rate","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security awareness quiz scores","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security policy violations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security-related helpdesk tickets","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Security Tools Ecosystem","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"SIEM (Security Information & Event Management)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Splunk Enterprise Security","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"IBM QRadar","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Microsoft Sentinel","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Elastic Security","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Sumo Logic","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"EDR/XDR (Endpoint/Extended Detection & Response)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"CrowdStrike Falcon","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SentinelOne","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Microsoft Defender for Endpoint","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Palo Alto Cortex XDR","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Carbon Black","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Vulnerability Management","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tenable Nessus/Tenable.io","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Qualys VMDR","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Rapid7 InsightVM","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Greenbone OpenVAS (open source)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Cloud Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Wiz","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Prisma Cloud (Palo Alto)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Lacework","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Orca Security","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"AWS Security Hub / Azure Security Center / GCP Security Command Center","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"SAST/DAST","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Snyk","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Veracode","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Checkmarx","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SonarQube","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"OWASP ZAP (open source)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Container Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Aqua Security","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Sysdig Secure","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Prisma Cloud Compute","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Trivy (open source)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Secrets Management","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"HashiCorp Vault","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"AWS Secrets Manager","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Azure Key Vault","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"CyberArk","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Identity & Access","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Okta","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Auth0","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Azure AD / Entra ID","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Ping Identity","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"CyberArk (PAM)","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Common Security Workflows","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"1. Security Incident Response Workflow","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"1. Detection & Alert\n ↓\n2. Triage & Classification\n - Determine severity (P0-P3)\n - Assign to responder\n ↓\n3. Investigation\n - Gather evidence\n - Analyze logs (SIEM)\n - Determine scope\n ↓\n4. Containment\n - Isolate affected systems\n - Block malicious IPs/domains\n - Disable compromised accounts\n ↓\n5. Eradication\n - Remove malware\n - Close vulnerabilities\n - Patch systems\n ↓\n6. Recovery\n - Restore from backups\n - Verify system integrity\n - Return to production\n ↓\n7. Post-Incident Review\n - Document timeline\n - Root cause analysis\n - Update playbooks\n - Implement improvements\n ↓\n8. Reporting\n - Executive summary\n - Regulatory notification (if required)\n - Stakeholder communication","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2. Vulnerability Management Workflow","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"1. Asset Discovery\n - Scan network for assets\n - Maintain asset inventory\n ↓\n2. Vulnerability Scanning\n - Authenticated scans\n - Unauthenticated scans\n - Agent-based monitoring\n ↓\n3. Assessment & Validation\n - Validate findings\n - Remove false positives\n - Add business context\n ↓\n4. Prioritization\n - Apply CVSS + context\n - Assign severity (P0-P3)\n - Create remediation tickets\n ↓\n5. Remediation\n - Patch systems\n - Apply compensating controls\n - Update configurations\n ↓\n6. Verification\n - Rescan to confirm fix\n - Update vulnerability status\n ↓\n7. Reporting\n - Metrics dashboard\n - Executive reports\n - Trend analysis","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3. Access Review Workflow","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"1. Schedule Review (Quarterly)\n ↓\n2. Generate Access Reports\n - User access by role\n - Privileged accounts\n - Service accounts\n - Orphaned accounts\n ↓\n3. Distribute to Managers\n - Each manager reviews their team\n - Certify appropriate access\n ↓\n4. Review & Certify\n - Approve legitimate access\n - Flag inappropriate access\n - Identify orphaned accounts\n ↓\n5. Remediation\n - Revoke unapproved access\n - Disable orphaned accounts\n - Update RBAC assignments\n ↓\n6. Document & Report\n - Certification completion rate\n - Access changes made\n - Compliance evidence","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"4. SOC2 Audit Preparation Workflow","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"1. Scoping (3-4 months before)\n - Define in-scope systems\n - Select Trust Service Criteria\n - Engage auditor\n ↓\n2. Gap Assessment (2-3 months before)\n - Map controls to requirements\n - Identify control gaps\n - Create remediation plan\n ↓\n3. Readiness (1-2 months before)\n - Implement missing controls\n - Document policies/procedures\n - Conduct mock audit\n ↓\n4. Evidence Collection (Ongoing)\n - Automate evidence gathering\n - Organize evidence repository\n - Prepare control narratives\n ↓\n5. Audit Kickoff\n - Provide evidence to auditor\n - Respond to requests\n - Schedule interviews\n ↓\n6. Fieldwork (4-6 weeks)\n - Auditor tests controls\n - Provide additional evidence\n - Address findings\n ↓\n7. Report Issuance\n - Review draft report\n - Address any exceptions\n - Receive final SOC2 report\n ↓\n8. Continuous Monitoring\n - Monitor control effectiveness\n - Prepare for next audit cycle","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Best Practices","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Security Architecture","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design with security in mind from the start (shift-left)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Apply defense in depth with multiple security layers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement Zero Trust: verify explicitly, use least privilege, assume breach","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Segment networks and limit lateral movement","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Encrypt data at rest and in transit","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use secure defaults and fail securely","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Access Control","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Enforce multi-factor authentication (MFA) everywhere","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement least privilege access","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use just-in-time (JIT) privileged access","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Regularly review and certify access","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Disable accounts promptly on termination","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Avoid shared accounts and service account abuse","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Security Operations","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Centralize logging with SIEM","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Automate detection and response where possible","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Maintain an incident response plan and test it","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conduct regular threat hunting exercises","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Keep vulnerability remediation SLAs aggressive","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Practice incident response through tabletop exercises","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Application Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Integrate security into CI/CD (DevSecOps)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Scan code for vulnerabilities (SAST, DAST, SCA)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Follow OWASP Top 10 guidelines","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conduct security code reviews for critical changes","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement secure API design (authentication, rate limiting, input validation)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use security headers (CSP, HSTS, X-Frame-Options)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Cloud Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use infrastructure as code (IaC) with security scanning","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Enable cloud-native security services (GuardDuty, Security Hub)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement CSPM to monitor misconfigurations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use cloud-native encryption and key management","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Apply least privilege IAM policies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Monitor for shadow IT and unauthorized resources","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Compliance","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Treat compliance as a continuous process, not one-time","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Map controls to multiple frameworks for efficiency","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Automate evidence collection where possible","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Maintain a compliance calendar for deadlines","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Document everything (if it's not documented, it doesn't exist)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conduct internal audits before external audits","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Security Culture","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Make security everyone's responsibility","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conduct regular security awareness training","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Run phishing simulations to test awareness","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Reward security-conscious behavior","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Create clear, accessible security policies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Foster a culture where reporting security concerns is encouraged","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Integration with Other Disciplines","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"With DevOps/Platform Engineering","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Integrate security scanning into CI/CD pipelines","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Automate security testing and compliance checks","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement Infrastructure as Code (IaC) security","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use container scanning and runtime protection","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Coordinate on incident response for production issues","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"With Enterprise Architecture","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Align security architecture with enterprise architecture","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Participate in architecture review boards","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Ensure security requirements in architecture standards","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design secure integration patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Define security reference architectures","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"With IT Operations","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Coordinate on patch management and change control","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Collaborate on monitoring and alerting","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Joint incident response for security and operational incidents","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Align on backup and disaster recovery procedures","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Coordinate access management and privileged access","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"With Product Management","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Provide security requirements for new features","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Participate in threat modeling for new products","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Balance security with user experience","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Advise on privacy and compliance implications","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Support security as a product differentiator","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"With Legal/Privacy","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Coordinate on data privacy regulations (GDPR, CCPA)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Collaborate on breach notification requirements","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Review vendor contracts for security terms","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Support privacy impact assessments","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Align on data retention and deletion policies","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"When to Engage Security & Compliance","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Required Engagement","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"New system or application design","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Architecture changes affecting security boundaries","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Regulatory compliance initiatives","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security incidents","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Vendor risk assessments","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Pre-production security reviews","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Audit preparation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Data breach or suspected breach","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Recommended Engagement","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Major feature releases","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Cloud migrations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"M&A due diligence","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Infrastructure changes","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"New third-party integrations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Significant process changes","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security tool selection","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Policy updates","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Continuous Collaboration","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security review of pull requests (for critical systems)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Vulnerability remediation prioritization","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security awareness and training","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Threat intelligence sharing","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Risk assessment updates","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Compliance monitoring","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}}]},"metadata":{"date":"2026-06-05","name":"security-compliance","author":"@skillopedia","source":{"stars":27714,"repo_name":"claude-code-templates","origin_url":"https://github.com/davila7/claude-code-templates/blob/HEAD/cli-tool/components/skills/development/security-compliance/SKILL.md","repo_owner":"davila7","body_sha256":"c24f6c24cba46295670357fa79bb98805a02549726408bd956d56ab130269f7b","cluster_key":"8640f7d6a7e0be98193d0de7cf7e16fece32e1f1df9a206f528ff6650581ee16","clean_bundle":{"format":"clean-skill-bundle-v1","source":"davila7/claude-code-templates/cli-tool/components/skills/development/security-compliance/SKILL.md","attachments":[{"id":"f979895f-5457-58ac-96ec-37fc04980b58","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/f979895f-5457-58ac-96ec-37fc04980b58/attachment.md","path":"README.md","size":16868,"sha256":"79d322c8443824baf1983bbb5e23882931c82645354e6ba4ce46c68ca4522dc3","contentType":"text/markdown; charset=utf-8"},{"id":"2aa3e846-1702-53ab-83aa-2cb82fdc232e","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/2aa3e846-1702-53ab-83aa-2cb82fdc232e/attachment.md","path":"examples/incident-response-template.md","size":8153,"sha256":"adb1fc8f572a14603c11a6a102d39487400bc070d278f9196bc3e2b3fc0e908a","contentType":"text/markdown; charset=utf-8"},{"id":"bf753eb9-03ba-58e3-a083-8fc58ba1ab0e","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/bf753eb9-03ba-58e3-a083-8fc58ba1ab0e/attachment.csv","path":"examples/risks.csv","size":1383,"sha256":"8447a36d2903e6ab78849eb2af885f6b180273e83f057dcd5c984a1a37cecba1","contentType":"text/csv; charset=utf-8"},{"id":"956ba03c-19c8-5532-8797-006ba27843c5","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/956ba03c-19c8-5532-8797-006ba27843c5/attachment.md","path":"examples/soc2-control-example.md","size":11354,"sha256":"50531e08783d2dfcbaab924b6d80fd01c9e6de3cd3b6eac87338b8c9f09db19b","contentType":"text/markdown; charset=utf-8"},{"id":"37854e38-9d12-582e-b57b-2f8e1a00c6a1","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/37854e38-9d12-582e-b57b-2f8e1a00c6a1/attachment.csv","path":"examples/vulnerabilities.csv","size":2111,"sha256":"3859723cc3827f0168c417bf52f3dfb7bc613e446df26239cbcaae72af7ce4bd","contentType":"text/csv; charset=utf-8"},{"id":"b5dcd01a-cafa-53a5-a890-dd1d4dd649a7","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b5dcd01a-cafa-53a5-a890-dd1d4dd649a7/attachment.md","path":"reference/application-security.md","size":26748,"sha256":"c548c9c876c0e569190e02483b20a6f22384d628799929dd5206b9c374754a76","contentType":"text/markdown; charset=utf-8"},{"id":"8a390239-ddfe-52f5-b828-e95855541c96","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/8a390239-ddfe-52f5-b828-e95855541c96/attachment.md","path":"reference/compliance-frameworks.md","size":51686,"sha256":"6c45b1607e943322aaaf19a349a990179be09d220a6bc032319a02cd509d3d88","contentType":"text/markdown; charset=utf-8"},{"id":"e605f972-4755-53a8-acff-33c3632b33b7","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/e605f972-4755-53a8-acff-33c3632b33b7/attachment.md","path":"reference/security-architecture.md","size":45301,"sha256":"8ae471c1297bd776591d65f55cff6637a9c9284b1f72e93ad798fae52512aa1b","contentType":"text/markdown; charset=utf-8"},{"id":"35a1f2e2-8a07-514d-92e8-4cdda9fac5cf","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/35a1f2e2-8a07-514d-92e8-4cdda9fac5cf/attachment.md","path":"reference/security-operations.md","size":29843,"sha256":"3a718152e1a3b9717dbd7d10772005486c551ee42c463d30f13b9deae2e96b9d","contentType":"text/markdown; charset=utf-8"},{"id":"4b4f8a23-9502-522b-823a-0eca14acde70","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/4b4f8a23-9502-522b-823a-0eca14acde70/attachment.md","path":"reference/threat-modeling-risk.md","size":44595,"sha256":"d072e18bd87e4b412cf42b94fc57bcd71ad8aa9c153ca0f755e9c3d34a7547a6","contentType":"text/markdown; charset=utf-8"},{"id":"bc99c0e3-87d3-520a-b538-ff3bdb3d905a","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/bc99c0e3-87d3-520a-b538-ff3bdb3d905a/attachment.py","path":"scripts/risk_calculator.py","size":13709,"sha256":"db5fd62fe95fdaaa9894d5cbd2e4fceadfa2f3d9188beb8f95948bcb55645518","contentType":"text/x-python; charset=utf-8"},{"id":"c2c10899-52de-5dd7-92ed-b1f700c55cb5","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/c2c10899-52de-5dd7-92ed-b1f700c55cb5/attachment.py","path":"scripts/vuln_prioritizer.py","size":16795,"sha256":"c21509925701e49e895c09bef9789d205623b7f711583d55517462f05de563e4","contentType":"text/x-python; charset=utf-8"}],"bundle_sha256":"7337be68b4bb44f77e884611a10766d835135f59b64a81bb148a0710e4257559","attachment_count":12,"text_attachments":12,"attachment_storage":"skillopedia-attachments-v1","binary_attachments":0,"excluded_attachments":[]},"cluster_size":2,"skill_md_path":"cli-tool/components/skills/development/security-compliance/SKILL.md","import_metadata":{"date":"2026-06-05","author":"@skillopedia","version":"v1","category":"security","category_label":"Security"},"exact_dupes_collapsed_into_this":1},"version":"v1","category":"security","import_tag":"clean-skills-v1","description":"Guides security professionals in implementing defense-in-depth security architectures, achieving compliance with industry frameworks (SOC2, ISO27001, GDPR, HIPAA), conducting threat modeling and risk assessments, managing security operations and incident response, and embedding security throughout the SDLC."}},"renderedAt":1782987404864}

Security & Compliance Expert Core Principles 1. Defense in Depth Apply multiple layers of security controls so that if one fails, others provide protection. Never rely on a single security mechanism. 2. Zero Trust Architecture Never trust, always verify. Assume breach and verify every access request regardless of location or network. 3. Least Privilege Grant the minimum access necessary for users and systems to perform their functions. Regularly review and revoke unused permissions. 4. Security by Design Integrate security requirements from the earliest stages of system design, not as an afte…