Update documentation with current infrastructure state

- Update all resource IDs to match current deployment
- CloudFront Distribution: EATJ1HDQU8V51
- WAF Web ACL: d61073b6-27b1-473e-aa9f-d2aa4a4c75a6
- WAF IP Set: a9e47946-c186-4b28-83a8-fe3aeb9c296b
- ACM Certificate: b011e60a-1ea1-4dd3-844f-e0851ece4784
- Route53 Zone: Z01934581JQAF2GS71GG
- Reflect enabled ACM certificate and Route53 DNS management
- Update all AWS CLI commands with correct resource IDs

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
kappa
2025-09-09 15:32:35 +09:00
parent 3b66e6d29f
commit d5440630f5
3 changed files with 460 additions and 340 deletions

View File

@@ -1,241 +1,285 @@
# AWS CloudFront 배포 가이드
# AWS CloudFront + CrowdSec 배포 가이드
## 📋 프로젝트 개요
AWS CloudFront CDN을 OpenTofu(Terraform fork)로 구성하여 `origin.servidor.it.com`을 origin으로 사용하는 인프라스트럭처 프로젝트입니다.
## 📋 완전 배포 가이드
AWS CloudFront CDN과 CrowdSec 실시간 보안 통합 시스템의 단계별 배포 가이드입니다.
## 🏗️ 현재 인프라 상태
## 🎯 배포 목표
- CloudFront CDN 구성 (`origin.servidor.it.com`)
- CrowdSec 컨테이너 보안 시스템
- Lambda 기반 실시간 WAF 통합
- Nginx Proxy Manager 로그 분석
### CloudFront Distribution
- **Distribution ID**: E1XR8P4ENGP8RU
- **CloudFront URL**: https://dspki4yrh5oy1.cloudfront.net
- **Origin**: origin.servidor.it.com (HTTP-only)
- **Status**: ✅ Deployed and Working
## ⚠️ 중요 제약사항
- **Origin Protocol**: HTTP-only (HTTPS 사용 시 504 에러)
- **DynamoDB Locking**: 권한 제한으로 비활성화
### 보안 설정
- **WAF**: AWS WAF v2 활성화
- WAF ID: d21d84c1-edb9-40af-9cdd-27f42f09c499
- Rate Limiting: 10,000 requests/5min per IP
- AWS Managed Rules - Common Rule Set (SQL Injection, XSS 방어)
- AWS Managed Rules - Known Bad Inputs (악성 패턴 차단)
- **Viewer Protocol**: HTTPS (redirect-to-https)
- **Origin Protocol**: HTTP-only (중요: HTTPS 사용 시 504 에러)
## ✅ 현재 활성화된 기능
- **ACM Certificate**: 활성화됨 (b011e60a-1ea1-4dd3-844f-e0851ece4784)
- **Route53 Records**: 활성화됨 (Z01934581JQAF2GS71GG)
- **WAF Protection**: 활성화됨 (d61073b6-27b1-473e-aa9f-d2aa4a4c75a6)
### 로깅 및 상태 관리
- **CloudFront Logs**: `s3://aws-cf-cloudfront-logs-535294143817/cloudfront-logs/`
- **Terraform State**: `s3://aws-cf-terraform-state-535294143817/aws-cf/terraform.tfstate`
- **State Locking**: 비활성화 (DynamoDB 권한 없음)
## 🚀 배포 방법
## 🚀 1단계: 인프라 배포
### 사전 요구사항
- OpenTofu 또는 Terraform 설치
- AWS CLI 구성
- 필요한 IAM 권한:
- CloudFrontFullAccess
- S3FullAccess
- Route53FullAccess
- AWSCertificateManagerFullAccess
- AWSWAFFullAccess (WAFv2 포함)
- AWSCloudFormationFullAccess
- AWS CLI 설정 완료
- OpenTofu 설치 (`brew install opentofu`)
- Incus 설치 및 설정
### 초기 설정
### 인프라 배포
```bash
# S3 Backend 설정 (이미 완료됨)
./setup-backend.sh
# 프로젝트 디렉토리로 이동
cd /Users/kaffa/Projects/was-cf
# State 마이그레이션 (이미 완료됨)
echo "yes" | tofu init -migrate-state
```
### 배포 명령어
```bash
# 초기화
# OpenTofu 초기화
tofu init
# 계획 확인
tofu plan
# 배포 실행
# 인프라 배포
tofu apply -auto-approve
# 상태 확인
tofu state list
```
## 📁 프로젝트 구조
```
aws-cf/
├── main.tf # CloudFront 메인 구성
├── variables.tf # 변수 정의
├── terraform.tfvars # 변수 값 설정
├── outputs.tf # 출력 정의
├── versions.tf # Provider 버전 관리
├── backend.tf # S3 Backend 설정
├── security.tf # WAF 및 보안 그룹
├── acm.tf # ACM 인증서 (비활성화)
├── setup-backend.sh # S3 Backend 설정 스크립트
├── README.md # 기존 문서
└── DEPLOYMENT_GUIDE.md # 이 문서
### 배포 결과 확인
```bash
# 출력값 확인
tofu output
# CloudFront 상태 확인
aws cloudfront get-distribution --id EATJ1HDQU8V51 --query 'Distribution.Status'
# WAF 규칙 확인
aws wafv2 get-web-acl --scope CLOUDFRONT --id d61073b6-27b1-473e-aa9f-d2aa4a4c75a6 --region us-east-1
```
## ⚙️ 중요 설정 내용
## 🔒 2단계: CrowdSec 컨테이너 설정
### terraform.tfvars 핵심 설정
```hcl
# Origin 설정 (매우 중요)
origin_domain = "origin.servidor.it.com"
origin_protocol_policy = "http-only" # HTTPS 사용 시 504 에러!
# CloudFront 설정
viewer_protocol_policy = "redirect-to-https"
price_class = "PriceClass_100"
# 보안 설정
enable_waf = true
# 로깅 설정
enable_cloudfront_logging = true
cloudfront_logs_bucket = "aws-cf-cloudfront-logs-535294143817"
# 비활성화된 기능 (권한/제한 사항)
create_route53_records = false # CAA 제한으로 비활성화
create_acm_certificate = false # CloudFront 기본 인증서 사용
enable_cloudformation_stack = false # CloudFormation 권한 없음
### 컨테이너 생성
```bash
# 새 Ubuntu 컨테이너 생성
incus launch ubuntu:24.04 crowdsec
incus exec crowdsec -- apt update
```
## 🔧 문제 해결 히스토리
### CrowdSec 설치
```bash
# CrowdSec 설치
incus exec crowdsec -- curl -s https://install.crowdsec.net | sh
### 1. 504 Gateway Timeout 해결 ✅
**문제**: CloudFront가 origin 서버에 연결할 수 없음
**원인**: origin.servidor.it.com이 HTTP(80)만 지원하는데 HTTPS(443)로 연결 시도
**해결**:
```hcl
origin_protocol_policy = "http-only"
# 서비스 상태 확인
incus exec crowdsec -- systemctl status crowdsec
```
### 2. ACM 인증서 CAA 제한 ✅
**문제**: *.servidor.it.com 도메인에 대한 ACM 인증서 발급 실패
**원인**: CAA DNS 레코드가 AWS 인증서 발급을 제한
**해결**: CloudFront 기본 인증서 사용
```hcl
create_acm_certificate = false
viewer_certificate {
cloudfront_default_certificate = true
### 보안 컬렉션 설치
```bash
# Nginx Proxy Manager 컬렉션 설치
incus exec crowdsec -- cscli collections install crowdsecurity/nginx-proxy-manager
# 설치된 컬렉션 확인
incus exec crowdsec -- cscli collections list
# 설정 적용
incus exec crowdsec -- systemctl reload crowdsec
```
## 🔗 3단계: 웹훅 통합 설정
### 알림 설정 파일 생성
```bash
incus exec crowdsec -- tee /etc/crowdsec/notifications/aws-waf.yaml << 'EOF'
type: http
name: aws-waf
log_level: info
url: https://8zdmpjfnhh.execute-api.us-east-1.amazonaws.com/dev/webhook
method: POST
headers:
Content-Type: application/json
User-Agent: CrowdSec/1.7.0
timeout: 10s
format: |
{{ .|toJson }}
EOF
```
### 프로필 설정
```bash
incus exec crowdsec -- tee /etc/crowdsec/profiles.yaml << 'EOF'
name: aws_waf_profile
filters:
- Alert.Remediation == true && Alert.GetScenario() startsWith "crowdsecurity/"
notifications:
- aws-waf
on_success: break
EOF
```
### CrowdSec 재시작
```bash
incus exec crowdsec -- systemctl restart crowdsec
```
## 🧪 4단계: 통합 테스트
### 웹훅 엔드포인트 테스트
```bash
curl -X POST https://8zdmpjfnhh.execute-api.us-east-1.amazonaws.com/dev/webhook \
-H "Content-Type: application/json" \
-H "User-Agent: CrowdSec/1.7.0" \
-d '[{
"uuid": "test-123",
"decisions": [{
"value": "192.168.1.100",
"type": "ban",
"action": "add"
}]
}]'
```
**예상 응답:**
```json
{
"success": true,
"message": "WAF IP Set updated successfully",
"ips_added": ["192.168.1.100"],
"ips_removed": [],
"total_ips": 1
}
```
### 3. DynamoDB State Locking 권한 ✅
**문제**: Terraform state locking을 위한 DynamoDB 테이블 생성/접근 불가
**해결**: S3만 사용 (1인 개발 시 충분)
```hcl
backend "s3" {
bucket = "aws-cf-terraform-state-535294143817"
key = "aws-cf/terraform.tfstate"
# dynamodb_table = "terraform-state-lock" # 비활성화
}
```
### 4. 중복 CloudFront Distribution 정리 ✅
**문제**: 여러 배포 시도로 3개의 distribution 생성
**해결**:
- E18GW141CX7I8C - 비활성화 중 (삭제 예정)
- E32FD742KMW2YY - 비활성화 중 (삭제 예정)
- E1XR8P4ENGP8RU - 현재 사용 중 ✅
### 5. WAF 권한 문제 ✅
**초기 문제**: WAFv2 권한 없다고 오류 발생
**해결**: AWSWAFFullAccess 정책에 wafv2:* 권한 포함되어 있음 확인
## 📊 모니터링 및 관리
### 상태 확인 명령어
### WAF IP Set 확인
```bash
# CloudFront 상태
aws cloudfront get-distribution --id E1XR8P4ENGP8RU \
--query 'Distribution.Status' --output text
# WAF 연결 확인
aws cloudfront get-distribution --id E1XR8P4ENGP8RU \
--query 'Distribution.DistributionConfig.WebACLId' --output text
# 로그 확인
aws s3 ls s3://aws-cf-cloudfront-logs-535294143817/cloudfront-logs/ --recursive
# State 파일 확인
aws s3 ls s3://aws-cf-terraform-state-535294143817/aws-cf/
aws wafv2 get-ip-set --scope CLOUDFRONT --region us-east-1 \
--id a9e47946-c186-4b28-83a8-fe3aeb9c296b \
--name aws-cf-dev-blocked-ips \
--query 'IPSet.Addresses'
```
### 성능 테스트
### IP 제거 테스트
```bash
# CloudFront 응답 확인
curl -I https://dspki4yrh5oy1.cloudfront.net
# 출력 예시:
# HTTP/2 200
# content-type: text/html
# x-cache: Miss from cloudfront (첫 요청) / Hit from cloudfront (캐시된 요청)
curl -X POST https://8zdmpjfnhh.execute-api.us-east-1.amazonaws.com/dev/webhook \
-H "Content-Type: application/json" \
-H "User-Agent: CrowdSec/1.7.0" \
-d '[{
"uuid": "test-456",
"decisions": [{
"value": "192.168.1.100",
"type": "ban",
"action": "delete"
}]
}]'
```
### 비활성화된 Distribution 삭제 (완전 비활성화 후)
### CrowdSec 알림 테스트
```bash
# 상태 확인
aws cloudfront list-distributions \
--query 'DistributionList.Items[*].[Id,Status,DistributionConfig.Enabled]' \
--output table
# 삭제 (Deployed 상태에서 Enabled=false 일 때)
aws cloudfront get-distribution-config --id E18GW141CX7I8C > dist-config.json
ETAG=$(jq -r '.ETag' dist-config.json)
aws cloudfront delete-distribution --id E18GW141CX7I8C --if-match $ETAG
incus exec crowdsec -- cscli notifications test aws-waf
```
## 🔒 보안 고려사항
## 📊 5단계: 모니터링 설정
1. **WAF 설정**
- 현재 기본 AWS Managed Rules 사용
- 필요시 커스텀 룰 추가 가능
- Rate limiting 조정 가능 (security.tf)
### Lambda 함수 로그 모니터링
```bash
# 실시간 로그 확인
aws logs tail /aws/lambda/aws-cf-dev-crowdsec-waf-updater --follow
2. **Origin 보안**
- ⚠️ Origin이 HTTP만 지원하므로 CloudFront-Origin 간 트래픽 암호화 안됨
- 권장: Origin 서버에 HTTPS 지원 추가
# 특정 시간대 로그
aws logs filter-log-events \
--log-group-name /aws/lambda/aws-cf-dev-crowdsec-waf-updater \
--start-time $(date -d '1 hour ago' +%s)000
```
3. **로그 관리**
- CloudFront 로그 90일 자동 삭제 설정
- 장기 보관 필요시 S3 lifecycle 수정
### CrowdSec 상태 모니터링
```bash
# 메트릭 확인
incus exec crowdsec -- cscli metrics
## 📝 향후 개선 사항
# 현재 차단 결정
incus exec crowdsec -- cscli decisions list
### 권한 획득 시 활성화 가능한 기능
1. **DynamoDB State Locking**
- 팀 협업 시 필수
- backend.tf에서 주석 해제
# 허브 상태
incus exec crowdsec -- cscli hub list
```
2. **Custom Domain with ACM**
- CAA 레코드 수정 후 가능
- terraform.tfvars에서 `create_acm_certificate = true`
### WAF 메트릭 확인
```bash
# 차단된 요청 확인
aws cloudwatch get-metric-statistics \
--namespace AWS/WAFV2 \
--metric-name BlockedRequests \
--dimensions Name=WebACL,Value=aws-cf-dev-waf Name=Rule,Value=BlockedIPsRule \
--start-time $(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%S) \
--end-time $(date -u +%Y-%m-%dT%H:%M:%S) \
--period 300 --statistics Sum
```
3. **CloudFormation Stack**
- VPC 및 네트워킹 리소스 관리
- terraform.tfvars에서 `enable_cloudformation_stack = true`
## 🔧 문제 해결
### 성능 최적화
1. Cache Policy 최적화
2. Origin Request Policy 조정
3. CloudFront Edge Location 선택 (Price Class)
### 일반적인 문제들
## 🏷️ 태그 및 메타데이터
- **Project**: aws-cf
- **Environment**: dev
- **ManagedBy**: OpenTofu
- **Owner**: kaffa
- **Created**: 2025-09-08
- **LastUpdated**: 2025-09-09
**1. 웹훅 연결 실패**
```bash
# 네트워크 연결 확인
incus exec crowdsec -- curl -I https://8zdmpjfnhh.execute-api.us-east-1.amazonaws.com/dev/webhook
## 📚 참고 자료
- [OpenTofu Documentation](https://opentofu.org/docs/)
- [AWS CloudFront Best Practices](https://docs.aws.amazon.com/cloudfront/latest/developerguide/best-practices.html)
- [AWS WAF Documentation](https://docs.aws.amazon.com/waf/latest/developerguide/)
# CrowdSec 알림 설정 확인
incus exec crowdsec -- cat /etc/crowdsec/notifications/aws-waf.yaml
```
**2. Lambda 함수 오류**
```bash
# Lambda 함수 직접 테스트
aws lambda invoke --function-name aws-cf-dev-crowdsec-waf-updater response.json
# 에러 로그 확인
aws logs describe-log-groups --log-group-name-prefix "/aws/lambda/aws-cf-dev"
```
**3. WAF 업데이트 실패**
```bash
# IAM 권한 확인
aws iam get-role-policy --role-name aws-cf-dev-lambda-waf-role --policy-name aws-cf-dev-lambda-waf-policy
# WAF IP Set 상태 확인
aws wafv2 get-ip-set --scope CLOUDFRONT --region us-east-1 --id a9e47946-c186-4b28-83a8-fe3aeb9c296b --name aws-cf-dev-blocked-ips
```
## 📈 운영 관리
### 정기 유지보수
```bash
# CrowdSec 업데이트
incus exec crowdsec -- cscli hub update
incus exec crowdsec -- cscli hub upgrade
# 컬렉션 상태 확인
incus exec crowdsec -- cscli collections list
# 시스템 리소스 확인
incus info crowdsec
```
### 백업 및 복구
```bash
# CrowdSec 설정 백업
incus exec crowdsec -- tar -czf /tmp/crowdsec-config.tar.gz /etc/crowdsec
# 설정 파일 복사
incus file pull crowdsec/tmp/crowdsec-config.tar.gz ./
# Terraform 상태 백업
aws s3 sync s3://aws-cf-terraform-state-535294143817 ./backup/
```
## 🎯 완료 체크리스트
- [ ] AWS 인프라 배포 완료
- [ ] CrowdSec 컨테이너 설정 완료
- [ ] 웹훅 통합 설정 완료
- [ ] 통합 테스트 성공
- [ ] 모니터링 설정 완료
- [ ] 문서화 완료
---
*이 문서는 실제 배포 경험을 바탕으로 작성되었습니다.*
**배포 완료 시간**: 약 30-45분
**필수 권한**: AWS WAF, Lambda, API Gateway, CloudWatch 접근
**지원**: [CrowdSec Integration Guide](CROWDSEC-WAF-INTEGRATION.md) 참조