PCI DSS Compliance

๐Ÿ”ฅ Vibe Prompt

"Make payment processing PCI DSS compliant: network segmentation, encryption, access control, logging."

PCI DSS 12 Requirements

| # | Requirement | Example Controls |
|---|-------------|------------------|
| 1  | Firewall | Network seg, DMZ, deny by default |
| 2  | Secure config | Remove defaults, hardening |
| 3  | Protect stored data | Encryption, truncation, masking |
| 4  | Encrypt transmission | TLS 1.2+, strong ciphers |
| 5  | Anti-malware | AV on all servers (Windows) |
| 6  | Secure apps | SDLC, code review, vuln scans |
| 7  | Restrict access | Need-to-know, RBAC |
| 8  | Identify users | Unique IDs, MFA |
| 9  | Physical security | Badge access, CCTV |
| 10 | Logging | Audit trails, log retention (1yr) |
| 11 | Testing | Quarterly scans, annual pen test |
| 12 | Policy | Security policy, risk assessment |

CDE (Cardholder Data Environment)

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  CDE (Cardholder Data Environment)  โ”‚
โ”‚  โ”œโ”€โ”€ Payment processing servers     โ”‚
โ”‚  โ”œโ”€โ”€ Tokenization / encryption DB   โ”‚
โ”‚  โ””โ”€โ”€ HSM (Hardware Security Module) โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ†‘ Only CDE can access CDE
         โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Non-CDE (everything else)          โ”‚
โ”‚  โ”œโ”€โ”€ Web servers (public)           โ”‚
โ”‚  โ”œโ”€โ”€ App servers                    โ”‚
โ”‚  โ””โ”€โ”€ Corporate network              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Tokenization (PCI DSS Requirement 3)

# Instead of storing card numbers, store tokens
import uuid

def tokenize(card_number):
    # Call tokenization service
    response = requests.post("https://tokenizer.example.com/tokenize",
        json={"pan": card_number},
        headers={"Authorization": f"Bearer {vault_token}"}
    )
    return response.json()["token"]  # e.g., "tok_abc123..."

# Store only token (not the card number!)
db.execute("INSERT INTO payments (order_id, token, amount, currency) VALUES (%s, %s, %s, %s)",
           (order_id, tokenized_card, 99.99, "USD"))

Encryption at Rest (Requirement 3.4)

# PAN must be rendered unreadable
from cryptography.fernet import Fernet

# Encrypt PAN before storing
key = vault.get_secret("payment-encryption-key")
cipher = Fernet(key)
encrypted_pan = cipher.encrypt(b"4111111111111111")

# Store encrypted
db.execute("INSERT INTO payments (encrypted_pan, token, amount) VALUES (%s, %s, %s)",
           (encrypted_pan, token, 99.99))

# Mask for display (show last 4)
masked = "************" + card_number[-4:]
# Display: ************1111

Logging Requirements (Requirement 10)

# PCI logging requirements
# 1. All access to CDE
# 2. All privileged operations
# 3. Audit trails (cannot be altered)
# 4. Log retention: 1 year (online), 3 months (immediate access)

class PCILogger:
    def __init__(self):
        self.logger = logging.getLogger('pci')
        # Send to SIEM (write-once, immutable)
        handler = logging.handlers.SysLogHandler(address=('siem.company.com', 514))
        self.logger.addHandler(handler)
    
    def log_access(self, user, resource, action):
        self.logger.info(json.dumps({
            "type": "pci_access",
            "timestamp": datetime.utcnow().isoformat(),
            "user": user,
            "resource": resource,
            "action": action,
            "ip": request.remote_addr,
            "user_agent": request.user_agent.string
        }))
    
    def log_admin(self, user, action, details):
        self.logger.warning(json.dumps({
            "type": "pci_admin",
            "timestamp": datetime.utcnow().isoformat(),
            "user": user,
            "action": action,
            "details": details
        }))

Quarterly Scan & Annual Pentest (Req 11)

# Quarterly ASV scan (Approved Scanning Vendor)
# We use Trustwave:
./trustwave_scan.sh --target 203.0.113.0/24 --output scan_q1_2024.pdf

# Annual penetration test
# Must cover CDE + critical systems
nmap -sV -p- --script vulners 203.0.113.10 -oN annual_pentest_2024.txt

PCI DSS Compliance Levels

| Level | Transactions/year | Validation | |-------|------------------|------------| | 1 | >6M | On-site assessment + QSA | | 2 | 1M-6M | SAQ + scan | | 3 | 20K-1M | SAQ + scan | | 4 | <20K | SAQ + scan |

Best Practices

  • Outsource payment processing (Stripe, Braintree) = reduced scope!
  • Never store CVV or PIN
  • Tokenize all card data
  • Segment CDE from non-CDE
  • Use 3D Secure for transactions
  • Implement TDE for database encryption
  • Deploy HSM for key management
  • Rotate encryption keys quarterly

PCI DSS 12 Requirements Overview

| Requirement | Focus | Key Activities | |-------------|-------|---------------| | 1 | Firewall | Install and maintain firewall rules to protect cardholder data | | 2 | Passwords | Change vendor defaults, use strong passwords | | 3 | Data protection | Protect stored cardholder data (encrypt PAN, truncate, tokenize) | | 4 | Encryption | Encrypt transmission of cardholder data over open networks | | 5 | Anti-malware | Use and regularly update anti-malware software | | 6 | Secure systems | Develop and maintain secure systems and applications | | 7 | Access control | Restrict access to cardholder data by business need-to-know | | 8 | Authentication | Assign unique IDs to users, use MFA | | 9 | Physical security | Restrict physical access to cardholder data | | 10 | Logging | Track and monitor all access to network resources and cardholder data | | 11 | Testing | Regularly test security systems and processes | | 12 | Policy | Maintain a policy that addresses information security |

Requirement 3: Data Protection

import os
from cryptography.fernet import Fernet

def encrypt_pan(pan: str, key: bytes) -> str:
    """Encrypt a Primary Account Number (PAN)."""
    f = Fernet(key)
    token = f.encrypt(pan.encode())
    return token.decode()

def mask_pan(pan: str) -> str:
    """Mask PAN โ€” only last 4 digits visible."""
    return f"XXXX-XXXX-XXXX-{pan[-4:]}" if len(pan) >= 4 else pan

# Generate encryption key
key = Fernet.generate_key()

# Example
pan = "4111111111111111"
encrypted = encrypt_pan(pan, key)
masked = mask_pan(pan)

print(f"Original: {pan}")
print(f"Masked:   {masked}")
print(f"Encrypted: {encrypted[:40]}...")

# PCI DSS requires: never store CVV, never store full track data after authorization

Requirement 10: Logging

# Logging requirements per PCI DSS 10.2
required_events:
  - All individual user access to cardholder data
  - All actions taken by root or administrative accounts
  - All access to audit trails
  - Invalid logical access attempts
  - Use of identification and authentication mechanisms
  - Initialization of audit logs
  - Creation and deletion of system-level objects

log_content:
  - User identification
  - Type of event
  - Date and time
  - Success or failure indication
  - Origination of event
  - Identity or name of affected data or component

SAQ (Self-Assessment Questionnaire) Types

| SAQ Type | Who Can Use It | |----------|---------------| | SAQ A | Card-not-present merchants (e-commerce only) | | SAQ A-EP | E-commerce with third-party payment processing | | SAQ B | Imprint-only merchants (no electronic storage) | | SAQ C | Merchants with payment application connected to internet | | SAQ C-VT | Merchants using virtual terminal on a PC | | SAQ D | All other merchants (most complex) |

Summary

PCI DSS has 12 requirements covering firewall, passwords, data protection, encryption, anti-malware, secure systems, access control, authentication, physical security, logging, testing, and policy.

Key takeaways: | 12 requirements: firewall โ†’ passwords โ†’ data protection โ†’ encryption โ†’ anti-malware โ†’ secure systems โ†’ access control โ†’ authentication โ†’ physical โ†’ logging โ†’ testing โ†’ policy | | Never store CVV after authorization | | Mask PAN: only last 4 digits visible | | Encrypt PAN at rest with AES-256 | | Log all access to cardholder data | | SAQ D is the most comprehensive self-assessment | | Annual ASV scan required for all merchants |

Next Chapter: Compliance Automation

The next chapter covers automating compliance monitoring.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!