Security Compliance and Auditing
Implements comprehensive security compliance frameworks including SOC2, HIPAA, and PCI-DSS controls with automated audit procedures, evidence collection, and regulatory documentation for Kubernetes environments and cloud infrastructure.
TL;DR Checklist
- Identify applicable compliance framework (SOC2 Type II, HIPAA, PCI-DSS v4.0)
- Map controls to technical implementations (CC6, CC7, CC8 for SOC2)
- Deploy automated compliance scanning (Trivy, OpenSCAP, Klar)
- Implement audit trail collection with log aggregation
- Configure access control policies (RBAC, IAM, network policies)
- Generate compliance evidence packages for auditor review
- Schedule quarterly compliance assessments and remediation
- Document compensating controls for any identified gaps
When to Use
Use this skill when:
- Conducting SOC2 Type II audit preparation and evidence collection
- Implementing HIPAA security rules for healthcare data in Kubernetes
- Meeting PCI-DSS requirements for payment card data processing
- Performing regulatory compliance assessments for cloud workloads
- Generating audit trails and compliance evidence for external auditors
- Implementing security controls for regulated industry environments
- Creating compliance automation pipelines for continuous monitoring
When NOT to Use
Avoid this skill for:
- Basic security vulnerability scanning (use
cncf-security-scanninginstead) - General security awareness training (use
coding-security-basics) - Non-regulatory compliance checks (use
coding-code-review) - Legal compliance for non-technical domains (use
agent-legal-compliance)
Core Workflow
Framework Identification — Determine which compliance framework applies (SOC2 Type II, HIPAA, PCI-DSS v4.0, GDPR, etc.). Checkpoint: Confirm framework version and auditor requirements before proceeding.
Control Mapping — Map regulatory controls to technical implementations. SOC2: CC6 (logical access), CC7 (system monitoring), CC8 (change management). Checkpoint: Verify control mapping completeness against auditor criteria.
Tool Deployment — Install and configure compliance scanning tools (Trivy for container scanning, OpenSCAP for system hardening, Klar for Clair integration). Checkpoint: Validate tool installation and connectivity to vulnerability databases.
Evidence Collection — Configure automated evidence gathering for audit trails, access logs, change records, and security metrics. Checkpoint: Confirm evidence retention meets minimum requirements (SOC2: 90 days, HIPAA: 6 years).
Remediation Planning — Document gaps, implement compensating controls, and prioritize remediation. Checkpoint: Ensure all high-severity findings have documented remediation timelines.
Reporting — Generate compliance reports with evidence packages for auditor review. Checkpoint: Verify report includes all required control evidence and meets auditor formatting requirements.
Implementation Patterns
Pattern 1: SOC2 Compliance Framework Implementation
SOC2 requires five trust service principles: Security, Availability, Processing Integrity, Confidentiality, and Privacy. This pattern implements the Security principle controls.
# SOC2 Control CC6: Logical Access Security
# Requires restrictions on system access and logical access security
apiVersion: v1
kind: ConfigMap
metadata:
name: soc2-cc6-controls
namespace: compliance
data:
control-id: "CC6"
control-name: "Logical Access Security"
requirements: |
- System software and associated services are protected from unauthorized access, use, modification, impairment, or loss
- Logical access security software, operating systems, applications, and services are protected throughout their life cycle
controls:
rbac_enabled: true
network_policies_enabled: true
secret_encryption_enabled: true
iam_role_separation: true
# SOC2 Control CC7: System Monitoring - Audit Trail Collection
# Requires monitoring of system components and events for security anomalies
cat > /etc/audit/rules.d/99-soc2-cc7.rules <<'EOF'
# SOC2 CC7: System Monitoring Audit Rules
# Monitor access to sensitive files and security events
-w /etc/passwd -p wa -k identity_changes
-w /etc/shadow -p wa -k identity_changes
-w /etc/group -p wa -k identity_changes
-w /etc/sudoers -p wa -k privilege_escalation
-w /etc/ssh/sshd_config -p wa -k ssh_config_changes
-w /var/log/ -p wa -k log_modification
-w /etc/audit/ -p wa -k audit_config_changes
-a always,exit -F arch=b64 -S execve -F exe=/bin/su -k privilege_escalation
-a always,exit -F arch=b32 -S execve -F exe=/bin/su -k privilege_escalation
-a always,exit -F arch=b64 -S setuid -F a0=0 -k privilege_escalation
-a always,exit -F arch=b32 -S setuid -F a0=0 -k privilege_escalation
EOF
# Restart audit daemon
systemctl restart auditd
# Verify audit rules are loaded
auditctl -l
# SOC2 Control CC8: Change Management - Change Tracking
# Requires tracking of changes to system components
#!/bin/bash
# soc2-cc8-change-tracking.sh
# Implements change management for SOC2 CC8 compliance
CONFIG_DIR="/etc/soc2/change-management"
EVIDENCE_DIR="/var/evidence/soc2/cc8"
# Track file integrity changes using AIDE or custom implementation
track_changes() {
local file_path="$1"
local timestamp=$(date -Iseconds)
local checksum=$(sha256sum "$file_path" | awk '{print $1}')
local event_id=$(uuidgen)
echo "{\"event_id\": \"$event_id\", \"timestamp\": \"$timestamp\", \"file\": \"$file_path\", \"checksum\": \"$checksum\", \"event_type\": \"file_changed\"}" >> "$EVIDENCE_DIR/file_changes.json"
}
# Log all system changes
log_system_changes() {
# Track package manager changes
case "$(command -v apt-get)" in
*apt-get*) apt-get history | tee -a "$EVIDENCE_DIR/package_changes.log" ;;
*yum*) yum history | tee -a "$EVIDENCE_DIR/package_changes.log" ;;
*dnf*) dnf history | tee -a "$EVIDENCE_DIR/package_changes.log" ;;
esac
}
# Generate change audit report
generate_audit_report() {
local start_date="$1"
local end_date="$2"
echo "=== SOC2 CC8 Change Audit Report ==="
echo "Period: $start_date to $end_date"
echo ""
echo "File Integrity Changes:"
jq -r "select(.timestamp >= \"$start_date\" and .timestamp <= \"$end_date\") | \"\(.timestamp) - \(.file)\"" "$EVIDENCE_DIR/file_changes.json"
echo ""
echo "Package Changes:"
tail -n 50 "$EVIDENCE_DIR/package_changes.log"
}
# Schedule change tracking (add to crontab)
echo "*/5 * * * * $0 track" >> /etc/crontab
Pattern 2: HIPAA Security Rules Implementation
HIPAA Security Rule requires administrative, physical, and technical safeguards for Electronic Protected Health Information (ePHI).
# HIPAA Administrative Safeguards - Access Control
apiVersion: v1
kind: ConfigMap
metadata:
name: hipaa-access-control
namespace: healthcare-compliance
data:
control-id: "HIPAA-164.312(a)"
control-name: "Access Control"
requirements: |
- Implement technical policies and procedures for electronic information systems
- Maintain a record of who accesses ePHI
- Implement procedures to authorize and monitor access
controls:
unique_user_identifier: true
emergency_access_procedure: true
automatic_logoff: true
encryption_decryption: true
# HIPAA Technical Safeguards - Audit Controls
apiVersion: v1
kind: ConfigMap
metadata:
name: hipaa-audit-controls
namespace: healthcare-compliance
data:
control-id: "HIPAA-164.308(a)(1)(ii)(D)"
control-name: "Audit Controls"
requirements: |
- Implement hardware, software, and procedural mechanisms
- Record and examine activity in information systems
- Retain audit logs for minimum 6 years
controls:
audit_logging_enabled: true
log_aggregation_enabled: true
log_retention_days: 2190 # 6 years
anomaly_detection_enabled: true
# HIPAA Audit Control Implementation - System-Wide Logging
# Implements audit logging for HIPAA compliance
cat > /etc/rsyslog.d/99-hipaa-audit.conf <<'EOF'
# HIPAA Audit Controls - System Logging
# Ensure all security-relevant events are logged
# Enable module for structured logging
module(load="imuxsock" SysSock.Use="on")
module(load="imklog" permitnonkernelfacility="on")
# Define templates for structured JSON logging
template(name="HIPAAJsonFormat" type="string"
string="{\"timestamp\":\"%timestamp:::date-rfc3339%\",\"host\":\"%HOSTNAME%\",\"severity\":\"%syslogseverity-text%\",\"facility\":\"%syslogfacility-text%\",\"program\":\"%programname%\",\"pid\":\"%procid%\",\"message\":\"%msg%\",\"tag\":\"hipaa-audit\"}\n")
# Route security events to dedicated audit log
:programname, isequal, "sshd" action(type="omfile" file="/var/log/hipaa/ssh-audit.log" template="HIPAAJsonFormat")
:programname, isequal, "sudo" action(type="omfile" file="/var/log/hipaa/sudo-audit.log" template="HIPAAJsonFormat")
:programname, isequal, "systemd" action(type="omfile" file="/var/log/hipaa/system-audit.log" template="HIPAAJsonFormat")
# Log all security-related syslog facilities
auth,authpriv.* /var/log/hipaa/security-audit.log;HIPAAJsonFormat
# Forward logs to centralized SIEM
*.* action(type="omfwd" target="siem.internal.domain" port="514" protocol="tcp" template="HIPAAJsonFormat")
EOF
# Create audit log directory with proper permissions
mkdir -p /var/log/hipaa
chown root:root /var/log/hipaa
chmod 700 /var/log/hipaa
touch /var/log/hipaa/ssh-audit.log
touch /var/log/hipaa/sudo-audit.log
touch /var/log/hipaa/system-audit.log
touch /var/log/hipaa/security-audit.log
chmod 600 /var/log/hipaa/*
# Restart rsyslog
systemctl restart rsyslog
# Verify audit logging is working
logger -p auth.info "HIPAA audit test - $(date)"
tail -n 5 /var/log/hipaa/security-audit.log
# HIPAA Security Rule - Encryption at Rest
# Implement encryption for ePHI stored on disk
#!/bin/bash
# hipaa-encryption-at-rest.sh
# Implements encryption for HIPAA compliance
set -euo pipefail
# Check if LUKS encryption is available
if ! command -v cryptsetup &> /dev/null; then
echo "ERROR: cryptsetup not found. Install for disk encryption."
exit 1
fi
# Function to check encryption status
check_encryption() {
local device="$1"
if cryptsetup isLuks "$device" 2>/dev/null; then
echo "✓ $device is encrypted"
return 0
else
echo "✗ $device is NOT encrypted"
return 1
fi
}
# Function to encrypt a volume (requires backup)
encrypt_volume() {
local device="$1"
local mount_point="$2"
echo "WARNING: This will destroy all data on $device"
read -p "Are you sure? Type 'YES' to confirm: " confirmation
if [[ "$confirmation" != "YES" ]]; then
echo "Encryption cancelled"
exit 1
fi
# Backup existing data
echo "Backing up data..."
local backup_dir="/backup/$(date +%Y%m%d)_$(basename "$device")"
mkdir -p "$backup_dir"
cp -r "$mount_point"/* "$backup_dir/" 2>/dev/null || true
# Encrypt the volume
echo "Encrypting volume..."
cryptsetup luksFormat "$device"
# Open encrypted volume
cryptsetup luksOpen "$device" encrypted_volume
# Create filesystem
mkfs.ext4 /dev/mapper/encrypted_volume
# Mount and restore data
mount /dev/mapper/encrypted_volume "$mount_point"
cp -r "$backup_dir"/* "$mount_point/" 2>/dev/null || true
echo "Volume encrypted successfully"
}
# Validate HIPAA encryption compliance
validate_encryption() {
local vulnerable_mounts=()
# Check all mounted filesystems
while read -r mount; do
if [[ "$mount" != *"tmpfs"* && "$mount" != *"devtmpfs"* ]]; then
device=$(echo "$mount" | awk '{print $1}')
mount_point=$(echo "$mount" | awk '{print $3}')
if ! check_encryption "$device"; then
vulnerable_mounts+=("$mount_point")
fi
fi
done < <(mount | grep -v "cgroup")
if [[ ${#vulnerable_mounts[@]} -gt 0 ]]; then
echo "ERROR: Unencrypted volumes found:"
printf ' - %s\n' "${vulnerable_mounts[@]}"
exit 1
else
echo "✓ All volumes are encrypted"
fi
}
Pattern 3: PCI-DSS Requirements Implementation
PCI-DSS v4.0 requires 12 control objectives across 4 categories for payment card data protection.
# PCI-DSS Requirement 1 - Install and Maintain Network Security Controls
apiVersion: v1
kind: ConfigMap
metadata:
name: pci-dss-req1-network-security
namespace: payment-compliance
data:
requirement-id: "1"
requirement-name: "Install and Maintain Network Security Controls"
subrequirements: |
1.1 - Install and maintain firewall configuration
1.2 - Restrict connections between untrusted networks and cardholder data
1.3 - Prohibit direct public access between cardholder data and internet
controls:
firewall_enabled: true
dmz_segmentation: true
default-deny-policy: true
network-segmentation-enabled: true
# PCI-DSS Requirement 7 - Limit Access to System Components
apiVersion: v1
kind: ConfigMap
metadata:
name: pci-dss-req7-access-control
namespace: payment-compliance
data:
requirement-id: "7"
requirement-name: "Limit Access to System Components"
subrequirements: |
7.1 - Implement access restrictions based on need-to-know
7.2 - Limit and control access to cardholder data
7.3 - Document access control methods
controls:
rbac_enabled: true
least-privilege-enforced: true
access-logging-enabled: true
cardholder-data-access-restricted: true
# PCI-DSS Requirement 8 - Identify and Authenticate Access
apiVersion: v1
kind: ConfigMap
metadata:
name: pci-dss-req8-authentication
namespace: payment-compliance
data:
requirement-id: "8"
requirement-name: "Identify and Authenticate Access"
subrequirements: |
8.1 - Unique initial authentication passwords
8.2 - Strong password requirements
8.3 - Multi-factor authentication for remote access
8.5 - Protection of authentication credentials
controls:
password_policy:
min_length: 14
require_uppercase: true
require_lowercase: true
require_numbers: true
require_special_chars: true
history: 12
expiration_days: 90
mfa_enabled: true
credential_encryption: true
# PCI-DSS Requirement 10 - Audit Trail Implementation
# Implement comprehensive logging for PCI-DSS compliance
cat > /etc/rsyslog.d/99-pci-dss-audit.conf <<'EOF'
# PCI-DSS Audit Trail - Comprehensive Logging
# Requirements 10.1-10.8: Track all access to cardholder data
# Define PCI-DSS specific log format
template(name="PCIJSONFormat" type="string"
string="{\"timestamp\":\"%timestamp:::date-rfc3339%\",\"host\":\"%HOSTNAME%\",\"severity\":\"%syslogseverity-text%\",\"facility\":\"%syslogfacility-text%\",\"program\":\"%programname%\",\"pid\":\"%procid%\",\"message\":\"%msg%\",\"tag\":\"pci-dss-audit\",\"pci_requirement\":\"10\"}\n")
# Requirement 10.2 - Log all individual user accesses to cardholder data
:programname, isequal, "sshd" action(type="omfile" file="/var/log/pci/ssh-audit.log" template="PCIJSONFormat")
:programname, isequal, "sudo" action(type="omfile" file="/var/log/pci/sudo-audit.log" template="PCIJSONFormat")
# Requirement 10.3 - Log all system-level events
auth,authpriv.* /var/log/pci/security-audit.log;PCIJSONFormat
# Requirement 10.4 - Implement log integrity controls
# Log rotation with verification
$CycleLogIndex 1
$CycleLogTimestampFormat %Y%m%d
# Requirement 10.5 - Protect log data
:programname, startswith, "payment" action(type="omfile" file="/var/log/pci/payment-audit.log" template="PCIJSONFormat")
# Requirement 10.7 - Retain audit logs for 12 months
# Log rotation configuration
$WorkDirectory /var/lib/rsyslog
$ActionQueueType LinkedList
$ActionQueueFileName pciAudit
$ActionQueueMaxDiskSpace 10g
$ActionQueueSaveOnShutdown on
$ActionResumeRetryCount -1
EOF
# PCI-DSS Requirement 10.3 - Create and maintain audit trail
# Implement comprehensive file access logging
cat > /etc/audit/rules.d/99-pci-dss.rules <<'EOF'
# PCI-DSS Requirement 10 - Audit Trail Rules
# Track all access to cardholder data environment
# Critical system files monitoring
-w /etc/passwd -p wa -k cde_changes
-w /etc/shadow -p wa -k cde_changes
-w /etc/group -p wa -k cde_changes
-w /etc/sudoers -p wa -k cde_changes
-w /etc/sudoers.d/ -p wa -k cde_changes
# Payment application files
-w /etc/payment/ -p wa -k payment_config
-w /opt/payment/ -p wa -k payment_app
# Cardholder data files
-w /var/log/payment/ -p wa -k cardholder_data
-w /var/opt/pci/ -p wa -k cardholder_data
# Authentication files
-w /etc/ssh/sshd_config -p wa -k ssh_config
-w /etc/pam.d/ -p wa -k pam_config
#PCI-DSS Requirement 10.2.1 - Log all user activities
-a always,exit -F arch=b64 -S creat -F dir=/var/log/audit -k file_creation
-a always,exit -F arch=b32 -S creat -F dir=/var/log/audit -k file_creation
#PCI-DSS Requirement 10.2.5 - Log all access to cardholder data
-a always,exit -F arch=b64 -S open -F path=/var/opt/pci/ -k cardholder_access
-a always,exit -F arch=b32 -S open -F path=/var/opt/pci/ -k cardholder_access
-a always,exit -F arch=b64 -S openat -F path=/var/opt/pci/ -k cardholder_access
-a always,exit -F arch=b32 -S openat -F path=/var/opt/pci/ -k cardholder_access
#PCI-DSS Requirement 10.3 - Log all system-level events
-a always,exit -F arch=b64 -S chmod -F dir=/etc/ -k permission_changes
-a always,exit -F arch=b32 -S chmod -F dir=/etc/ -k permission_changes
-a always,exit -F arch=b64 -S chown -F dir=/etc/ -k permission_changes
-a always,exit -F arch=b32 -S chown -F dir=/etc/ -k permission_changes
#PCI-DSS Requirement 10.2.4 - Log all failed access attempts
-a always,exit -F arch=b64 -S open -F exit=-EACCES -k access_denied
-a always,exit -F arch=b32 -S open -F exit=-EACCES -k access_denied
-a always,exit -F arch=b64 -S openat -F exit=-EACCES -k access_denied
-a always,exit -F arch=b32 -S openat -F exit=-EACCES -k access_denied
EOF
# PCI-DSS Requirement 10.7 - Retain audit logs for at least 12 months
# Create log rotation configuration
cat > /etc/logrotate.d/pci-audit <<'EOF'
/var/log/pci/*.log {
daily
missingok
rotate 365
compress
delaycompress
notifempty
create 0640 root adm
dateext
dateformat -%Y%m%d
sharedscripts
postrotate
/usr/bin/systemctl reload rsyslog > /dev/null 2>&1 || true
endscript
}
/var/log/audit/audit.log {
daily
missingok
rotate 365
compress
delaycompress
notifempty
create 0600 root root
dateext
sharedscripts
postrotate
/sbin/ausearch --start today > /dev/null 2>&1 || true
endscript
}
EOF
# Validate PCI-DSS audit configuration
validate_pci_audit() {
local errors=0
# Check audit rules are loaded
if ! auditctl -l | grep -q "pci"; then
echo "ERROR: PCI-DSS audit rules not loaded"
errors=$((errors + 1))
fi
# Check log rotation configured
if [[ ! -f /etc/logrotate.d/pci-audit ]]; then
echo "ERROR: PCI-DSS log rotation not configured"
errors=$((errors + 1))
fi
# Check log directory permissions
if [[ ! -d /var/log/pci ]]; then
echo "ERROR: PCI-DSS log directory not created"
errors=$((errors + 1))
fi
if [[ $? -ne 0 ]]; then
echo "PCI-DSS audit validation: FAILED ($errors errors)"
exit 1
else
echo "PCI-DSS audit validation: PASSED"
fi
}
Pattern 4: Compliance Automation with OpenSCAP
OpenSCAP provides automated compliance scanning for security policies and regulations.
# OpenSCAP Installation and Configuration for PCI-DSS Scanning
#!/bin/bash
# openscap-pci-dss-scanner.sh
# Automates PCI-DSS compliance scanning using OpenSCAP
set -euo pipefail
# Install OpenSCAP tools
install_openscap() {
echo "Installing OpenSCAP tools..."
case "$(command -v apt-get)" in
*apt-get*)
apt-get update && apt-get install -y \
openscap-scanner \
oscap-augeas \
scap-security-guide \
scap-security-guide-doc
;;
*yum*|*dnf*)
yum install -y \
openscap \
openscap-utils \
scap-security-guide
;;
esac
}
# Download PCI-DSS SCAP content
download_pci_scap_content() {
echo "Downloading PCI-DSS SCAP content..."
local content_dir="/usr/share/xml/scap/ssg/content"
local pci_content="ssg-openscap-pci-dss.xml"
if [[ ! -f "$content_dir/$pci_content" ]]; then
echo "PCI-DSS SCAP content not found, installing scap-security-guide..."
install_openscap
fi
echo "$content_dir"
}
# Run PCI-DSS compliance scan
run_pci_scan() {
local target_host="${1:-localhost}"
local output_dir="${2:-/var/openscap/pci-results}"
echo "Running PCI-DSS compliance scan on $target_host..."
# Create output directory
mkdir -p "$output_dir"
# Run SCAP scan
oscap xccdf eval \
--profile pci-dss \
--report "$output_dir/pci-dss-report.html" \
--results-arf "$output_dir/pci-dss-results.xml" \
/usr/share/xml/scap/ssg/content/ssg-openscap-pci-dss.xml
# Generate JSON summary for automation
oscap xccdf eval \
--profile pci-dss \
--fetch-remote-resources \
--json-results "$output_dir/pci-dss-results.json" \
/usr/share/xml/scap/ssg/content/ssg-openscap-pci-dss.xml
echo "Scan complete. Results in $output_dir"
}
# Validate PCI-DSS compliance
validate_pci_compliance() {
local results_file="/var/openscap/pci-results/pci-dss-results.json"
if [[ ! -f "$results_file" ]]; then
echo "ERROR: PCI-DSS scan results not found"
exit 1
fi
# Check for passing controls
local passing=$(jq '.total_passed_checks' "$results_file")
local failing=$(jq '.total_failed_checks' "$results_file")
local total=$(jq '.total_checks' "$results_file")
echo "PCI-DSS Compliance Summary:"
echo " Passing: $passing / $total"
echo " Failing: $failing"
if [[ $failing -gt 0 ]]; then
echo "PCI-DSS Compliance: FAILED"
echo "Failed controls:"
jq -r '.checks[] | select(.result == "fail") | " - \(.benchmark_id)"' "$results_file"
exit 1
else
echo "PCI-DSS Compliance: PASSED"
fi
}
# Generate compliance evidence package
generate_evidence_package() {
local scan_date=$(date +%Y%m%d)
local evidence_dir="/var/evidence/pci-dss/$scan_date"
mkdir -p "$evidence_dir"
# Copy scan results
cp -r /var/openscap/pci-results/* "$evidence_dir/"
# Generate metadata
cat > "$evidence_dir/metadata.json" <<EOF
{
"evidence_type": "pci-dss-scan",
"scan_date": "$(date -Iseconds)",
"scanned_host": "$(hostname)",
"scap_profile": "pci-dss",
"scap_version": "1.3",
"scanner": "OpenSCAP",
"scanner_version": "$(oscap --version | head -1)"
}
EOF
# Create evidence archive
tar -czf "$evidence_dir/evidence-package.tar.gz" -C "$evidence_dir" .
echo "Evidence package generated: $evidence_dir/evidence-package.tar.gz"
}
# Main execution
case "${1:-scan}" in
install)
install_openscap
;;
scan)
run_pci_scan "${2:-localhost}" "${3:-/var/openscap/pci-results}"
;;
validate)
validate_pci_compliance
;;
evidence)
generate_evidence_package
;;
*)
echo "Usage: $0 {install|scan [host] [output-dir]|validate|evidence}"
exit 1
;;
esac
Pattern 5: Compliance Automation with Trivy
Trivy provides container image scanning for security vulnerabilities and compliance checks.
# Trivy Configuration for PCI-DSS and SOC2 Compliance
#!/bin/bash
# trivy-compliance-scanner.sh
# Automates container compliance scanning for PCI-DSS and SOC2
set -euo pipefail
# Install Trivy
install_trivy() {
echo "Installing Trivy..."
# Download and install Trivy
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
# Verify installation
trivy --version
# Download vulnerability database
trivy image --download-db-only
}
# Configure Trivy for PCI-DSS scanning
configure_pci_trivy() {
cat > /etc/trivy/pci-dss.yaml <<'EOF'
# Trivy PCI-DSS Configuration
# Custom configuration for PCI-DSS compliance scanning
scan:
RemovedPackages: false
Misconfigurations: true
Secrets: true
VulnerabilityType:
- OS
- Library
severity:
- HIGH
- CRITICAL
format: table
# PCI-DSS specific misconfigurations
misconfiguration:
check:
- PCI-DSS-1.1 # Firewall configuration
- PCI-DSS-1.2 # Network segmentation
- PCI-DSS-1.3 # Prohibit direct public access
- PCI-DSS-2.1 # Default accounts removed
- PCI-DSS-2.2 # Only necessary services enabled
- PCI-DSS-6.1 # Security patches applied
- PCI-DSS-6.5 # Secure coding practices
- PCI-DSS-6.6 # Web application security
- PCI-DSS-8.1 # Unique user identification
- PCI-DSS-8.2 # Strong password requirements
- PCI-DSS-8.3 # Multi-factor authentication
- PCI-DSS-8.5 # Protection of authentication credentials
- PCI-DSS-10.1 # Audit trail implementation
- PCI-DSS-10.2 # Access logging
- PCI-DSS-10.3 # Log integrity controls
- PCI-DSS-10.7 # Log retention (12 months)
EOF
echo "Trivy PCI-DSS configuration created at /etc/trivy/pci-dss.yaml"
}
# Scan container image for PCI-DSS compliance
scan_pci_image() {
local image="${1:?Image name required}"
local output_dir="${2:-/var/trivy/pci-results}"
local scan_date=$(date +%Y%m%d)
mkdir -p "$output_dir/$scan_date"
echo "Scanning image: $image for PCI-DSS compliance..."
# Run Trivy PCI-DSS scan
trivy image \
--config /etc/trivy/pci-dss.yaml \
--severity HIGH,CRITICAL \
--format table \
--output "$output_dir/$scan_date/pci-dss-report.txt" \
"$image"
# Generate JSON results for automation
trivy image \
--config /etc/trivy/pci-dss.yaml \
--severity HIGH,CRITICAL \
--format json \
--output "$output_dir/$scan_date/pci-dss-results.json" \
"$image"
# Check for compliance failures
if grep -q "FAILED" "$output_dir/$scan_date/pci-dss-report.txt"; then
echo "PCI-DSS Compliance: FAILED"
grep "FAILED" "$output_dir/$scan_date/pci-dss-report.txt"
exit 1
else
echo "PCI-DSS Compliance: PASSED"
fi
}
# Scan for SOC2 compliance
scan_soc2_image() {
local image="${1:?Image name required}"
local output_dir="${2:-/var/trivy/soc2-results}"
local scan_date=$(date +%Y%m%d)
mkdir -p "$output_dir/$scan_date"
echo "Scanning image: $image for SOC2 compliance..."
# Create SOC2 configuration
cat > /tmp/soc2-config.yaml <<'EOF'
# Trivy SOC2 Configuration
misconfiguration:
check:
- SOC2-CC1.1 # Control environment
- SOC2-CC2.1 # Communication and information
- SOC2-CC3.1 # Risk assessment
- SOC2-CC4.1 # Monitoring and evaluation
- SOC2-CC5.1 # Access control
- SOC2-CC6.1 # Logical access security
- SOC2-CC6.2 # Network security
- SOC2-CC7.1 # System monitoring
- SOC2-CC7.2 # Alerting
- SOC2-CC8.1 # Change management
- SOC2-CC8.2 # Configuration management
EOF
trivy image \
--config /tmp/soc2-config.yaml \
--severity HIGH,CRITICAL \
--format json \
--output "$output_dir/$scan_date/soc2-results.json" \
"$image"
echo "SOC2 scan complete: $output_dir/$scan_date/soc2-results.json"
}
# Generate compliance evidence package
generate_trivy_evidence() {
local image="${1:?Image name required}"
local evidence_dir="/var/evidence/trivy/$(date +%Y%m%d)"
mkdir -p "$evidence_dir"
# Run multiple scans
scan_pci_image "$image" /var/trivy/pci-results
scan_soc2_image "$image" /var/trivy/soc2-results
# Copy all results to evidence directory
cp -r /var/trivy/pci-results/* "$evidence_dir/pci/"
cp -r /var/trivy/soc2-results/* "$evidence_dir/soc2/"
# Generate metadata
cat > "$evidence_dir/metadata.json" <<EOF
{
"evidence_type": "container-compliance",
"scan_date": "$(date -Iseconds)",
"scanned_image": "$image",
"scanned_host": "$(hostname)",
"scanner": "Trivy",
"scanner_version": "$(trivy --version | head -1)"
}
EOF
# Create evidence archive
tar -czf "$evidence_dir/evidence-package.tar.gz" -C "$evidence_dir" .
echo "Evidence package generated: $evidence_dir/evidence-package.tar.gz"
}
# Run compliance checks in CI/CD pipeline
ci_pipeline_check() {
local image="${1:-app:latest}"
echo "Running CI/CD compliance check..."
# Check for critical vulnerabilities
trivy image \
--severity CRITICAL,HIGH \
--exit-code 1 \
"$image" && {
echo "✓ No critical vulnerabilities found"
} || {
echo "✗ Critical vulnerabilities found"
exit 1
}
# Check for PCI-DSS misconfigurations
trivy config \
--config /etc/trivy/pci-dss.yaml \
--severity HIGH,CRITICAL \
--exit-code 1 \
--scanners misconfig \
. && {
echo "✓ No PCI-DSS misconfigurations found"
} || {
echo "✗ PCI-DSS misconfigurations found"
exit 1
}
echo "CI/CD Compliance Check: PASSED"
}
# Main execution
case "${1:-scan}" in
install)
install_trivy
configure_pci_trivy
;;
scan-pci)
scan_pci_image "${2:-app:latest}" "${3:-/var/trivy/pci-results}"
;;
scan-soc2)
scan_soc2_image "${2:-app:latest}" "${3:-/var/trivy/soc2-results}"
;;
evidence)
generate_trivy_evidence "${2:-app:latest}"
;;
ci)
ci_pipeline_check "${2:-app:latest}"
;;
*)
echo "Usage: $0 {install|scan-pci [image] [output-dir]|scan-soc2 [image] [output-dir]|evidence [image]|ci [image]}"
exit 1
;;
esac
Pattern 6: Compliance Automation with Klar (Clair Integration)
Klar integrates with Clair for container vulnerability scanning with compliance reporting.
# Klar Configuration for Compliance Scanning
#!/bin/bash
# klar-compliance-scanner.sh
# Automates Clair-based container vulnerability scanning for compliance
set -euo pipefail
# Install Klar
install_klar() {
echo "Installing Klar..."
local version="2.6.1"
local os="linux"
local arch="amd64"
curl -L "https://github.com/optiopay/klar/releases/download/v${version}/klar-${version}-${os}-${arch}.tar.gz" \
| tar -xz -C /tmp &&
mv /tmp/klar /usr/local/bin/
echo "Klar installed successfully"
}
# Configure Clair API endpoint
configure_clair() {
local clair_url="${CLAIR_URL:-http://clair.local:6060}"
local namespace="${CLAIR_NAMESPACE:-default}"
cat > /etc/klar/klar.yml <<EOF
clair_url: $clair_url
clair_api_version: 3
namespace: $namespace
output: text
format: table
severity: HIGH,CRITICAL
EOF
echo "Klar configured with Clair at $clair_url"
}
# Scan image with Klar for PCI-DSS compliance
scan_pci_with_klar() {
local image="${1:?Image name required}"
local output_dir="${2:-/var/klar/pci-results}"
local scan_date=$(date +%Y%m%d)
mkdir -p "$output_dir/$scan_date"
echo "Scanning $image with Klar for PCI-DSS compliance..."
# Set Docker registry credentials
export CLAIR_USER="${DOCKER_REGISTRY_USER:-}"
export CLAIR_PASS="${DOCKER_REGISTRY_PASSWORD:-}"
# Run Klar scan
klar status \
--output "$output_dir/$scan_date/klar-results.txt" \
"$image" > "$output_dir/$scan_date/klar-output.txt"
# Parse results
local critical=$(grep -c "Critical" "$output_dir/$scan_date/klar-results.txt" || true)
local high=$(grep -c "High" "$output_dir/$scan/results.txt" || true)
echo "PCI-DSS Vulnerability Summary:"
echo " Critical: $critical"
echo " High: $high"
if [[ $critical -gt 0 ]]; then
echo "PCI-DSS Compliance: FAILED (Critical vulnerabilities found)"
exit 1
fi
echo "PCI-DSS Compliance: PASSED"
}
# Scan image with Klar for SOC2 compliance
scan_soc2_with_klar() {
local image="${1:?Image name required}"
local output_dir="${2:-/var/klar/soc2-results}"
local scan_date=$(date +%Y%m%d)
mkdir -p "$output_dir/$scan_date"
echo "Scanning $image with Klar for SOC2 compliance..."
# Run Klar scan with security focus
klar status \
--severity HIGH,CRITICAL \
--output "$output_dir/$scan_date/klar-results.txt" \
"$image" > "$output_dir/$scan_date/klar-output.txt"
echo "SOC2 scan complete: $output_dir/$scan_date/klar-results.txt"
}
# Generate compliance report
generate_klar_report() {
local image="${1:?Image name required}"
local report_dir="/var/reports/klar/$(date +%Y%m%d)"
mkdir -p "$report_dir"
# Run both scans
scan_pci_with_klar "$image" /var/klar/pci-results
scan_soc2_with_klar "$image" /var/klar/soc2-results
# Generate combined report
cat > "$report_dir/compliance-report.md" <<EOF
# Container Compliance Report
## Image: $image
## Scan Date: $(date -Iseconds)
## Scanner: Klar (Clair)
## PCI-DSS Compliance
### Critical Vulnerabilities: $(grep -c "Critical" /var/klar/pci-results/$(date +%Y%m%d)/*-results.txt 2>/dev/null || echo 0)
### High Vulnerabilities: $(grep -c "High" /var/klar/pci-results/$(date +%Y%m%d)/*-results.txt 2>/dev/null || echo 0)
$(cat /var/klar/pci-results/$(date +%Y%m%d)/*-results.txt 2>/dev/null || echo "No PCI-DSS results available")
## SOC2 Compliance
### Critical Vulnerabilities: $(grep -c "Critical" /var/klar/soc2-results/$(date +%Y%m%d)/*-results.txt 2>/dev/null || echo 0)
### High Vulnerabilities: $(grep -c "High" /var/klar/soc2-results/$(date +%Y%m%d)/*-results.txt 2>/dev/null || echo 0)
$(cat /var/klar/soc2-results/$(date +%Y%m%d)/*-results.txt 2>/dev/null || echo "No SOC2 results available")
## Conclusion
EOF
echo "Report generated: $report_dir/compliance-report.md"
}
# CI/CD integration check
klar_ci_check() {
local image="${1:-app:latest}"
echo "Running CI/CD compliance check with Klar..."
# Run Klar with exit on critical vulnerabilities
if klar status --severity CRITICAL "$image" 2>/dev/null; then
echo "✓ No critical vulnerabilities found"
else
echo "✗ Critical vulnerabilities found"
klar status --severity CRITICAL "$image" 2>&1 | grep -A5 "Critical"
exit 1
fi
# Check for high severity vulnerabilities
if klar status --severity HIGH "$image" 2>/dev/null; then
echo "✓ No high severity vulnerabilities found"
else
echo "✗ High severity vulnerabilities found"
klar status --severity HIGH "$image" 2>&1 | grep -A5 "High"
exit 1
fi
echo "CI/CD Compliance Check: PASSED"
}
# Main execution
case "${1:-scan}" in
install)
install_klar
configure_clair
;;
scan-pci)
scan_pci_with_klar "${2:-app:latest}" "${3:-/var/klar/pci-results}"
;;
scan-soc2)
scan_soc2_with_klar "${2:-app:latest}" "${3:-/var/klar/soc2-results}"
;;
report)
generate_klar_report "${2:-app:latest}"
;;
ci)
klar_ci_check "${2:-app:latest}"
;;
*)
echo "Usage: $0 {install|scan-pci [image] [output-dir]|scan-soc2 [image] [output-dir]|report [image]|ci [image]}"
exit 1
;;
esac
Pattern 7: Audit Trail Implementation
Comprehensive audit trail implementation for compliance evidence collection.
# Audit Trail Configuration - SOC2/PCI-DSS/HIPAA
apiVersion: v1
kind: ConfigMap
metadata:
name: audit-trail-configuration
namespace: compliance
data:
framework: "SOC2, PCI-DSS, HIPAA"
requirements: |
- SOC2 CC7: System monitoring and audit trails
- PCI-DSS Requirement 10: Audit trail implementation
- HIPAA Audit Controls: 164.308(a)(1)(ii)(D)
controls:
audit_logging_enabled: true
log_retention_days: 365
log_encryption_enabled: true
log_integrity_enabled: true
anomaly_detection_enabled: true
real_time_alerting_enabled: true
# Comprehensive Audit Trail Implementation
#!/bin/bash
# audit-trail-implementer.sh
# Implements comprehensive audit trails for compliance
set -euo pipefail
# Install audit tools
install_audit_tools() {
echo "Installing audit tools..."
case "$(command -v apt-get)" in
*apt-get*)
apt-get update && apt-get install -y \
auditd \
ausearch \
aureport \
logwatch \
fail2ban \
rsyslog
;;
*yum*|*dnf*)
yum install -y \
audit \
audit-libs \
rsyslog \
logwatch \
fail2ban
;;
esac
# Enable auditd
systemctl enable auditd
systemctl start auditd
}
# Configure audit rules for SOC2 compliance
configure_soc2_audit_rules() {
cat > /etc/audit/rules.d/99-soc2.rules <<'EOF'
# SOC2 Audit Rules - CC6, CC7, CC8
# CC6: Logical Access Security
# CC7: System Monitoring
# CC8: Change Management
# File access monitoring
-w /etc/passwd -p wa -k identity_access
-w /etc/shadow -p wa -k identity_access
-w /etc/group -p wa -k identity_access
# Authentication events
-a always,exit -F arch=b64 -S login -k authentication
-a always,exit -F arch=b32 -S login -k authentication
-a always,exit -F arch=b64 -S acct -k user_modifications
-a always,exit -F arch=b32 -S acct -k user_modifications
# Privilege escalation
-a always,exit -F arch=b64 -S setuid -F a0=0 -k privilege_escalation
-a always,exit -F arch=b32 -S setuid -F a0=0 -k privilege_escalation
-a always,exit -F arch=b64 -S setgid -F a0=0 -k privilege_escalation
-a always,exit -F arch=b32 -S setgid -F a0=0 -k privilege_escalation
# System configuration changes
-w /etc/audit/ -p wa -k config_changes
-w /etc/ssh/ -p wa -k ssh_config_changes
-w /etc/sudoers -p wa -k sudo_config_changes
# Service management
-a always,exit -F arch=b64 -S init_module -k module_loading
-a always,exit -F arch=b32 -S init_module -k module_loading
-a always,exit -F arch=b64 -S delete_module -k module_loading
-a always,exit -F arch=b32 -S delete_module -k module_loading
# Network changes
-w /etc/hosts -p wa -k network_changes
-w /etc/sysconfig/network-scripts/ -p wa -k network_changes
-w /etc/resolv.conf -p wa -k network_changes
# Time changes
-a always,exit -F arch=b64 -S sethostname -k time_changes
-a always,exit -F arch=b32 -S sethostname -k time_changes
-a always,exit -F arch=b64 -S setdomainname -k time_changes
-a always,exit -F arch=b32 -S setdomainname -k time_changes
# File integrity
-w /usr/bin/ -p x -k system_binaries
-w /usr/sbin/ -p x -k system_binaries
-w /bin/ -p x -k system_binaries
-w /sbin/ -p x -k system_binaries
EOF
}
# Configure audit rules for PCI-DSS compliance
configure_pci_audit_rules() {
cat > /etc/audit/rules.d/99-pci-dss.rules <<'EOF'
# PCI-DSS Audit Rules - Requirement 10
# 10.1 - Implement audit trails
# 10.2 - Implement procedures for audit log generation
# 10.3 - Protect audit trail
# 10.4 - Correlate audit logs
# 10.5 - Use secure storage
# 1
…(truncated)