您当前的位置:首页 > 学海无涯 > 信息安全网站首页信息安全
IS027001下基于AWS部署RockyOS的Terraform配置
发布时间:2025-11-04作者:♂逸風★淩軒
main.tf - 主配置文件,包含所有 AWS 资源定义
variables.tf - 变量定义文件
outputs.tf - 输出定义文件
versions.tf - Terraform 和 Provider 版本约束
user-data.sh - EC2 实例初始化脚本(安全加固)
terraform.tfvars.example - 变量配置示例
README.md - 完整使用文档
.gitignore - Git 忽略规则
加密: KMS 加密 EBS 卷、CloudWatch 日志、SNS 主题
网络隔离: VPC + 公有/私有子网架构,NAT Gateway
访问控制: 安全组、IAM 角色、SSH 加固、fail2ban
审计日志: auditd 全面审计规则、VPC Flow Logs、CloudWatch 日志
监控告警: CPU/磁盘告警、SNS 邮件通知
备份恢复: AWS Backup 每日备份,保留 30 天
漏洞管理: 自动安全更新、SSM 补丁管理
文件完整性: AIDE 监控系统文件变更
✅ SELinux Enforcing 模式
✅ 防火墙 (firewalld) 仅开放必要端口
✅ 强密码策略(14位+复杂度)
✅ SSH 禁用 root 登录和密码认证
✅ 账户锁定策略(5次失败锁定30分钟)
✅ 时钟同步 (chrony)
✅ 日志轮转(90天保留)
✅ IMDSv2 强制使用
A.9 访问控制 ✓
A.10 密码学 ✓
A.12 运营安全 ✓
A.13 通信安全 ✓
A.16 事件管理 ✓
📁 创建的文件
🔐 ISO27001 合规性
核心安全控制
安全加固措施
📊 预估成本
约 $145/月(基于 2 个 t3.medium 实例 + 网络 + 监控备份)
🎯 ISO27001 控制措施映射
🚀 快速开始
cd d:\code\python\52aiops\terraform\aws-rockyos-iso27001 # 1. 复制并配置变量 cp terraform.tfvars.example terraform.tfvars # 编辑 terraform.tfvars,设置 key_pair_name 和其他参数 # 2. 初始化 Terraform terraform init # 3. 查看执行计划 terraform plan # 4. 应用配置 terraform apply
main.tf
# ISO27001 Compliant Rocky Linux on AWS Infrastructure
# 满足ISO27001信息安全标准的Rocky Linux AWS基础设施
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
default_tags {
tags = {
Environment = var.environment
Project = var.project_name
ManagedBy = "Terraform"
Compliance = "ISO27001"
Owner = var.owner
}
}
}
# Data source for Rocky Linux AMI
data "aws_ami" "rocky_linux" {
most_recent = true
owners = ["792107900819"] # Rocky Linux official account
filter {
name = "name"
values = ["Rocky-9-EC2-Base-*.x86_64"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
filter {
name = "root-device-type"
values = ["ebs"]
}
}
# KMS Key for encryption (ISO27001: A.10.1.1 加密控制)
resource "aws_kms_key" "main" {
description = "KMS key for ${var.project_name} encryption"
deletion_window_in_days = 30
enable_key_rotation = true
tags = {
Name = "${var.project_name}-kms-key"
}
}
resource "aws_kms_alias" "main" {
name = "alias/${var.project_name}-key"
target_key_id = aws_kms_key.main.key_id
}
# VPC with private and public subnets (ISO27001: A.13.1 网络安全管理)
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = true
enable_dns_support = true
tags = {
Name = "${var.project_name}-vpc"
}
}
# Internet Gateway
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
tags = {
Name = "${var.project_name}-igw"
}
}
# Public Subnet
resource "aws_subnet" "public" {
count = length(var.availability_zones)
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index)
availability_zone = var.availability_zones[count.index]
tags = {
Name = "${var.project_name}-public-subnet-${count.index + 1}"
Type = "Public"
}
}
# Private Subnet
resource "aws_subnet" "private" {
count = length(var.availability_zones)
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index + 100)
availability_zone = var.availability_zones[count.index]
tags = {
Name = "${var.project_name}-private-subnet-${count.index + 1}"
Type = "Private"
}
}
# Elastic IP for NAT Gateway
resource "aws_eip" "nat" {
count = length(var.availability_zones)
domain = "vpc"
tags = {
Name = "${var.project_name}-nat-eip-${count.index + 1}"
}
depends_on = [aws_internet_gateway.main]
}
# NAT Gateway
resource "aws_nat_gateway" "main" {
count = length(var.availability_zones)
allocation_id = aws_eip.nat[count.index].id
subnet_id = aws_subnet.public[count.index].id
tags = {
Name = "${var.project_name}-nat-${count.index + 1}"
}
depends_on = [aws_internet_gateway.main]
}
# Route Table for Public Subnet
resource "aws_route_table" "public" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
tags = {
Name = "${var.project_name}-public-rt"
}
}
# Route Table for Private Subnet
resource "aws_route_table" "private" {
count = length(var.availability_zones)
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.main[count.index].id
}
tags = {
Name = "${var.project_name}-private-rt-${count.index + 1}"
}
}
# Route Table Association
resource "aws_route_table_association" "public" {
count = length(var.availability_zones)
subnet_id = aws_subnet.public[count.index].id
route_table_id = aws_route_table.public.id
}
resource "aws_route_table_association" "private" {
count = length(var.availability_zones)
subnet_id = aws_subnet.private[count.index].id
route_table_id = aws_route_table.private[count.index].id
}
# VPC Flow Logs (ISO27001: A.12.4 日志记录和监控)
resource "aws_flow_log" "main" {
iam_role_arn = aws_iam_role.flow_logs.arn
log_destination = aws_cloudwatch_log_group.flow_logs.arn
traffic_type = "ALL"
vpc_id = aws_vpc.main.id
tags = {
Name = "${var.project_name}-vpc-flow-logs"
}
}
resource "aws_cloudwatch_log_group" "flow_logs" {
name = "/aws/vpc/${var.project_name}-flow-logs"
retention_in_days = 90
kms_key_id = aws_kms_key.main.arn
tags = {
Name = "${var.project_name}-flow-logs"
}
}
resource "aws_iam_role" "flow_logs" {
name = "${var.project_name}-vpc-flow-logs-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "vpc-flow-logs.amazonaws.com"
}
}
]
})
}
resource "aws_iam_role_policy" "flow_logs" {
name = "${var.project_name}-vpc-flow-logs-policy"
role = aws_iam_role.flow_logs.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogGroups",
"logs:DescribeLogStreams"
]
Effect = "Allow"
Resource = "*"
}
]
})
}
# Security Group for Rocky Linux instances (ISO27001: A.13.1.3 网络隔离)
resource "aws_security_group" "rocky_instance" {
name = "${var.project_name}-rocky-sg"
description = "Security group for Rocky Linux instances"
vpc_id = aws_vpc.main.id
# SSH access (restricted to bastion/management IP)
ingress {
description = "SSH from management network"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = var.allowed_ssh_cidr
}
# HTTPS
ingress {
description = "HTTPS"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = var.allowed_https_cidr
}
# Allow all outbound
egress {
description = "Allow all outbound"
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "${var.project_name}-rocky-sg"
}
}
# IAM Role for EC2 instances (ISO27001: A.9.2 访问控制)
resource "aws_iam_role" "ec2_role" {
name = "${var.project_name}-ec2-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "ec2.amazonaws.com"
}
}
]
})
tags = {
Name = "${var.project_name}-ec2-role"
}
}
# IAM Policy for CloudWatch Logs
resource "aws_iam_role_policy" "cloudwatch_logs" {
name = "${var.project_name}-cloudwatch-logs-policy"
role = aws_iam_role.ec2_role.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogStreams"
]
Resource = "arn:aws:logs:*:*:*"
},
{
Effect = "Allow"
Action = [
"cloudwatch:PutMetricData"
]
Resource = "*"
}
]
})
}
# IAM Policy for SSM (Systems Manager for patching)
resource "aws_iam_role_policy_attachment" "ssm_managed_instance" {
role = aws_iam_role.ec2_role.name
policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}
resource "aws_iam_instance_profile" "ec2_profile" {
name = "${var.project_name}-ec2-profile"
role = aws_iam_role.ec2_role.name
}
# CloudWatch Log Group for application logs
resource "aws_cloudwatch_log_group" "application" {
name = "/aws/ec2/${var.project_name}"
retention_in_days = 90
kms_key_id = aws_kms_key.main.arn
tags = {
Name = "${var.project_name}-app-logs"
}
}
# Launch Template for Rocky Linux instances
resource "aws_launch_template" "rocky" {
name_prefix = "${var.project_name}-rocky-"
image_id = data.aws_ami.rocky_linux.id
instance_type = var.instance_type
key_name = var.key_pair_name
iam_instance_profile {
arn = aws_iam_instance_profile.ec2_profile.arn
}
vpc_security_group_ids = [aws_security_group.rocky_instance.id]
# EBS encryption (ISO27001: A.10.1.1 加密)
block_device_mappings {
device_name = "/dev/sda1"
ebs {
volume_size = var.root_volume_size
volume_type = "gp3"
encrypted = true
kms_key_id = aws_kms_key.main.arn
delete_on_termination = true
}
}
metadata_options {
http_endpoint = "enabled"
http_tokens = "required" # Enforce IMDSv2
http_put_response_hop_limit = 1
}
monitoring {
enabled = true
}
user_data = base64encode(templatefile("${path.module}/user-data.sh", {
cloudwatch_log_group = aws_cloudwatch_log_group.application.name
region = var.aws_region
}))
tag_specifications {
resource_type = "instance"
tags = {
Name = "${var.project_name}-rocky-instance"
}
}
tag_specifications {
resource_type = "volume"
tags = {
Name = "${var.project_name}-rocky-volume"
}
}
}
# Auto Scaling Group
resource "aws_autoscaling_group" "rocky" {
name = "${var.project_name}-rocky-asg"
vpc_zone_identifier = aws_subnet.private[*].id
desired_capacity = var.desired_capacity
max_size = var.max_size
min_size = var.min_size
health_check_type = "EC2"
health_check_grace_period = 300
launch_template {
id = aws_launch_template.rocky.id
version = "$Latest"
}
tag {
key = "Name"
value = "${var.project_name}-rocky-instance"
propagate_at_launch = true
}
tag {
key = "AutoScaling"
value = "true"
propagate_at_launch = true
}
}
# SNS Topic for alarms (ISO27001: A.16.1 事件管理)
resource "aws_sns_topic" "alarms" {
name = "${var.project_name}-alarms"
kms_master_key_id = aws_kms_key.main.id
tags = {
Name = "${var.project_name}-alarms"
}
}
resource "aws_sns_topic_subscription" "alarms_email" {
count = length(var.alarm_email_addresses)
topic_arn = aws_sns_topic.alarms.arn
protocol = "email"
endpoint = var.alarm_email_addresses[count.index]
}
# CloudWatch Alarms
resource "aws_cloudwatch_metric_alarm" "cpu_high" {
alarm_name = "${var.project_name}-cpu-high"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "2"
metric_name = "CPUUtilization"
namespace = "AWS/EC2"
period = "300"
statistic = "Average"
threshold = "80"
alarm_description = "This metric monitors ec2 cpu utilization"
alarm_actions = [aws_sns_topic.alarms.arn]
dimensions = {
AutoScalingGroupName = aws_autoscaling_group.rocky.name
}
}
resource "aws_cloudwatch_metric_alarm" "disk_usage_high" {
alarm_name = "${var.project_name}-disk-usage-high"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "1"
metric_name = "disk_used_percent"
namespace = "CWAgent"
period = "300"
statistic = "Average"
threshold = "80"
alarm_description = "This metric monitors disk usage"
alarm_actions = [aws_sns_topic.alarms.arn]
}
# Backup vault for EBS volumes (ISO27001: A.12.3 备份)
resource "aws_backup_vault" "main" {
name = "${var.project_name}-backup-vault"
kms_key_arn = aws_kms_key.main.arn
tags = {
Name = "${var.project_name}-backup-vault"
}
}
resource "aws_backup_plan" "daily" {
name = "${var.project_name}-daily-backup"
rule {
rule_name = "daily_backup"
target_vault_name = aws_backup_vault.main.name
schedule = "cron(0 2 * * ? *)" # 2 AM daily
lifecycle {
delete_after = 30 # Retain for 30 days
}
recovery_point_tags = {
Type = "Daily"
}
}
tags = {
Name = "${var.project_name}-backup-plan"
}
}
resource "aws_backup_selection" "ec2_backup" {
name = "${var.project_name}-ec2-backup-selection"
plan_id = aws_backup_plan.daily.id
iam_role_arn = aws_iam_role.backup.arn
selection_tag {
type = "STRINGEQUALS"
key = "AutoScaling"
value = "true"
}
}
resource "aws_iam_role" "backup" {
name = "${var.project_name}-backup-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "backup.amazonaws.com"
}
}
]
})
}
resource "aws_iam_role_policy_attachment" "backup_policy" {
role = aws_iam_role.backup.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup"
}
resource "aws_iam_role_policy_attachment" "backup_restore_policy" {
role = aws_iam_role.backup.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"
}outputs.tf
# Outputs for ISO27001 Compliant Rocky Linux Infrastructure
output "vpc_id" {
description = "VPC ID"
value = aws_vpc.main.id
}
output "vpc_cidr" {
description = "VPC CIDR block"
value = aws_vpc.main.cidr_block
}
output "public_subnet_ids" {
description = "Public subnet IDs"
value = aws_subnet.public[*].id
}
output "private_subnet_ids" {
description = "Private subnet IDs"
value = aws_subnet.private[*].id
}
output "security_group_id" {
description = "Security group ID for Rocky Linux instances"
value = aws_security_group.rocky_instance.id
}
output "kms_key_id" {
description = "KMS key ID for encryption"
value = aws_kms_key.main.id
}
output "kms_key_arn" {
description = "KMS key ARN"
value = aws_kms_key.main.arn
}
output "autoscaling_group_name" {
description = "Auto Scaling Group name"
value = aws_autoscaling_group.rocky.name
}
output "iam_role_name" {
description = "IAM role name for EC2 instances"
value = aws_iam_role.ec2_role.name
}
output "cloudwatch_log_group" {
description = "CloudWatch log group name"
value = aws_cloudwatch_log_group.application.name
}
output "backup_vault_name" {
description = "AWS Backup vault name"
value = aws_backup_vault.main.name
}
output "sns_topic_arn" {
description = "SNS topic ARN for alarms"
value = aws_sns_topic.alarms.arn
}
output "rocky_linux_ami_id" {
description = "Rocky Linux AMI ID used"
value = data.aws_ami.rocky_linux.id
}
output "rocky_linux_ami_name" {
description = "Rocky Linux AMI name"
value = data.aws_ami.rocky_linux.name
}terraform.tfvars.example
# Terraform Variables Configuration Example # 复制此文件为 terraform.tfvars 并填写实际值 # AWS Region aws_region = "ap-southeast-1" # Environment environment = "production" # Project Name project_name = "52aiops" # Owner owner = "DevOps Team" # VPC Configuration vpc_cidr = "10.0.0.0/16" availability_zones = ["ap-southeast-1a", "ap-southeast-1b"] # EC2 Configuration instance_type = "t3.medium" key_pair_name = "your-key-pair-name" # 替换为您的AWS密钥对名称 root_volume_size = 50 # Auto Scaling Configuration desired_capacity = 2 min_size = 1 max_size = 4 # Security Configuration # 仅允许内网访问SSH(推荐) allowed_ssh_cidr = ["10.0.0.0/8"] # 允许所有来源访问HTTPS(根据实际需求调整) allowed_https_cidr = ["0.0.0.0/0"] # Alarm Configuration # 接收告警通知的邮箱地址列表 alarm_email_addresses = [ "admin@52aiops.cn" ]
user-data.sh
#!/bin/bash
# User data script for Rocky Linux instances
# ISO27001 Compliant Configuration
set -e
# Log everything
exec > >(tee /var/log/user-data.log)
exec 2>&1
echo "=== Starting ISO27001 compliant Rocky Linux initialization ==="
# Update system packages (ISO27001: A.12.6.1 技术漏洞管理)
echo "Updating system packages..."
dnf update -y
# Install security and monitoring tools
echo "Installing security and monitoring tools..."
dnf install -y \
aide \
firewalld \
fail2ban \
chrony \
audit \
amazon-cloudwatch-agent \
amazon-ssm-agent
# Configure firewalld (ISO27001: A.13.1.1 网络控制)
echo "Configuring firewall..."
systemctl enable firewalld
systemctl start firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
# Configure fail2ban (ISO27001: A.9.4.2 安全登录)
echo "Configuring fail2ban..."
cat > /etc/fail2ban/jail.local <<EOF
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
[sshd]
enabled = true
port = ssh
logpath = /var/log/secure
EOF
systemctl enable fail2ban
systemctl start fail2ban
# Harden SSH configuration (ISO27001: A.9.4.2)
echo "Hardening SSH configuration..."
sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/#MaxAuthTries 6/MaxAuthTries 3/' /etc/ssh/sshd_config
sed -i 's/#ClientAliveInterval 0/ClientAliveInterval 300/' /etc/ssh/sshd_config
sed -i 's/#ClientAliveCountMax 3/ClientAliveCountMax 2/' /etc/ssh/sshd_config
echo "Protocol 2" >> /etc/ssh/sshd_config
systemctl restart sshd
# Configure time synchronization (ISO27001: A.12.4.4 时钟同步)
echo "Configuring time synchronization..."
systemctl enable chronyd
systemctl start chronyd
timedatectl set-timezone Asia/Shanghai
# Initialize AIDE (Advanced Intrusion Detection Environment)
# ISO27001: A.12.4.1 事件日志记录
echo "Initializing AIDE for file integrity monitoring..."
aide --init
mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
# Configure audit rules (ISO27001: A.12.4.1 事件日志记录)
echo "Configuring audit rules..."
cat > /etc/audit/rules.d/iso27001.rules <<EOF
# Monitor authentication events
-w /var/log/lastlog -p wa -k logins
-w /var/run/faillock/ -p wa -k logins
# Monitor unauthorized access attempts
-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/gshadow -p wa -k identity
# Monitor system network configuration
-w /etc/hosts -p wa -k network_modifications
-w /etc/sysconfig/network -p wa -k network_modifications
# Monitor privileged commands
-a always,exit -F arch=b64 -S execve -F uid=0 -F key=root_commands
-a always,exit -F arch=b32 -S execve -F uid=0 -F key=root_commands
# Monitor kernel module loading
-w /sbin/insmod -p x -k modules
-w /sbin/rmmod -p x -k modules
-w /sbin/modprobe -p x -k modules
EOF
augenrules --load
systemctl restart auditd
# Configure CloudWatch Agent
echo "Configuring CloudWatch Agent..."
cat > /opt/aws/amazon-cloudwatch-agent/etc/config.json <<EOF
{
"agent": {
"metrics_collection_interval": 60,
"run_as_user": "cwagent"
},
"logs": {
"logs_collected": {
"files": {
"collect_list": [
{
"file_path": "/var/log/messages",
"log_group_name": "${cloudwatch_log_group}",
"log_stream_name": "{instance_id}/messages"
},
{
"file_path": "/var/log/secure",
"log_group_name": "${cloudwatch_log_group}",
"log_stream_name": "{instance_id}/secure"
},
{
"file_path": "/var/log/audit/audit.log",
"log_group_name": "${cloudwatch_log_group}",
"log_stream_name": "{instance_id}/audit"
}
]
}
}
},
"metrics": {
"namespace": "CWAgent",
"metrics_collected": {
"cpu": {
"measurement": [
{
"name": "cpu_usage_idle",
"rename": "CPU_IDLE",
"unit": "Percent"
}
],
"metrics_collection_interval": 60,
"totalcpu": false
},
"disk": {
"measurement": [
{
"name": "used_percent",
"rename": "DISK_USED",
"unit": "Percent"
}
],
"metrics_collection_interval": 60,
"resources": [
"*"
]
},
"mem": {
"measurement": [
{
"name": "mem_used_percent",
"rename": "MEM_USED",
"unit": "Percent"
}
],
"metrics_collection_interval": 60
}
}
}
}
EOF
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
-a fetch-config \
-m ec2 \
-s \
-c file:/opt/aws/amazon-cloudwatch-agent/etc/config.json
# Set up automatic security updates (ISO27001: A.12.6.1)
echo "Configuring automatic security updates..."
dnf install -y dnf-automatic
sed -i 's/^apply_updates = no/apply_updates = yes/' /etc/dnf/automatic.conf
sed -i 's/^upgrade_type = default/upgrade_type = security/' /etc/dnf/automatic.conf
systemctl enable --now dnf-automatic.timer
# Configure password policies (ISO27001: A.9.4.3 口令管理系统)
echo "Configuring password policies..."
authselect select sssd with-faillock --force
cat > /etc/security/pwquality.conf <<EOF
# Password quality requirements
minlen = 14
dcredit = -1
ucredit = -1
lcredit = -1
ocredit = -1
minclass = 4
maxrepeat = 3
maxclassrepeat = 4
EOF
# Configure account lockout (ISO27001: A.9.4.2)
cat > /etc/security/faillock.conf <<EOF
deny = 5
unlock_time = 1800
fail_interval = 900
EOF
# Disable unnecessary services (ISO27001: A.9.1.2 最小权限原则)
echo "Disabling unnecessary services..."
SERVICES_TO_DISABLE="postfix bluetooth cups"
for service in $SERVICES_TO_DISABLE; do
if systemctl list-unit-files | grep -q "$service.service"; then
systemctl disable $service 2>/dev/null || true
systemctl stop $service 2>/dev/null || true
fi
done
# Set secure file permissions (ISO27001: A.9.1.1 访问控制策略)
echo "Setting secure file permissions..."
chmod 700 /root
chmod 600 /boot/grub2/grub.cfg 2>/dev/null || true
chmod 600 /etc/ssh/sshd_config
chmod 644 /etc/passwd
chmod 644 /etc/group
chmod 000 /etc/shadow
chmod 000 /etc/gshadow
# Configure system accounting (ISO27001: A.12.4.1)
echo "Configuring system accounting..."
systemctl enable psacct
systemctl start psacct
# Set up log rotation (ISO27001: A.12.4.2 日志文件保护)
cat > /etc/logrotate.d/iso27001 <<EOF
/var/log/messages
/var/log/secure
/var/log/maillog
/var/log/cron
{
daily
rotate 90
compress
delaycompress
missingok
notifempty
sharedscripts
postrotate
/usr/bin/systemctl reload rsyslog > /dev/null 2>&1 || true
endscript
}
EOF
# Enable SELinux (ISO27001: A.9.1.2 访问控制)
echo "Ensuring SELinux is enabled..."
setenforce 1
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
# Create compliance report
echo "Generating compliance report..."
cat > /root/iso27001-compliance-report.txt <<EOF
=== ISO27001 Compliance Configuration Report ===
Generated: $(date)
Instance ID: $(ec2-metadata --instance-id | cut -d " " -f 2)
Security Configurations Applied:
✓ A.9.1.2 - Minimum necessary services enabled
✓ A.9.4.2 - SSH hardened, fail2ban enabled
✓ A.9.4.3 - Strong password policies configured
✓ A.10.1.1 - Disk encryption enabled (via EBS)
✓ A.12.4.1 - Comprehensive audit logging enabled
✓ A.12.4.2 - Log rotation configured
✓ A.12.4.4 - Time synchronization configured
✓ A.12.6.1 - Automatic security updates enabled
✓ A.13.1.1 - Firewall configured
✓ A.16.1 - Monitoring and alerting configured
Installed Security Tools:
- AIDE (File Integrity Monitoring)
- fail2ban (Intrusion Prevention)
- auditd (System Auditing)
- CloudWatch Agent (Log Aggregation & Monitoring)
- SSM Agent (Patch Management)
SELinux Status: $(getenforce)
Firewall Status: $(firewall-cmd --state)
EOF
echo "=== ISO27001 compliant Rocky Linux initialization completed ==="
echo "Compliance report available at: /root/iso27001-compliance-report.txt"variables.tf
# Variables for ISO27001 Compliant Rocky Linux Infrastructure
variable "aws_region" {
description = "AWS region to deploy resources"
type = string
default = "ap-southeast-1"
}
variable "environment" {
description = "Environment name (e.g., production, staging, development)"
type = string
default = "production"
}
variable "project_name" {
description = "Project name for resource naming"
type = string
default = "52aiops"
}
variable "owner" {
description = "Owner of the infrastructure"
type = string
default = "DevOps Team"
}
variable "vpc_cidr" {
description = "CIDR block for VPC"
type = string
default = "10.0.0.0/16"
}
variable "availability_zones" {
description = "List of availability zones"
type = list(string)
default = ["ap-southeast-1a", "ap-southeast-1b"]
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t3.medium"
}
variable "key_pair_name" {
description = "AWS key pair name for SSH access"
type = string
}
variable "root_volume_size" {
description = "Size of root EBS volume in GB"
type = number
default = 50
}
variable "desired_capacity" {
description = "Desired number of instances in Auto Scaling Group"
type = number
default = 2
}
variable "min_size" {
description = "Minimum number of instances in Auto Scaling Group"
type = number
default = 1
}
variable "max_size" {
description = "Maximum number of instances in Auto Scaling Group"
type = number
default = 4
}
variable "allowed_ssh_cidr" {
description = "CIDR blocks allowed to SSH into instances"
type = list(string)
default = ["10.0.0.0/8"] # Restrict to internal network only
}
variable "allowed_https_cidr" {
description = "CIDR blocks allowed to access HTTPS"
type = list(string)
default = ["0.0.0.0/0"]
}
variable "alarm_email_addresses" {
description = "Email addresses to receive alarm notifications"
type = list(string)
default = []
}versions.tf
# Terraform and Provider Versions
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
# 可选:配置远程后端存储 Terraform 状态
# backend "s3" {
# bucket = "52aiops-terraform-state"
# key = "rocky-linux/terraform.tfstate"
# region = "ap-southeast-1"
# encrypt = true
# kms_key_id = "alias/terraform-state-key"
# dynamodb_table = "terraform-state-lock"
# }
}README.md
# ISO27001 合规的 Rocky Linux AWS 基础设施 这是一套完整的 Terraform 配置,用于在 AWS 上部署符合 ISO27001 信息安全管理标准的 Rocky Linux 基础设施。 ## 📋 ISO27001 合规性映射 本配置实现了以下 ISO27001 控制措施: ### A.9 访问控制 (Access Control) - **A.9.1.1** - 访问控制策略:通过安全组和IAM角色实现 - **A.9.1.2** - 最小权限原则:禁用不必要的服务,SELinux强制模式 - **A.9.4.2** - 安全登录:SSH加固、fail2ban、密钥认证 - **A.9.4.3** - 口令管理:强密码策略(14位最小长度,复杂度要求) ### A.10 密码学 (Cryptography) - **A.10.1.1** - 加密控制: - EBS卷使用KMS加密 - CloudWatch日志加密 - SNS主题加密 - 密钥自动轮换 ### A.12 运营安全 (Operations Security) - **A.12.3** - 备份:AWS Backup每日备份,保留30天 - **A.12.4.1** - 事件日志记录:auditd详细审计规则 - **A.12.4.2** - 日志文件保护:日志轮转、90天保留 - **A.12.4.4** - 时钟同步:chrony NTP配置 - **A.12.6.1** - 技术漏洞管理:自动安全更新 ### A.13 通信安全 (Communications Security) - **A.13.1** - 网络安全管理: - VPC隔离(公有/私有子网) - 安全组限制访问 - VPC Flow Logs监控 - NAT网关用于私有子网出站 ### A.16 信息安全事件管理 (Information Security Incident Management) - **A.16.1** - 事件管理: - CloudWatch告警 - SNS通知 - AIDE文件完整性监控 ## 🏗️ 架构概览 ``` ┌─────────────────────────────────────────────────────────────┐ │ AWS Region │ │ ┌───────────────────────────────────────────────────────┐ │ │ │ VPC (10.0.0.0/16) │ │ │ │ │ │ │ │ ┌──────────────┐ ┌──────────────┐ │ │ │ │ │ Public AZ-A │ │ Public AZ-B │ │ │ │ │ │ NAT Gateway │ │ NAT Gateway │ │ │ │ │ └──────┬───────┘ └──────┬───────┘ │ │ │ │ │ │ │ │ │ │ ┌──────▼───────┐ ┌──────▼───────┐ │ │ │ │ │ Private AZ-A │ │ Private AZ-B │ │ │ │ │ │ Rocky Linux │◄────ASG─────►│ Rocky Linux │ │ │ │ │ │ (Encrypted) │ │ (Encrypted) │ │ │ │ │ └──────────────┘ └──────────────┘ │ │ │ │ │ │ │ │ │ │ └──────────┬──────────────────┘ │ │ │ │ │ │ │ │ │ ┌───────▼────────┐ │ │ │ │ │ KMS Encryption │ │ │ │ │ └────────────────┘ │ │ │ └───────────────────────────────────────────────────────┘ │ │ │ │ ┌────────────────┐ ┌─────────────┐ ┌──────────────┐ │ │ │ CloudWatch │ │ AWS Backup │ │ SNS Alarms │ │ │ │ Logs & Metrics │ │ Vault │ │ Notification │ │ │ └────────────────┘ └─────────────┘ └──────────────┘ │ └─────────────────────────────────────────────────────────────┘ ``` ## 📦 包含的资源 ### 网络层 - VPC with public and private subnets - Internet Gateway - NAT Gateways (Multi-AZ) - Route Tables - VPC Flow Logs ### 计算层 - Auto Scaling Group - Launch Template (Rocky Linux 9) - Encrypted EBS Volumes (KMS) - CloudWatch Agent for monitoring - SSM Agent for patch management ### 安全层 - Security Groups (restricted access) - IAM Roles and Policies - KMS Keys (auto-rotation enabled) - fail2ban for intrusion prevention - AIDE for file integrity monitoring - auditd for system auditing ### 监控与告警 - CloudWatch Metrics and Alarms - CloudWatch Log Groups (90-day retention) - SNS Topics for notifications - CPU/Disk usage alarms ### 备份与恢复 - AWS Backup Vault (KMS encrypted) - Daily backup plan (30-day retention) ## 🚀 使用方法 ### 前置要求 1. **安装 Terraform** ```bash # 下载并安装 Terraform >= 1.0 wget https://releases.hashicorp.com/terraform/1.6.0/terraform_1.6.0_linux_amd64.zip unzip terraform_1.6.0_linux_amd64.zip sudo mv terraform /usr/local/bin/ ``` 2. **配置 AWS 凭证** ```bash aws configure # 输入 Access Key ID # 输入 Secret Access Key # 输入默认区域:ap-southeast-1 # 输入默认输出格式:json ``` 3. **创建 SSH 密钥对** ```bash # 在 AWS 控制台创建密钥对,或使用 AWS CLI aws ec2 create-key-pair --key-name 52aiops-key --query 'KeyMaterial' --output text > 52aiops-key.pem chmod 400 52aiops-key.pem ``` ### 部署步骤 1. **克隆配置文件** ```bash cd terraform/aws-rockyos-iso27001 ``` 2. **配置变量** ```bash cp terraform.tfvars.example terraform.tfvars # 编辑 terraform.tfvars,填写实际值 vim terraform.tfvars ``` 3. **初始化 Terraform** ```bash terraform init ``` 4. **验证配置** ```bash terraform validate terraform fmt ``` 5. **查看执行计划** ```bash terraform plan ``` 6. **应用配置** ```bash terraform apply # 输入 'yes' 确认执行 ``` 7. **查看输出** ```bash terraform output ``` ### 验证部署 1. **检查实例状态** ```bash aws ec2 describe-instances \ --filters "Name=tag:Project,Values=52aiops" \ --query 'Reservations[*].Instances[*].[InstanceId,State.Name,PrivateIpAddress]' \ --output table ``` 2. **查看 CloudWatch 日志** ```bash aws logs describe-log-streams \ --log-group-name "/aws/ec2/52aiops" \ --max-items 5 ``` 3. **验证备份配置** ```bash aws backup list-backup-plans ``` 4. **SSH 连接测试**(通过堡垒机或VPN) ```bash ssh -i 52aiops-key.pem ec2-user@<PRIVATE_IP> # 查看合规报告 sudo cat /root/iso27001-compliance-report.txt ``` ## 🔒 安全配置详情 ### SSH 加固 - 禁用 root 登录 - 仅允许密钥认证 - 最大尝试次数:3次 - 会话超时:300秒 - 仅支持 SSH 协议 2 ### 密码策略 - 最小长度:14位 - 必须包含大写、小写、数字、特殊字符 - 账户锁定:5次失败尝试后锁定30分钟 ### 审计日志 监控以下事件: - 用户登录/登出 - 身份变更(passwd, shadow, group) - 网络配置变更 - 特权命令执行 - 内核模块加载 ### 自动化安全更新 - 每日自动检查安全更新 - 自动应用安全补丁 - 通过 SSM Agent 管理 ## 📊 监控指标 ### 系统指标 - CPU 使用率 (>80% 告警) - 磁盘使用率 (>80% 告警) - 内存使用率 - 网络流量 ### 日志收集 - `/var/log/messages` - 系统日志 - `/var/log/secure` - 安全日志 - `/var/log/audit/audit.log` - 审计日志 ### 告警通知 通过 SNS 发送邮件通知到配置的邮箱地址。 ## 🔄 日常运维 ### 手动触发备份 ```bash aws backup start-backup-job \ --backup-vault-name 52aiops-backup-vault \ --resource-arn <INSTANCE_ARN> \ --iam-role-arn <BACKUP_ROLE_ARN> ``` ### 查看审计日志 ```bash # SSH 到实例 sudo ausearch -k logins -i sudo ausearch -k identity -i ``` ### 文件完整性检查 ```bash # SSH 到实例 sudo aide --check ``` ### 更新安全规则 ```bash # 修改 main.tf 中的安全组规则 terraform plan terraform apply ``` ## 💰 成本估算 基于默认配置(2个 t3.medium 实例): | 资源 | 月成本(美元) | |------|----------------| | EC2 实例 (2x t3.medium) | ~$60 | | EBS 存储 (2x 50GB gp3) | ~$10 | | NAT Gateway (2x) | ~$64 | | CloudWatch Logs | ~$5 | | AWS Backup | ~$5 | | KMS | ~$1 | | **总计** | **~$145/月** | *价格基于 ap-southeast-1 区域,实际费用可能有所不同* ## 🧹 清理资源 **警告**:此操作将删除所有创建的资源! ```bash terraform destroy # 输入 'yes' 确认删除 ``` ## 📝 合规性检查清单 部署完成后,请验证以下项目: - [ ] VPC Flow Logs 已启用并正常记录 - [ ] CloudWatch 日志正常收集 - [ ] 实例可通过 SSM Session Manager 访问 - [ ] 备份计划已创建并执行 - [ ] SNS 邮件订阅已确认 - [ ] SSH 仅允许密钥认证 - [ ] EBS 卷已加密 - [ ] SELinux 处于 Enforcing 模式 - [ ] fail2ban 服务正在运行 - [ ] 自动安全更新已启用 - [ ] AIDE 文件完整性监控已初始化 - [ ] auditd 审计规则已加载 ## 🆘 故障排查 ### 实例无法启动 ```bash # 查看 Auto Scaling 活动 aws autoscaling describe-scaling-activities \ --auto-scaling-group-name 52aiops-rocky-asg ``` ### CloudWatch Agent 未运行 ```bash # SSH 到实例 sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \ -a query -m ec2 -c default -s ``` ### 备份失败 ```bash # 查看备份任务状态 aws backup list-backup-jobs \ --by-backup-vault-name 52aiops-backup-vault ``` ## 📚 参考文档 - [ISO/IEC 27001:2013 标准](https://www.iso.org/standard/54534.html) - [Rocky Linux 文档](https://docs.rockylinux.org/) - [AWS 安全最佳实践](https://docs.aws.amazon.com/security/) - [Terraform AWS Provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)
关键字词:

下一篇:返回列表
相关文章
-
无相关信息