🔒 Security

HIPAA

Health Insurance Portability and Accountability Act

HIPAA is a US federal law enacted in 1996 that protects the privacy and security of health information (PHI: Protected Health Information). Healthcare providers, insurers, and IT companies handling health data must comply with HIPAA regulations.

📖 Detailed Explanation

HIPAA (Health Insurance Portability and Accountability Act) is a federal law that forms the foundation of the U.S. healthcare industry. It was enacted in 1996 under President Bill Clinton and initially focused on insurance portability, but it later developed into the core framework for protecting health information with the addition of the Privacy Rule in 2003 and the Security Rule in 2005. In the era of digital healthcare, HIPAA has become an essential consideration in the design of healthcare IT systems.

The core of HIPAA is the protection of PHI (Protected Health Information). PHI includes 18 types of data that can identify a patient: name, date of birth, address, Social Security number, medical record number, health insurance ID, photos, email, and more. ePHI (Electronic PHI) is PHI stored or transmitted in digital form and is subject to the stricter Security Rule. Even a single PHI breach can result in serious legal liability and reputational damage.

HIPAA consists of three core rules. The Privacy Rule sets standards for the use and disclosure of PHI (patient consent, minimum necessary principle). The Security Rule requires technical, physical, and administrative safeguards for ePHI (encryption, access control, audit logs). The Breach Notification Rule stipulates the obligation to notify patients and HHS (the U.S. Department of Health and Human Services) within 72 hours of a PHI breach. If 500 or more people are affected, a media notice is also mandatory.

Entities subject to HIPAA are divided into Covered Entities (healthcare providers, insurers, healthcare clearinghouses) and Business Associates (third parties that handle PHI on behalf of a CE). Most cloud service, SaaS, and AI healthcare solution providers qualify as BAs. A BA must enter into a BAA (Business Associate Agreement) with the CE and is directly liable for HIPAA violations. Penalties for violations are up to $1.5M per violation ($15M per year), and criminal penalties are also possible.

💻 Code Example

# HIPAA 준수를 위한 PHI 데이터 보호 예제 - Python
import hashlib
import logging
from datetime import datetime
from typing import Dict, Any, Optional
from cryptography.fernet import Fernet
from functools import wraps

# HIPAA 감사 로그 설정 (Security Rule 요구사항)
logging.basicConfig(
    filename='hipaa_audit.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
audit_logger = logging.getLogger('HIPAA_AUDIT')

# PHI 식별자 18가지 유형
PHI_IDENTIFIERS = [
    'name', 'address', 'dates', 'phone', 'fax', 'email',
    'ssn', 'mrn', 'health_plan_id', 'account_number',
    'certificate_number', 'vehicle_id', 'device_id', 'url',
    'ip_address', 'biometric', 'photo', 'any_unique_id'
]

class HIPAACompliantStorage:
    """HIPAA 준수 PHI 저장소"""

    def __init__(self, encryption_key: bytes):
        self.cipher = Fernet(encryption_key)
        self._phi_access_log = []

    def encrypt_phi(self, phi_data: Dict[str, Any]) -> bytes:
        """PHI 암호화 (Security Rule - 기술적 보호조치)"""
        import json
        json_data = json.dumps(phi_data)
        encrypted = self.cipher.encrypt(json_data.encode())

        # 감사 로그 기록
        audit_logger.info(f"PHI encrypted: patient_id={phi_data.get('patient_id', 'unknown')}")
        return encrypted

    def decrypt_phi(self, encrypted_data: bytes, user_id: str, purpose: str) -> Dict[str, Any]:
        """PHI 복호화 (접근 기록 필수)"""
        import json

        # 접근 기록 (Minimum Necessary 원칙 확인용)
        access_record = {
            'timestamp': datetime.utcnow().isoformat(),
            'user_id': user_id,
            'purpose': purpose,
            'action': 'decrypt'
        }
        self._phi_access_log.append(access_record)
        audit_logger.info(f"PHI accessed: user={user_id}, purpose={purpose}")

        decrypted = self.cipher.decrypt(encrypted_data)
        return json.loads(decrypted.decode())


def hipaa_audit_required(action: str):
    """HIPAA 감사 로그 데코레이터"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            user_id = kwargs.get('user_id', 'system')
            patient_id = kwargs.get('patient_id', 'unknown')

            # 접근 전 로그
            audit_logger.info(
                f"PHI_ACCESS_START: action={action}, user={user_id}, patient={patient_id}"
            )

            try:
                result = func(*args, **kwargs)
                audit_logger.info(
                    f"PHI_ACCESS_SUCCESS: action={action}, user={user_id}"
                )
                return result
            except Exception as e:
                audit_logger.error(
                    f"PHI_ACCESS_FAILED: action={action}, user={user_id}, error={str(e)}"
                )
                raise
        return wrapper
    return decorator


def de_identify_phi(phi_record: Dict[str, Any]) -> Dict[str, Any]:
    """PHI 비식별화 (Safe Harbor 방식)

    HIPAA에서 허용하는 18가지 식별자 제거/변환
    """
    de_identified = phi_record.copy()

    # 직접 식별자 제거
    for identifier in PHI_IDENTIFIERS:
        if identifier in de_identified:
            if identifier in ['name', 'ssn', 'email', 'phone']:
                de_identified[identifier] = '[REDACTED]'
            elif identifier == 'dates':
                # 연도만 유지 (Safe Harbor)
                de_identified[identifier] = de_identified[identifier][:4] + '-XX-XX'
            elif identifier == 'address':
                # 주(State)만 유지, 상세 주소 제거
                de_identified[identifier] = de_identified.get('state', '[REDACTED]')

    return de_identified


# 사용 예시
if __name__ == "__main__":
    # 암호화 키 생성 (실제로는 안전한 키 관리 시스템 사용)
    key = Fernet.generate_key()
    storage = HIPAACompliantStorage(key)

    # PHI 데이터
    patient_phi = {
        'patient_id': 'P12345',
        'name': 'John Doe',
        'ssn': '123-45-6789',
        'dates': '1985-03-15',
        'diagnosis': 'Type 2 Diabetes',
        'medication': 'Metformin 500mg'
    }

    # 암호화 저장
    encrypted = storage.encrypt_phi(patient_phi)

    # 권한 있는 접근
    decrypted = storage.decrypt_phi(
        encrypted,
        user_id='dr_smith',
        purpose='Treatment'
    )

    # 연구용 비식별화
    de_identified = de_identify_phi(patient_phi)
    print(f"De-identified: {de_identified}")
// HIPAA 준수 ePHI 암호화 및 접근 제어 - Node.js
const crypto = require('crypto');
const { createLogger, format, transports } = require('winston');

// HIPAA 감사 로그 설정
const auditLogger = createLogger({
    level: 'info',
    format: format.combine(
        format.timestamp(),
        format.json()
    ),
    transports: [
        new transports.File({ filename: 'hipaa_audit.log' }),
        new transports.File({ filename: 'hipaa_error.log', level: 'error' })
    ]
});

class HIPAAEncryption {
    constructor() {
        // AES-256-GCM (HIPAA Security Rule 권장)
        this.algorithm = 'aes-256-gcm';
        this.keyLength = 32;
        this.ivLength = 16;
        this.tagLength = 16;
    }

    /**
     * ePHI 암호화 (전송 중 & 저장 시 암호화)
     */
    encryptPHI(plaintext, encryptionKey) {
        const iv = crypto.randomBytes(this.ivLength);
        const cipher = crypto.createCipheriv(
            this.algorithm,
            Buffer.from(encryptionKey, 'hex'),
            iv
        );

        let encrypted = cipher.update(plaintext, 'utf8', 'hex');
        encrypted += cipher.final('hex');
        const authTag = cipher.getAuthTag();

        // IV + AuthTag + Encrypted Data
        return {
            iv: iv.toString('hex'),
            authTag: authTag.toString('hex'),
            encryptedData: encrypted
        };
    }

    /**
     * ePHI 복호화
     */
    decryptPHI(encryptedObj, encryptionKey) {
        const decipher = crypto.createDecipheriv(
            this.algorithm,
            Buffer.from(encryptionKey, 'hex'),
            Buffer.from(encryptedObj.iv, 'hex')
        );

        decipher.setAuthTag(Buffer.from(encryptedObj.authTag, 'hex'));

        let decrypted = decipher.update(encryptedObj.encryptedData, 'hex', 'utf8');
        decrypted += decipher.final('utf8');

        return decrypted;
    }
}

/**
 * HIPAA 접근 제어 미들웨어
 */
class HIPAAAccessControl {
    constructor() {
        this.allowedRoles = {
            'view_phi': ['physician', 'nurse', 'admin'],
            'edit_phi': ['physician', 'admin'],
            'export_phi': ['admin', 'compliance_officer']
        };
    }

    /**
     * Minimum Necessary 원칙 적용
     */
    checkMinimumNecessary(userRole, requestedFields, purpose) {
        const allowedFields = {
            'physician': ['*'], // 모든 필드
            'nurse': ['name', 'vitals', 'medication', 'allergies'],
            'billing': ['name', 'insurance_id', 'procedure_codes'],
            'researcher': ['age_range', 'diagnosis', 'anonymized_id']
        };

        const userAllowed = allowedFields[userRole] || [];

        if (userAllowed.includes('*')) return requestedFields;

        return requestedFields.filter(field => userAllowed.includes(field));
    }

    /**
     * 접근 권한 검증 미들웨어
     */
    authorize(requiredPermission) {
        return (req, res, next) => {
            const userRole = req.user?.role;
            const userId = req.user?.id;

            // 감사 로그 기록
            auditLogger.info({
                event: 'PHI_ACCESS_ATTEMPT',
                userId,
                userRole,
                permission: requiredPermission,
                patientId: req.params.patientId,
                ipAddress: req.ip,
                timestamp: new Date().toISOString()
            });

            if (!this.allowedRoles[requiredPermission]?.includes(userRole)) {
                auditLogger.warn({
                    event: 'PHI_ACCESS_DENIED',
                    userId,
                    userRole,
                    permission: requiredPermission,
                    reason: 'Insufficient permissions'
                });

                return res.status(403).json({
                    error: 'Access Denied',
                    message: 'You do not have permission to access this PHI'
                });
            }

            next();
        };
    }
}

/**
 * Breach Notification 헬퍼
 */
async function notifyBreach(breachDetails) {
    const { affectedCount, breachDate, discoveryDate, phiTypes } = breachDetails;

    auditLogger.error({
        event: 'PHI_BREACH_DETECTED',
        ...breachDetails,
        timestamp: new Date().toISOString()
    });

    // 72시간 이내 통보 필요
    const notificationDeadline = new Date(discoveryDate);
    notificationDeadline.setHours(notificationDeadline.getHours() + 72);

    // 500명 이상 영향 시 HHS 즉시 보고 + 미디어 통보
    if (affectedCount >= 500) {
        console.log('CRITICAL: Major breach - HHS and media notification required');
        // await notifyHHS(breachDetails);
        // await notifyMedia(breachDetails);
    }

    // 영향받은 개인에게 통보
    // await notifyAffectedIndividuals(breachDetails);
}

module.exports = { HIPAAEncryption, HIPAAAccessControl, notifyBreach };
# HIPAA 준수 AWS 인프라 구성 - Terraform
# Security Rule 요구사항 충족을 위한 기술적 보호조치

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

# HIPAA 적격 서비스만 사용하는 VPC
resource "aws_vpc" "hipaa_vpc" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name        = "hipaa-compliant-vpc"
    Compliance  = "HIPAA"
    Environment = "production"
  }
}

# PHI 저장용 암호화된 S3 버킷
resource "aws_s3_bucket" "phi_storage" {
  bucket = "hipaa-phi-storage-${random_id.bucket_suffix.hex}"

  tags = {
    Name       = "PHI Storage"
    Compliance = "HIPAA"
    DataClass  = "PHI"
  }
}

# S3 버킷 암호화 (저장 시 암호화 - Security Rule)
resource "aws_s3_bucket_server_side_encryption_configuration" "phi_encryption" {
  bucket = aws_s3_bucket.phi_storage.id

  rule {
    apply_server_side_encryption_by_default {
      kms_master_key_id = aws_kms_key.phi_key.arn
      sse_algorithm     = "aws:kms"
    }
    bucket_key_enabled = true
  }
}

# S3 버킷 버전 관리 (무결성 보장)
resource "aws_s3_bucket_versioning" "phi_versioning" {
  bucket = aws_s3_bucket.phi_storage.id
  versioning_configuration {
    status = "Enabled"
  }
}

# S3 퍼블릭 액세스 차단
resource "aws_s3_bucket_public_access_block" "phi_public_access" {
  bucket = aws_s3_bucket.phi_storage.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# PHI 암호화용 KMS 키 (HIPAA 요구 AES-256)
resource "aws_kms_key" "phi_key" {
  description             = "KMS key for PHI encryption"
  deletion_window_in_days = 30
  enable_key_rotation     = true

  # 키 정책 - 최소 권한 원칙
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Sid    = "Enable IAM User Permissions"
        Effect = "Allow"
        Principal = {
          AWS = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"
        }
        Action   = "kms:*"
        Resource = "*"
      },
      {
        Sid    = "Allow PHI Access Role"
        Effect = "Allow"
        Principal = {
          AWS = aws_iam_role.phi_access_role.arn
        }
        Action = [
          "kms:Decrypt",
          "kms:GenerateDataKey"
        ]
        Resource = "*"
      }
    ]
  })

  tags = {
    Name       = "PHI Encryption Key"
    Compliance = "HIPAA"
  }
}

# PHI 데이터베이스 (RDS with 암호화)
resource "aws_db_instance" "phi_database" {
  identifier     = "hipaa-phi-db"
  engine         = "postgres"
  engine_version = "15.4"
  instance_class = "db.r6g.large"

  allocated_storage     = 100
  max_allocated_storage = 1000
  storage_type          = "gp3"
  storage_encrypted     = true  # 저장 시 암호화
  kms_key_id           = aws_kms_key.phi_key.arn

  db_name  = "phi_records"
  username = "phi_admin"
  password = var.db_password  # Secrets Manager 사용 권장

  # 네트워크 격리
  db_subnet_group_name   = aws_db_subnet_group.phi_subnet.name
  vpc_security_group_ids = [aws_security_group.phi_db_sg.id]
  publicly_accessible    = false

  # 백업 및 복구 (Security Rule)
  backup_retention_period = 35
  backup_window          = "03:00-04:00"
  maintenance_window     = "Mon:04:00-Mon:05:00"

  # 감사 로그 (CloudWatch로 전송)
  enabled_cloudwatch_logs_exports = ["postgresql", "upgrade"]

  # 삭제 보호
  deletion_protection = true
  skip_final_snapshot = false
  final_snapshot_identifier = "phi-db-final-snapshot"

  tags = {
    Name       = "PHI Database"
    Compliance = "HIPAA"
    DataClass  = "PHI"
  }
}

# CloudTrail (감사 로그 - Security Rule)
resource "aws_cloudtrail" "hipaa_trail" {
  name                          = "hipaa-audit-trail"
  s3_bucket_name               = aws_s3_bucket.audit_logs.id
  include_global_service_events = true
  is_multi_region_trail        = true
  enable_log_file_validation   = true
  kms_key_id                   = aws_kms_key.phi_key.arn

  event_selector {
    read_write_type           = "All"
    include_management_events = true

    data_resource {
      type   = "AWS::S3::Object"
      values = ["${aws_s3_bucket.phi_storage.arn}/"]
    }
  }

  tags = {
    Name       = "HIPAA Audit Trail"
    Compliance = "HIPAA"
  }
}

# 감사 로그 보존 (6년 - HIPAA 요구사항)
resource "aws_s3_bucket_lifecycle_configuration" "audit_retention" {
  bucket = aws_s3_bucket.audit_logs.id

  rule {
    id     = "hipaa-retention"
    status = "Enabled"

    transition {
      days          = 90
      storage_class = "GLACIER"
    }

    expiration {
      days = 2190  # 6년
    }
  }
}

output "phi_storage_bucket" {
  value       = aws_s3_bucket.phi_storage.bucket
  description = "HIPAA-compliant PHI storage bucket"
}

🗣️ Say It Like This in Practice

💬 In a Healthcare SaaS Architecture Meeting
"Because our service handles PHI, we qualify as a HIPAA Business Associate. We need to enter into a BAA with the hospital, and we need a signed BAA with AWS as well. Data must be encrypted with AES-256, and all PHI access must be retained in audit logs for 6 years. Also, in line with the Minimum Necessary principle, we need to restrict which PHI fields each role can access."
💬 In response to a security audit
"We've implemented all of the Security Rule's technical safeguards. We've applied encryption at rest (KMS), encryption in transit (TLS 1.3), unique user IDs, automatic logoff, and audit logs. For physical safeguards, we provide evidence with AWS's SOC 2 report. Administrative safeguards include annual HIPAA training, risk analysis, and a disaster recovery plan."
💬 In Responding to a Data Breach Incident
"We're acting under the Breach Notification Rule. Once a PHI breach is confirmed, we must notify affected patients within 72 hours. If 500 or more people are affected, we must report to HHS immediately and inform the media as well. Let's determine the scope of impact now and prepare the notification wording in consultation with the legal team. Audit logs let us trace who accessed which data."

⚠️ Cautions & Best Practices

❌
Transmitting/Storing PHI Without Encryption

Transmitting PHI via email, text messages, or unencrypted cloud storage is a HIPAA violation. Always use encrypted channels (TLS) and storage (AES-256). Incidents where PHI is exposed due to S3 bucket public-setting mistakes are frequent.

❌
Using Third-Party Services Without a BAA

You must enter into a BAA with every service that PHI passes through, such as AWS, Google Cloud, and Slack. If you use a service without a BAA, both the CE and the BA bear liability for the violation. In particular, most free versions and personal-use services do not support HIPAA.

❌
Inadequate Audit Logs

If it is impossible to trace who accessed which PHI and when, it is a Security Rule violation. Logs must be retained for at least 6 years. Without logs, it is impossible to determine the scope of impact in a breach incident or to mount a legal defense.

✅
HIPAA Compliance Best Practices

Implement PHI minimization (collect only the necessary data), role-based access control (RBAC), regular risk analysis (at least once a year), employee training (at hire + annually), incident response planning, and systematic BAA management. If possible, also consider HITRUST CSF certification.

🔗 Related Terms

📚 Learn More