Complete infrastructure and integration updates

Infrastructure improvements:
- Update CloudFront distribution with ACM certificate support
- Enable custom domain aliases when certificate is available
- Add comprehensive WAF outputs for CrowdSec integration
- Update variables with current configuration defaults

New files:
- Add CrowdSec WAF integration documentation
- Add sync script for CrowdSec to WAF automation
- Add MCP configuration for development tools

Configuration updates:
- Align Terraform configuration with deployed state
- Enable ACM certificate and Route53 DNS by default
- Maintain HTTP-only origin protocol for compatibility

🤖 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:33:36 +09:00
parent d5440630f5
commit b87947e3e3
7 changed files with 515 additions and 10 deletions

309
CROWDSEC-WAF-INTEGRATION.md Normal file
View File

@@ -0,0 +1,309 @@
# CrowdSec - AWS WAF 실시간 통합 가이드
## 📋 개요
이 문서는 CrowdSec와 AWS WAF 간의 실시간 IP 차단 통합 시스템 구현 가이드입니다. CrowdSec가 탐지한 악성 IP를 AWS Lambda를 통해 자동으로 WAF IP Set에 추가/제거하여 실시간 보안을 제공합니다.
## 🏗️ 아키텍처
```
CrowdSec Container → Webhook Notification → API Gateway → Lambda Function → AWS WAF IP Set → CloudFront Distribution
```
### 주요 구성 요소
1. **CrowdSec Container** (Incus)
- 보안 이벤트 감지 및 분석
- Nginx Proxy Manager 로그 모니터링
- 웹훅 알림 전송
2. **AWS API Gateway**
- 웹훅 엔드포인트 제공
- Lambda 함수 트리거
3. **AWS Lambda Function**
- CrowdSec Alert 데이터 처리
- WAF IP Set 업데이트 수행
4. **AWS WAF v2**
- IP Set 기반 차단 규칙
- CloudFront 배포 보호
## 🚀 구현 단계
### 1. 인프라 배포
```bash
# OpenTofu 초기화
tofu init
# 인프라 배포
tofu apply -auto-approve
```
**배포되는 리소스:**
- Lambda 함수 및 IAM 역할
- API Gateway 웹훅 엔드포인트
- WAF v2 IP Set 및 Web ACL
- CloudWatch 로그 그룹
### 2. CrowdSec 컨테이너 설정
#### 컨테이너 생성 및 설정
```bash
# 새 컨테이너 생성
incus launch ubuntu:24.04 crowdsec
# CrowdSec 설치
incus exec crowdsec -- apt update
incus exec crowdsec -- curl -s https://install.crowdsec.net | sh
# Nginx Proxy Manager 컬렉션 설치
incus exec crowdsec -- cscli collections install crowdsecurity/nginx-proxy-manager
incus exec crowdsec -- systemctl reload crowdsec
```
#### 웹훅 알림 설정
```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
# 프로필 설정
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 재시작
incus exec crowdsec -- systemctl restart crowdsec
```
### 3. Lambda 함수 코드
**파일 위치:** `/Users/kaffa/Projects/was-cf/lambda-crowdsec-waf.py`
주요 기능:
- CrowdSec Alert JSON 구조 처리
- IP 주소 추출 및 검증
- WAF IP Set 업데이트 (추가/제거)
- 에러 처리 및 로깅
핵심 처리 로직:
```python
# CrowdSec Alert 구조 처리 (toJson 형식)
if isinstance(webhook_data, list):
# Alert 배열인 경우
for alert in webhook_data:
if 'decisions' in alert and alert['decisions']:
for decision in alert['decisions']:
# Source IP 추출
source_ip = alert.get('source', {}).get('ip', '')
# Decision 정보 포함
decision['source_ip'] = source_ip
decision['alert_uuid'] = alert.get('uuid', '')
decisions.append(decision)
```
## 📊 WAF 규칙 우선순위
AWS WAF Web ACL 규칙 순서 (낮은 번호가 높은 우선순위):
1. **Priority 1: BlockedIPsRule** ← CrowdSec IP 차단 (최고 우선순위) - `aws-cf-dev-blocked-ips` IP Set 사용
2. **Priority 2: RateLimitRule** ← 일반 레이트 제한 (10,000 req/5min) - 전체 IP 대상
3. **Priority 3: AWSManagedRulesCommonRuleSet** ← AWS 관리형 공통 규칙
4. **Priority 4: AWSManagedRulesKnownBadInputsRuleSet** ← AWS 관리형 악성 입력 규칙
**⚠️ 참고:** 이전에 있던 `suspicious_ips` IP Set과 `SuspiciousIPsRateLimit` 규칙은 현재 Lambda 기반 실시간 통합으로 대체되어 제거되었습니다.
## 🧪 테스트 및 검증
### 1. 웹훅 엔드포인트 테스트
```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-uuid-123",
"machine_id": "test-machine",
"created_at": "2025-09-09T02:50:00Z",
"scenario": "test/security-scan",
"source": {"ip": "192.168.1.100"},
"decisions": [{
"value": "192.168.1.100",
"type": "ban",
"action": "add",
"scope": "ip"
}]
}]'
```
**예상 응답:**
```json
{
"success": true,
"message": "WAF IP Set updated successfully",
"ips_added": ["192.168.1.100"],
"ips_removed": [],
"total_ips": 1
}
```
### 2. WAF IP Set 확인
```bash
# IP Set 내용 조회
aws wafv2 get-ip-set \
--scope CLOUDFRONT \
--id c43ff364-f3e2-43c7-8462-8fae20599d8d \
--name aws-cf-dev-blocked-ips \
--region us-east-1 \
--query 'IPSet.Addresses'
```
### 3. CrowdSec 알림 테스트
```bash
# CrowdSec 알림 테스트
incus exec crowdsec -- cscli notifications test aws-waf
```
## 📈 설치된 보안 컬렉션
### Nginx Proxy Manager 컬렉션
- **컬렉션:** `crowdsecurity/nginx-proxy-manager`
- **파서:** `crowdsecurity/nginx-proxy-manager-logs`
- **HTTP 로그:** `crowdsecurity/http-logs`
### 주요 보안 시나리오 (40+ 개)
- **Web 공격:** XSS, SQLi, Path Traversal 프로빙
- **CVE 취약점:** Log4j, Spring4Shell, Apache 등
- **관리자 인터페이스:** 무차별 대입 공격 감지
- **백도어 시도:** 악성 스크립트 업로드 감지
- **WordPress:** 스캔 및 무차별 대입 공격
- **네트워크:** 오픈 프록시, 크롤링 감지
## 🔧 리소스 정보
### AWS 리소스
```bash
# CloudFront Distribution ID
E1XR8P4ENGP8RU
# WAF Web ACL ID
d21d84c1-edb9-40af-9cdd-27f42f09c499
# WAF IP Set ID
c43ff364-f3e2-43c7-8462-8fae20599d8d
# Lambda Function
aws-cf-dev-crowdsec-waf-updater
# Webhook URL
https://8zdmpjfnhh.execute-api.us-east-1.amazonaws.com/dev/webhook
```
### Terraform 출력값
```bash
tofu output
```
## 🔍 모니터링 및 로그
### Lambda 함수 로그
```bash
# CloudWatch 로그 확인
aws logs tail /aws/lambda/aws-cf-dev-crowdsec-waf-updater --follow
```
### CrowdSec 로그
```bash
# CrowdSec 서비스 로그
incus exec crowdsec -- journalctl -u crowdsec -f
# 차단 결정 목록
incus exec crowdsec -- cscli decisions list
```
### WAF 메트릭
- CloudWatch에서 WAF 차단 메트릭 확인
- `BlockedIPsRule` 메트릭 모니터링
## 🛠️ 문제 해결
### 일반적인 문제
1. **웹훅 연결 실패**
- 네트워크 연결 확인
- API Gateway URL 유효성 검사
- CrowdSec 알림 설정 재검토
2. **Lambda 함수 오류**
- CloudWatch 로그 확인
- IAM 권한 검증
- WAF IP Set 접근 권한 확인
3. **IP가 차단되지 않음**
- WAF 규칙 우선순위 확인
- CloudFront 배포와 WAF 연결 상태
- IP Set 업데이트 상태 확인
### 디버깅 명령어
```bash
# CrowdSec 상태 확인
incus exec crowdsec -- cscli metrics
# 알림 플러그인 상태
incus exec crowdsec -- cscli notifications list
# Lambda 함수 테스트
aws lambda invoke --function-name aws-cf-dev-crowdsec-waf-updater response.json
# WAF 규칙 확인
aws wafv2 get-web-acl --scope CLOUDFRONT --id d21d84c1-edb9-40af-9cdd-27f42f09c499 --name aws-cf-dev-waf --region us-east-1
```
## 🚀 확장 가능성
1. **다중 환경 지원**
- 개발/스테이징/프로덕션 환경별 WAF 연결
- 환경별 IP Set 분리
2. **고급 알림**
- Slack/Discord 통합
- 이메일 알림 추가
- 대시보드 연동
3. **IP 화이트리스트**
- 신뢰할 수 있는 IP 자동 제외
- 지역별 IP 필터링
4. **자동 해제**
- 시간 기반 자동 차단 해제
- 위험도 기반 차단 기간 조정
## 📝 참고 자료
- [CrowdSec Documentation](https://docs.crowdsec.net/)
- [AWS WAF Developer Guide](https://docs.aws.amazon.com/waf/)
- [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/)
- [CrowdSec Hub](https://hub.crowdsec.net/)
---
**구현 완료일:** 2025-09-09
**마지막 업데이트:** 2025-09-09
**작성자:** Claude Code SuperClaude Framework