41 pages ยท 8 sections
Ctrl K
GitHub Portfolio

Compliance Frameworks

Compliance frameworks provide structured approaches to information security governance. This guide covers SOC 2, ISO 27001, PCI-DSS, and DISA STIG implementation with practical automation and evidence collection.

SOC 2 Type I vs Type II

Service Organization Control 2 (SOC 2) is an audit framework developed by the AICPA that evaluates service organizations based on the Trust Services Criteria (TSC).

Type I vs Type II Comparison

DimensionSOC 2 Type ISOC 2 Type II
ScopeDesign of controls at a point in timeDesign and operating effectiveness over a period
Observation PeriodSingle date (as of)Minimum 3 months (typically 6-12 months)
Effort2-4 weeks3-6 months total
Cost$15,000 - $40,000$30,000 - $100,000+
RenewalAnnualAnnual (overlapping observation periods)
Trust ValueInitial validationDemonstrates sustained compliance

Trust Services Criteria (TSC)

CategoryPrincipleDescriptionKey Controls
SecurityCC1-CC7 (Common Criteria)Protection against unauthorized accessAccess control, encryption, monitoring, change management
AvailabilityA1Systems available for operation and useUptime monitoring, disaster recovery, incident response
Processing IntegrityPI1System processing is complete, valid, accurate, timelyInput validation, error handling, data reconciliation
ConfidentialityC1Confidential information is protectedEncryption, access restrictions, data classification
PrivacyP1-P7Personal information is collected, used, retained, disclosed, and disposed of properlyConsent management, data minimization, retention policies

Implementation Checklist

  1. Scope Definition โ€” Define the "system" boundary: applications, infrastructure, people, processes, and data
  2. Gap Assessment โ€” Map existing controls to TSC requirements; identify gaps
  3. Control Implementation โ€” Build missing controls, document all procedures
  4. Evidence Collection โ€” Automate evidence collection for all controls
  5. Readiness Assessment โ€” Internal audit simulation with external consultant
  6. Formal Audit โ€” Engage CPA firm for Type I or Type II audit
  7. Continuous Monitoring โ€” Ongoing evidence collection and control testing

Evidence Collection Automation

#!/usr/bin/env python3
"""
soc2_evidence_collector.py โ€” Automated evidence collection for SOC 2 audits.

Collects evidence from AWS, GitHub, and internal systems,
organizing it by Trust Services Criteria.
"""

import json
import boto3
import subprocess
from datetime import datetime, timedelta
from pathlib import Path
from dataclasses import dataclass, asdict
from typing import List, Dict
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@dataclass
class EvidenceItem:
    control_id: str
    criteria: str  # e.g., "CC6.1", "A1.2"
    title: str
    description: str
    evidence_type: str  # "config", "screenshot", "log", "policy"
    source: str
    collected_at: str
    data: Dict
    file_path: str = ""

class SOC2EvidenceCollector:
    """Collects and organizes SOC 2 evidence across cloud platforms."""
    
    def __init__(self, output_dir: str = "./soc2-evidence"):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.evidence: List[EvidenceItem] = []
        
        # AWS clients
        self.iam = boto3.client('iam')
        self.cloudtrail = boto3.client('cloudtrail')
        self.config = boto3.client('config')
        self.ec2 = boto3.client('ec2')
        self.kms = boto3.client('kms')
        self.s3 = boto3.client('s3')
    
    def collect_all(self):
        """Run all evidence collection methods."""
        logger.info("Starting SOC 2 evidence collection...")
        
        self._collect_cc61_access_control()    # Logical access controls
        self._collect_cc62_access_removal()    # Access removal
        self._collect_cc63_access_reviews()    # Access reviews
        self._collect_cc64_encryption()        # Encryption at rest
        self._collect_cc66_transmission()      # Transmission security
        self._collect_cc67_data_processing()   # Data handling
        self._collect_cc71_vulnerability()     # Vulnerability management
        self._collect_cc72_monitoring()        # System monitoring
        self._collect_cc81_change_management() # Change management
        self._collect_a12_availability()       # System availability
        
        # Write manifest
        self._write_manifest()
        logger.info(f"Evidence collection complete. {len(self.evidence)} items collected.")
    
    def _collect_cc61_access_control(self):
        """CC6.1: Logical access controls โ€” IAM policy evidence."""
        logger.info("Collecting CC6.1: Logical access security...")
        
        # Get all IAM policies
        paginator = self.iam.get_paginator('list_policies')
        policies = []
        for page in paginator.paginate(Scope='Local'):
            for policy in page['Policies']:
                version = self.iam.get_policy_version(
                    PolicyArn=policy['Arn'],
                    VersionId=policy['DefaultVersionId']
                )
                policies.append({
                    'name': policy['PolicyName'],
                    'arn': policy['Arn'],
                    'document': version['PolicyVersion']['Document']
                })
        
        evidence = EvidenceItem(
            control_id="CC6.1",
            criteria="CC6.1",
            title="IAM Access Control Policies",
            description="Logical access security policies enforcing least privilege",
            evidence_type="config",
            source="AWS IAM",
            collected_at=datetime.utcnow().isoformat(),
            data={'policy_count': len(policies), 'policies': policies[:5]}
        )
        self.evidence.append(evidence)
        self._write_json(evidence)
    
    def _collect_cc64_encryption(self):
        """CC6.4: Encryption at rest โ€” KMS key configuration."""
        logger.info("Collecting CC6.4: Encryption at rest...")
        
        keys = self.kms.list_keys()['Keys']
        key_details = []
        for key in keys[:10]:
            metadata = self.kms.describe_key(KeyId=key['KeyId'])['KeyMetadata']
            rotation = self.kms.get_key_rotation_status(KeyId=key['KeyId'])
            key_details.append({
                'id': key['KeyId'],
                'enabled': metadata['Enabled'],
                'rotation_enabled': rotation['KeyRotationEnabled'],
                'origin': metadata['Origin'],
                'description': metadata.get('Description', '')
            })
        
        evidence = EvidenceItem(
            control_id="CC6.4",
            criteria="CC6.4",
            title="Encryption Key Management",
            description="KMS keys with rotation status for encryption at rest",
            evidence_type="config",
            source="AWS KMS",
            collected_at=datetime.utcnow().isoformat(),
            data={'key_count': len(keys), 'keys': key_details}
        )
        self.evidence.append(evidence)
        self._write_json(evidence)
    
    def _collect_cc72_monitoring(self):
        """CC7.2: System monitoring โ€” CloudTrail configuration."""
        logger.info("Collecting CC7.2: System monitoring...")
        
        trails = self.cloudtrail.describe_trails()['trailList']
        trail_details = []
        for trail in trails:
            status = self.cloudtrail.get_trail_status(Name=trail['Name'])
            trail_details.append({
                'name': trail['Name'],
                's3_bucket': trail['S3BucketName'],
                'is_logging': status.get('IsLogging', False),
                'latest_delivery': status.get('LatestDeliveryTime', '').isoformat() if status.get('LatestDeliveryTime') else None,
                'kms_encrypted': 'KmsKeyId' in trail
            })
        
        evidence = EvidenceItem(
            control_id="CC7.2",
            criteria="CC7.2",
            title="System Activity Monitoring",
            description="CloudTrail configuration for system activity monitoring",
            evidence_type="config",
            source="AWS CloudTrail",
            collected_at=datetime.utcnow().isoformat(),
            data={'trail_count': len(trails), 'trails': trail_details}
        )
        self.evidence.append(evidence)
        self._write_json(evidence)
    
    def _write_json(self, evidence: EvidenceItem):
        """Write evidence item to JSON file."""
        criteria_dir = self.output_dir / evidence.criteria
        criteria_dir.mkdir(exist_ok=True)
        
        filename = f"{evidence.control_id}_{datetime.now():%Y%m%d_%H%M%S}.json"
        filepath = criteria_dir / filename
        
        with open(filepath, 'w') as f:
            json.dump(asdict(evidence), f, indent=2, default=str)
        
        evidence.file_path = str(filepath)
    
    def _write_manifest(self):
        """Write evidence manifest."""
        manifest = {
            'generated_at': datetime.utcnow().isoformat(),
            'period_start': (datetime.now() - timedelta(days=90)).isoformat(),
            'period_end': datetime.utcnow().isoformat(),
            'total_evidence_items': len(self.evidence),
            'evidence_by_criteria': {}
        }
        
        for e in self.evidence:
            if e.criteria not in manifest['evidence_by_criteria']:
                manifest['evidence_by_criteria'][e.criteria] = []
            manifest['evidence_by_criteria'][e.criteria].append({
                'title': e.title,
                'file': e.file_path
            })
        
        with open(self.output_dir / 'manifest.json', 'w') as f:
            json.dump(manifest, f, indent=2, default=str)

# CLI usage
if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='Collect SOC 2 evidence')
    parser.add_argument('--output', default='./soc2-evidence', help='Output directory')
    args = parser.parse_args()
    
    collector = SOC2EvidenceCollector(output_dir=args.output)
    collector.collect_all()

Auditor Preparation Checklist

# auditor-readiness-checklist.yaml
soc2_type2_readiness:
  
  documentation:
    - [ ] Information Security Policy (signed by CEO)
    - [ ] Risk Assessment Report (within 12 months)
    - [ ] Vendor Management Policy
    - [ ] Acceptable Use Policy
    - [ ] Incident Response Plan
    - [ ] Business Continuity / Disaster Recovery Plan
    - [ ] Data Classification Policy
    - [ ] Employee Handbook (security section)
    - [ ] Code of Conduct
    
  access_control:
    - [ ] User access provisioning procedure documented
    - [ ] User access deprovisioning procedure documented
    - [ ] Quarterly access reviews (last 4 quarters)
    - [ ] Privileged access list current
    - [ ] MFA enforcement evidence
    - [ ] Password policy documentation
    
  infrastructure:
    - [ ] Network diagram (current)
    - [ ] Asset inventory (complete)
    - [ ] Vulnerability scan reports (last 4 quarters)
    - [ ] Penetration test report (within 12 months)
    - [ ] Change management logs
    - [ ] Backup/restoration test results
    
  monitoring:
    - [ ] Log retention policy
    - [ ] SIEM configuration evidence
    - [ ] Alert response procedures
    - [ ] Sample of security alerts and responses
    
  hr:
    - [ ] Background check policy
    - [ ] Security awareness training records (100%)
    - [ ] Confidentiality agreements (signed)
    - [ ] Termination checklist

ISO/IEC 27001:2013

ISO 27001 is the international standard for Information Security Management Systems (ISMS). Certification demonstrates a systematic approach to managing sensitive information.

ISMS Scope Definition

# ISMS Scope Statement Template

## Scope of the Information Security Management System

**Organization:** Company Inc.
**Scope Statement:** The ISMS covers all information systems, processes, and 
data related to the development, operation, and support of the Company's 
SaaS platform and associated professional services.

**Boundaries:**
- Primary data centers: AWS us-east-1, us-west-2
- Office locations: San Francisco HQ, New York satellite
- Remote workforce: All employees with company-managed devices
- Third-party processors: Listed in Register of Suppliers

**Inclusions:**
- Customer data processing and storage
- Internal HR and financial systems
- Product development environments
- Customer-facing applications and APIs

**Exclusions:**
- Public marketing website (managed by third party)
- Physical security of shared office building (landlord responsibility)
- Employee personal devices (BYOD not permitted)

**Interfaces:**
- AWS (IaaS provider)
- Stripe (payment processor)
- SendGrid (email delivery)

Risk Assessment Methodology

# iso27001_risk_assessment.py
from dataclasses import dataclass
from enum import Enum
from typing import List
import json

class RiskLevel(Enum):
    LOW = "Low"
    MEDIUM = "Medium"
    HIGH = "High"
    CRITICAL = "Critical"

@dataclass
class Risk:
    asset: str
    threat: str
    vulnerability: str
    likelihood: int  # 1-5
    impact: int      # 1-5
    existing_controls: List[str]
    risk_owner: str
    treatment: str   # Accept, Mitigate, Transfer, Avoid
    
    @property
    def risk_score(self) -> int:
        return self.likelihood * self.impact
    
    @property
    def risk_level(self) -> RiskLevel:
        if self.risk_score >= 20:
            return RiskLevel.CRITICAL
        elif self.risk_score >= 12:
            return RiskLevel.HIGH
        elif self.risk_score >= 6:
            return RiskLevel.MEDIUM
        return RiskLevel.LOW

# Example: Risk register for ISO 27001
risks = [
    Risk(
        asset="Customer database",
        threat="Unauthorized access via compromised credentials",
        vulnerability="Weak password policy, no MFA on legacy admin accounts",
        likelihood=3,
        impact=5,
        existing_controls=["Database encryption at rest", "Access logging"],
        risk_owner="CISO",
        treatment="Mitigate โ€” Implement MFA for all admin accounts within 30 days"
    ),
    Risk(
        asset="CI/CD pipeline",
        threat="Supply chain compromise via malicious dependency",
        vulnerability="Lack of dependency pinning and signature verification",
        likelihood=3,
        impact=4,
        existing_controls=["Dependency scanning", "Private artifact repository"],
        risk_owner="VP Engineering",
        treatment="Mitigate โ€” Implement Sigstore verification for all artifacts"
    ),
    Risk(
        asset="Employee laptops",
        threat="Data breach via lost or stolen device",
        vulnerability="Devices without full disk encryption",
        likelihood=2,
        impact=4,
        existing_controls=["MDM enrollment", "Remote wipe capability"],
        risk_owner="IT Director",
        treatment="Mitigate โ€” Enforce BitLocker/FileVault on all devices"
    )
]

# Generate risk register
for risk in risks:
    print(f"Asset: {risk.asset}")
    print(f"  Score: {risk.risk_score} ({risk.risk_level.value})")
    print(f"  Treatment: {risk.treatment}")
    print()

Statement of Applicability (SoA)

Control RefControl TitleApplicableJustificationImplementation
A.5.1Policies for information securityYesAll employees must follow security policiesInformation Security Policy v3.2
A.6.1Organization of information securityYesSecurity roles must be definedRACI matrix, security org chart
A.7.1Human resource security โ€” prior to employmentYesBackground checks requiredHR onboarding checklist
A.8.1Asset managementYesAll assets must be inventoriedCMDB, AWS Config
A.9.1Access controlYesLeast privilege requiredRBAC, quarterly access reviews
A.10.1CryptographyYesEncryption required for customer dataAWS KMS, TLS 1.3
A.11.1Physical securityPartialCloud-hosted, minimal physical assetsAWS data center certifications
A.12.1Operations securityYesOperational procedures requiredRunbooks, change management
A.13.1Communications securityYesNetwork segmentation requiredVPC, security groups, WAF
A.14.1System acquisition and developmentYesSecure development requiredSDLC, SAST/DAST in CI/CD

PCI-DSS v4.0

The Payment Card Industry Data Security Standard (PCI-DSS) v4.0 applies to all entities that store, process, or transmit cardholder data (CHD) and/or sensitive authentication data (SAD).

Scope Reduction Strategies

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    CDE (In Scope)                    โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”‚
โ”‚  โ”‚  Payment   โ”‚  โ”‚ Cardholder โ”‚  โ”‚ Auth Data  โ”‚    โ”‚
โ”‚  โ”‚  Gateway   โ”‚  โ”‚  Database  โ”‚  โ”‚  Storage   โ”‚    โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ”‚
โ”‚                                                      โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”‚
โ”‚  โ”‚         Connected Systems (In Scope)        โ”‚     โ”‚
โ”‚  โ”‚  Jump hosts, SIEM, backup systems           โ”‚     โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚               Out of Scope (Segmented)               โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”‚
โ”‚  โ”‚ Marketing  โ”‚  โ”‚ Analytics  โ”‚  โ”‚   HR/      โ”‚    โ”‚
โ”‚  โ”‚  Website   โ”‚  โ”‚  Platform  โ”‚  โ”‚   Payroll  โ”‚    โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ”‚
โ”‚                                                      โ”‚
โ”‚  Isolated by VLAN/firewall โ€” no CDE access          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Network Segmentation Requirements

# terraform/pci-network-segmentation.tf
# PCI-DSS Requirement 1: Network segmentation for CDE

# CDE VPC โ€” Isolated from corporate VPC
resource "aws_vpc" "cde" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true
  
  tags = {
    Name = "cde-vpc"
    Scope = "PCI-CDE"
  }
}

# CDE subnets โ€” Private only, no public IPs
resource "aws_subnet" "cde_private" {
  vpc_id                  = aws_vpc.cde.id
  cidr_block              = "10.0.1.0/24"
  availability_zone       = "us-east-1a"
  map_public_ip_on_launch = false
  
  tags = {
    Name = "cde-private"
    Scope = "PCI-CDE"
  }
}

# Security group โ€” Default deny all
resource "aws_security_group" "cde_default" {
  name        = "cde-default-deny"
  description = "Default deny all for CDE"
  vpc_id      = aws_vpc.cde.id
  
  tags = {
    Scope = "PCI-CDE"
  }
}

# Explicit allow rules only
resource "aws_security_group_rule" "cde_payment_gateway_ingress" {
  type                     = "ingress"
  from_port                = 443
  to_port                  = 443
  protocol                 = "tcp"
  source_security_group_id = aws_security_group.payment_gateway.id
  security_group_id        = aws_security_group.cde_default.id
  description              = "HTTPS from payment gateway"
}

# VPC Flow Logs for CDE monitoring
resource "aws_flow_log" "cde_flow" {
  vpc_id                   = aws_vpc.cde.id
  traffic_type             = "ALL"
  log_destination          = aws_cloudwatch_log_group.cde_flow.arn
  log_destination_type     = "cloud-watch-logs"
  iam_role_arn             = aws_iam_role.flow_logs.arn
  
  tags = {
    Name = "cde-flow-logs"
    Scope = "PCI-CDE"
  }
}

# Transit Gateway attachment โ€” Controlled routing only
resource "aws_ec2_transit_gateway_vpc_attachment" "cde" {
  transit_gateway_id = aws_ec2_transit_gateway.main.id
  vpc_id             = aws_vpc.cde.id
  subnet_ids         = [aws_subnet.cde_private.id]
  
  appliance_mode_support = "disable"
  dns_support            = "enable"
  
  tags = {
    Name = "cde-tgw-attachment"
  }
}

# Transit Gateway route table โ€” Restrict CDE routing
resource "aws_ec2_transit_gateway_route_table" "cde" {
  transit_gateway_id = aws_ec2_transit_gateway.main.id
  
  tags = {
    Name = "cde-route-table"
  }
}

DISA STIG for Government Deployments

The Defense Information Systems Agency (DISA) Security Technical Implementation Guides (STIGs) provide standardized hardening requirements for DoD systems.

STIGViewer Usage

# Download STIGViewer and STIG content
# https://public.cyber.mil/stigs/downloads/

# 1. Download STIGViewer JAR
wget https://dl.dod.cyber.mil/stigs/zip/U_STIGViewer.zip
unzip U_STIGViewer.zip
java -jar STIGViewer.jar

# 2. Download applicable STIGs
# - Ubuntu 22.04 V2R1
# - PostgreSQL 15 V1R1
# - Apache Tomcat 10 V1R1
# - Kubernetes V1R8

# 3. Import into STIGViewer
# File โ†’ Import STIG โ†’ Select .zip files
# Create Checklist โ†’ Select target STIGs

Automated STIG Compliance with Ansible

# ansible/stig-compliance.yml
# Apply DISA STIG benchmarks via Ansible

- name: Apply Ubuntu 22.04 STIG
  hosts: all
  become: yes
  vars:
    stig_level: "high"  # Apply CAT I and CAT II findings
    
  tasks:
    # UBTU-22-101000 โ€” Password complexity requirements
    - name: Ensure pam_pwquality is configured
      lineinfile:
        path: /etc/security/pwquality.conf
        regexp: "^{{ item.key }}"
        line: "{{ item.key }} = {{ item.value }}"
      loop:
        - { key: "minlen", value: "15" }
        - { key: "minclass", value: "4" }
        - { key: "maxrepeat", value: "2" }
        - { key: "dcredit", value: "-1" }
        - { key: "ucredit", value: "-1" }
        - { key: "ocredit", value: "-1" }
        - { key: "lcredit", value: "-1" }
      tags: ["stig", "password", "UBTU-22-101000"]

    # UBTU-22-102000 โ€” Account lockout policy
    - name: Configure account lockout
      lineinfile:
        path: /etc/pam.d/common-auth
        line: "auth required pam_tally2.so onerr=fail deny=3 unlock_time=900"
        insertbefore: "^auth\\s\\[success="
      tags: ["stig", "lockout", "UBTU-22-102000"]

    # UBTU-22-103000 โ€” Audit logging
    - name: Ensure auditd is installed and running
      apt:
        name: auditd
        state: present
      tags: ["stig", "audit", "UBTU-22-103000"]

    - name: Configure audit rules
      template:
        src: audit.rules.j2
        dest: /etc/audit/rules.d/audit.rules
        mode: '0640'
      notify: restart auditd
      tags: ["stig", "audit", "UBTU-22-103000"]

    # UBTU-22-104000 โ€” File permissions
    - name: Set proper permissions on critical files
      file:
        path: "{{ item.path }}"
        owner: "{{ item.owner }}"
        group: "{{ item.group }}"
        mode: "{{ item.mode }}"
      loop:
        - { path: "/etc/shadow", owner: root, group: root, mode: "0640" }
        - { path: "/etc/passwd", owner: root, group: root, mode: "0644" }
        - { path: "/etc/group", owner: root, group: root, mode: "0644" }
        - { path: "/etc/ssh/sshd_config", owner: root, group: root, mode: "0600" }
        - { path: "/var/log", owner: root, group: syslog, mode: "0755" }
      tags: ["stig", "permissions", "UBTU-22-104000"]

    # UBTU-22-105000 โ€” SSH hardening
    - name: Harden SSH configuration
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^#?{{ item.key }}"
        line: "{{ item.key }} {{ item.value }}"
      loop:
        - { key: "PermitRootLogin", value: "no" }
        - { key: "PasswordAuthentication", value: "no" }
        - { key: "PubkeyAuthentication", value: "yes" }
        - { key: "X11Forwarding", value: "no" }
        - { key: "MaxAuthTries", value: "3" }
        - { key: "ClientAliveInterval", value: "300" }
        - { key: "ClientAliveCountMax", value: "0" }
        - { key: "Protocol", value: "2" }
        - { key: "Ciphers", value: "aes256-gcm@openssh.com,chacha20-poly1305@openssh.com" }
        - { key: "MACs", value: "hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com" }
      notify: restart sshd
      tags: ["stig", "ssh", "UBTU-22-105000"]

    # UBTU-22-106000 โ€” Kernel parameters
    - name: Apply security kernel parameters
      sysctl:
        name: "{{ item.key }}"
        value: "{{ item.value }}"
        state: present
        reload: yes
      loop:
        - { key: "kernel.randomize_va_space", value: "2" }
        - { key: "net.ipv4.ip_forward", value: "0" }
        - { key: "net.ipv4.conf.all.send_redirects", value: "0" }
        - { key: "net.ipv4.conf.default.send_redirects", value: "0" }
        - { key: "net.ipv4.conf.all.accept_redirects", value: "0" }
        - { key: "net.ipv4.conf.default.accept_redirects", value: "0" }
        - { key: "net.ipv4.icmp_echo_ignore_broadcasts", value: "1" }
        - { key: "net.ipv4.tcp_syncookies", value: "1" }
        - { key: "fs.protected_hardlinks", value: "1" }
        - { key: "fs.protected_symlinks", value: "1" }
      tags: ["stig", "kernel", "UBTU-22-106000"]

    # UBTU-22-107000 โ€” AIDE file integrity monitoring
    - name: Install AIDE
      apt:
        name: aide
        state: present
      tags: ["stig", "fim", "UBTU-22-107000"]

    - name: Initialize AIDE database
      command: aideinit
      args:
        creates: /var/lib/aide/aide.db.new
      tags: ["stig", "fim", "UBTU-22-107000"]

  handlers:
    - name: restart sshd
      service:
        name: sshd
        state: restarted

    - name: restart auditd
      service:
        name: auditd
        state: restarted
# ansible/audit.rules.j2 โ€” STIG audit rules
# Delete all existing rules
-D

# Set buffer size
-b 8192

# Failure mode: printk
-f 1

# Monitor password file changes
-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/shadow -p wa -k identity

# Monitor sudoers
-w /etc/sudoers -p wa -k sudoers
-w /etc/sudoers.d/ -p wa -k sudoers

# Monitor SSH configuration
-w /etc/ssh/sshd_config -p wa -k sshd

# Monitor kernel modules
-w /sbin/insmod -p x -k modules
-w /sbin/rmmod -p x -k modules
-w /sbin/modprobe -p x -k modules

# Monitor privilege escalation
-a always,exit -F arch=b64 -S setuid -S setgid -S setreuid -S setregid -k privilege

# Monitor file deletions
-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete

Compliance Automation Tools

ToolFrameworksKey FeaturesPrice Range
VantaSOC 2, ISO 27001, HIPAA, GDPRAutomated evidence collection, 200+ integrations, auditor portal$15K-$50K/year
DrataSOC 2, ISO 27001, PCI-DSS, HIPAAContinuous control monitoring, agent-based evidence, policy templates$15K-$50K/year
AuditBoardSOX, SOC 2, ISO 27001Enterprise risk management, audit workflow, control testingEnterprise pricing
LaceworkSOC 2, PCI-DSS, HIPAACloud security platform with compliance reportingUsage-based
Tenable.csSOC 2, PCI-DSS, HIPAA, NISTCSPM with compliance dashboard, IaC scanningPer-resource

Continuous Compliance Monitoring

# terraform/continuous-compliance.tf
# Automated compliance checks with AWS Config

# Enable AWS Config
resource "aws_config_configuration_recorder" "compliance" {
  name     = "compliance-recorder"
  role_arn = aws_iam_role.config.arn
  
  recording_group {
    all_supported                 = true
    record_global_resource_types = true
  }
}

resource "aws_config_delivery_channel" "compliance" {
  name           = "compliance-delivery"
  s3_bucket_name = aws_s3_bucket.compliance_logs.bucket
  sns_topic_arn  = aws_sns_topic.compliance_alerts.arn
  
  snapshot_delivery_properties {
    delivery_frequency = "TwentyFour_Hours"
  }
}

# Required tags rule
resource "aws_config_config_rule" "required_tags" {
  name = "required-tags"
  
  source {
    owner             = "AWS"
    source_identifier = "REQUIRED_TAGS"
  }
  
  input_parameters = jsonencode({
    tag1Key = "Environment"
    tag2Key = "Application"
    tag3Key = "Owner"
    tag4Key = "DataClassification"
    tag5Key = "CostCenter"
  })
}

# CloudTrail enabled rule
resource "aws_config_config_rule" "cloudtrail_enabled" {
  name = "cloudtrail-enabled"
  
  source {
    owner             = "AWS"
    source_identifier = "CLOUD_TRAIL_ENABLED"
  }
}

# MFA enabled for root
resource "aws_config_config_rule" "root_account_mfa" {
  name = "root-account-mfa"
  
  source {
    owner             = "AWS"
    source_identifier = "ROOT_ACCOUNT_MFA_ENABLED"
  }
}

# Encrypted volumes
resource "aws_config_config_rule" "ebs_encrypted" {
  name = "ebs-encrypted"
  
  source {
    owner             = "AWS"
    source_identifier = "EC2_EBS_ENCRYPTION_BY_DEFAULT"
  }
}

# S3 bucket public read prohibited
resource "aws_config_config_rule" "s3_public_read" {
  name = "s3-public-read-prohibited"
  
  source {
    owner             = "AWS"
    source_identifier = "S3_BUCKET_PUBLIC_READ_PROHIBITED"
  }
}

# AWS Config aggregator for multi-account
resource "aws_config_configuration_aggregator" "org" {
  name = "organization-aggregator"
  
  organization_aggregation_source {
    all_regions = true
    role_arn    = aws_iam_role.config_aggregator.arn
  }
}

Cross-Framework Control Mapping

Control AreaSOC 2 CCISO 27001PCI-DSS v4.0DISA STIG
Access ControlCC6.1-CC6.3A.9.1-A.9.47.1-7.2, 8.2-8.5UBTU-22-101000, UBTU-22-102000
EncryptionCC6.1, CC6.7A.10.1-A.10.23.6-3.7, 4.1-4.3UBTU-22-612010
Vulnerability ManagementCC7.1, CC8.1A.12.6, A.18.26.3-6.5, 11.3-11.6V-238220, V-238221
Logging & MonitoringCC7.2-CC7.3A.12.410.2-10.7UBTU-22-653050
Network SecurityCC6.6, CC6.7A.13.11.2-1.5, 2.1-2.3UBTU-22-251010
Change ManagementCC8.1A.12.1.2, A.14.2.26.5V-238202
Incident ResponseCC4.1-CC4.2, CC7.4-CC7.5A.16.112.10UBTU-22-653055
Physical SecurityCC6.4A.11.19.1-9.5N/A (cloud-hosted)
Data ClassificationCC6.1, CC6.7A.8.23.1-3.3V-238212
Backup & RecoveryA1.2, A1.3A.12.3, A.17.112.3-12.4UBTU-22-611010

Multi-Framework Certification Strategy

Organizations should map all frameworks to a single control library. Start with SOC 2 Type II as the foundation โ€” its broad Trust Services Criteria cover the majority of ISO 27001 and PCI-DSS requirements. Add framework-specific supplements only where gaps exist. This approach reduces audit fatigue and demonstrates mature security governance.

Related Topics