🔒 Security

CSPM

Cloud Security Posture Management

A cloud security posture management solution. Continuously monitors multi-cloud environments for misconfigurations, compliance violations, and security vulnerabilities, and remediates them automatically.

📖 Detailed Explanation

CSPM (Cloud Security Posture Management) is a solution that continuously assesses and manages the security posture of cloud infrastructure. The most frequent cause of security incidents in cloud environments is not hacking but misconfiguration. Mistakes such as publicly exposed S3 buckets, overly open security groups, and excessive IAM permissions lead to data breaches. CSPM automatically detects these misconfigurations and provides alerts.

The core function of CSPM is compliance checking. It automatically assesses whether cloud resources are configured in line with security standards such as CIS Benchmarks, SOC 2, HIPAA, PCI-DSS, and GDPR. When violations are found, it provides detailed remediation guidance, and some solutions also support auto-remediation. AWS Config Rules, Azure Policy, and GCP Security Command Center provide native CSPM capabilities.

In multi-cloud environments, CSPM provides unified visibility. As companies use a mix of AWS, Azure, and GCP, it has become difficult to manage the security settings of each cloud individually. Third-party CSPM tools such as Prisma Cloud, Wiz, and Lacework manage multi-cloud from a single dashboard and apply consistent security policies across clouds. They also provide features that visualize attack paths through graph-based analysis.

Integrating IaC (Infrastructure as Code) with CSPM is a trend. A Shift-Left approach, which scans Terraform and CloudFormation templates before deployment to detect security issues in advance, is spreading. Integrating tools such as Checkov and tfsec into the CI/CD pipeline can block misconfigurations at the deployment stage. The concept of CNAPP (Cloud Native Application Protection Platform), which integrates CSPM + CWPP + CIEM, has also emerged.

💻 Code Example

# CSPM - Terraform 보안 스캔 (Checkov)
# 배포 전 IaC 템플릿 보안 검사

# 취약한 S3 버킷 설정 (CSPM이 탐지할 문제)
resource "aws_s3_bucket" "data" {
  bucket = "company-data-bucket"
}

# ❌ Checkov 경고: CKV_AWS_18 - S3 bucket access logging disabled
# ❌ Checkov 경고: CKV_AWS_19 - S3 bucket encryption disabled
# ❌ Checkov 경고: CKV_AWS_21 - S3 bucket versioning disabled

# 보안 강화된 S3 버킷 설정
resource "aws_s3_bucket" "secure_data" {
  bucket = "company-secure-data"
}

resource "aws_s3_bucket_versioning" "secure_data" {
  bucket = aws_s3_bucket.secure_data.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "secure_data" {
  bucket = aws_s3_bucket.secure_data.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = aws_kms_key.s3_key.arn
    }
  }
}

resource "aws_s3_bucket_public_access_block" "secure_data" {
  bucket = aws_s3_bucket.secure_data.id

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

resource "aws_s3_bucket_logging" "secure_data" {
  bucket = aws_s3_bucket.secure_data.id

  target_bucket = aws_s3_bucket.logs.id
  target_prefix = "s3-access-logs/"
}

# CI/CD 파이프라인에서 Checkov 실행
# checkov -d . --framework terraform --output cli --compact
# checkov -d . --check CKV_AWS_18,CKV_AWS_19,CKV_AWS_21
# AWS Config Rules - 네이티브 CSPM 규칙
# CloudFormation 템플릿

AWSTemplateFormatVersion: '2010-09-09'
Description: CSPM - AWS Config Rules for Security Compliance

Resources:
  # S3 버킷 암호화 필수 규칙
  S3BucketSSLRequestsOnly:
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: s3-bucket-ssl-requests-only
      Description: S3 버킷이 SSL/TLS 요청만 허용하는지 확인
      Source:
        Owner: AWS
        SourceIdentifier: S3_BUCKET_SSL_REQUESTS_ONLY
      MaximumExecutionFrequency: TwentyFour_Hours

  # S3 퍼블릭 액세스 차단 규칙
  S3BucketPublicReadProhibited:
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: s3-bucket-public-read-prohibited
      Description: S3 버킷 퍼블릭 읽기 금지 확인
      Source:
        Owner: AWS
        SourceIdentifier: S3_BUCKET_PUBLIC_READ_PROHIBITED

  # EC2 인스턴스에 IMDSv2 강제
  EC2IMDSv2Check:
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: ec2-imdsv2-check
      Description: EC2 인스턴스가 IMDSv2를 사용하는지 확인
      Source:
        Owner: AWS
        SourceIdentifier: EC2_IMDSV2_CHECK

  # RDS 암호화 확인
  RDSStorageEncrypted:
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: rds-storage-encrypted
      Description: RDS 인스턴스 스토리지 암호화 확인
      Source:
        Owner: AWS
        SourceIdentifier: RDS_STORAGE_ENCRYPTED

  # 자동 교정 - SSM Automation
  S3RemediationConfiguration:
    Type: AWS::Config::RemediationConfiguration
    Properties:
      ConfigRuleName: !Ref S3BucketPublicReadProhibited
      TargetType: SSM_DOCUMENT
      TargetId: AWS-DisableS3BucketPublicReadWrite
      Automatic: true
      MaximumAutomaticAttempts: 3
      RetryAttemptSeconds: 60
      Parameters:
        S3BucketName:
          ResourceValue:
            Value: RESOURCE_ID
        AutomationAssumeRole:
          StaticValue:
            Values:
              - !GetAtt RemediationRole.Arn

  # 규정 준수 팩 - CIS AWS Foundations
  CISConformancePack:
    Type: AWS::Config::ConformancePack
    Properties:
      ConformancePackName: cis-aws-foundations-benchmark
      TemplateS3Uri: s3://config-conformance-packs/cis-aws-foundations.yaml
# CSPM 자동화 - Python으로 보안 태세 평가
import boto3
from datetime import datetime
import json

class CSPMScanner:
    """클라우드 보안 태세 자동 스캐너"""

    def __init__(self):
        self.s3 = boto3.client('s3')
        self.ec2 = boto3.client('ec2')
        self.iam = boto3.client('iam')
        self.findings = []

    def scan_s3_buckets(self):
        """S3 버킷 보안 설정 검사"""
        buckets = self.s3.list_buckets()['Buckets']

        for bucket in buckets:
            bucket_name = bucket['Name']

            # 퍼블릭 액세스 차단 확인
            try:
                public_access = self.s3.get_public_access_block(Bucket=bucket_name)
                config = public_access['PublicAccessBlockConfiguration']

                if not all([
                    config.get('BlockPublicAcls'),
                    config.get('BlockPublicPolicy'),
                    config.get('IgnorePublicAcls'),
                    config.get('RestrictPublicBuckets')
                ]):
                    self.findings.append({
                        'severity': 'HIGH',
                        'resource': f's3://{bucket_name}',
                        'rule': 'S3_PUBLIC_ACCESS_BLOCK',
                        'message': '퍼블릭 액세스 차단이 완전히 활성화되지 않음'
                    })
            except self.s3.exceptions.NoSuchPublicAccessBlockConfiguration:
                self.findings.append({
                    'severity': 'CRITICAL',
                    'resource': f's3://{bucket_name}',
                    'rule': 'S3_NO_PUBLIC_ACCESS_BLOCK',
                    'message': '퍼블릭 액세스 차단 설정이 없음'
                })

            # 암호화 확인
            try:
                encryption = self.s3.get_bucket_encryption(Bucket=bucket_name)
            except:
                self.findings.append({
                    'severity': 'HIGH',
                    'resource': f's3://{bucket_name}',
                    'rule': 'S3_ENCRYPTION_DISABLED',
                    'message': '서버 사이드 암호화가 비활성화됨'
                })

    def scan_security_groups(self):
        """보안 그룹 과도한 개방 검사"""
        sgs = self.ec2.describe_security_groups()['SecurityGroups']

        for sg in sgs:
            for rule in sg.get('IpPermissions', []):
                for ip_range in rule.get('IpRanges', []):
                    if ip_range.get('CidrIp') == '0.0.0.0/0':
                        port = rule.get('FromPort', 'All')
                        if port in [22, 3389, 3306, 5432]:  # 민감한 포트
                            self.findings.append({
                                'severity': 'CRITICAL',
                                'resource': f'sg:{sg["GroupId"]}',
                                'rule': 'SG_SENSITIVE_PORT_OPEN',
                                'message': f'민감한 포트 {port}가 인터넷에 개방됨'
                            })

    def scan_iam_policies(self):
        """IAM 과다 권한 검사"""
        users = self.iam.list_users()['Users']

        for user in users:
            policies = self.iam.list_attached_user_policies(UserName=user['UserName'])

            for policy in policies['AttachedPolicies']:
                if policy['PolicyArn'].endswith('/AdministratorAccess'):
                    self.findings.append({
                        'severity': 'HIGH',
                        'resource': f'iam:user/{user["UserName"]}',
                        'rule': 'IAM_ADMIN_ACCESS',
                        'message': 'IAM 사용자에게 AdministratorAccess 직접 부여됨'
                    })

    def generate_report(self):
        """CSPM 보고서 생성"""
        report = {
            'scan_time': datetime.now().isoformat(),
            'total_findings': len(self.findings),
            'by_severity': {
                'CRITICAL': len([f for f in self.findings if f['severity'] == 'CRITICAL']),
                'HIGH': len([f for f in self.findings if f['severity'] == 'HIGH']),
                'MEDIUM': len([f for f in self.findings if f['severity'] == 'MEDIUM'])
            },
            'findings': self.findings
        }
        return report

# 실행
scanner = CSPMScanner()
scanner.scan_s3_buckets()
scanner.scan_security_groups()
scanner.scan_iam_policies()
report = scanner.generate_report()
print(json.dumps(report, indent=2))

🗣️ Say It Like This in Practice

💬 In a Cloud Security Audit Preparation Meeting
"Before the SOC 2 audit, let's check the CSPM scan results first. There are currently 15 Critical findings, and 3 publicly exposed S3 buckets are the most urgent. Set up auto-remediation with AWS Config Rules, and document exceptions for the ones that can't be remediated."
💬 In a Multi-Cloud Security Strategy Discussion
"If we use native CSPM for each of AWS, Azure, and GCP, we end up with three dashboards. Let's adopt an integrated CSPM like Wiz or Prisma Cloud to manage our security posture in a single view and apply consistent CIS Benchmark policies across clouds."
💬 In DevSecOps Pipeline Design
"I've set up GitHub Actions so that a Checkov scan runs automatically when a Terraform PR is opened. If a Critical finding is detected, the merge is blocked, and High findings only show a warning. This is a Shift-Left approach that checks IaC with CSPM before deployment."

⚠️ Cautions & Best Practices

❌
Neglecting Alert Fatigue

When CSPM generates hundreds of alerts, the team starts ignoring them. Use priority-based filtering to respond immediately only to Critical/High findings, and handle the rest in a weekly review. Tune or add exceptions for noisy rules.

❌
Applying Auto-Remediation Indiscriminately

Applying CSPM auto-remediation directly to production can cause service outages. Operate in alert-only mode first, and after validating the remediation logic and testing it in staging, apply it to production.

❌
Relying Only on Runtime Without IaC Scanning

Runtime CSPM alone detects issues only after deployment. Scan Terraform and CloudFormation templates in advance with Checkov and tfsec at the CI/CD stage so that misconfigurations are never deployed in the first place.

✅
CSPM Best Practices

Adopt CIS Benchmarks as the baseline policy, and add custom rules to fit your organization's characteristics. Integrate CSPM findings with your SIEM to unify them with security incident response, and report a monthly security posture report to executive management.

🔗 Related Terms

📚 Learn More