-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.tf
More file actions
243 lines (198 loc) · 10.1 KB
/
Copy pathmain.tf
File metadata and controls
243 lines (198 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
provider "google" {
project = var.project_id
region = var.region
}
locals {
# Default security-focused filter. Covers the highest-signal audit events across:
# IAM, service accounts, firewall/network, GCS ACL/policy, KMS, org policy,
# compute instance tampering, Secret Manager, Cloud SQL, GKE, Cloud Run,
# Cloud Functions, logging sink integrity, Access Context Manager, BigQuery,
# Cloud Armor, Artifact Registry, Binary Authorization, VPN/Interconnect,
# Cloud Scheduler/Tasks, and billing.
default_log_filter = <<-EOT
logName="projects/${var.project_id}/logs/cloudaudit.googleapis.com%2Factivity"
AND (
-- IAM policy changes on any resource
protoPayload.methodName="SetIamPolicy"
-- Service account lifecycle and key management
OR protoPayload.methodName=("google.iam.admin.v1.CreateServiceAccount"
OR "google.iam.admin.v1.DeleteServiceAccount"
OR "google.iam.admin.v1.CreateServiceAccountKey"
OR "google.iam.admin.v1.DeleteServiceAccountKey"
OR "google.iam.admin.v1.DisableServiceAccount"
OR "google.iam.admin.v1.EnableServiceAccount"
OR "google.iam.admin.v1.UndeleteServiceAccount"
)
-- Firewall rules
OR protoPayload.methodName=~"compute\.firewalls\.(insert|patch|delete)"
-- VPC networks, peering, subnetworks, routers
OR protoPayload.methodName=~"compute\.networks\.(insert|delete|addPeering|removePeering)"
OR protoPayload.methodName=~"compute\.subnetworks\.(insert|delete|patch)"
OR protoPayload.methodName=~"compute\.routers\.(insert|delete|patch)"
-- VPN tunnels and interconnect attachments (traffic exfil risk)
OR protoPayload.methodName=~"compute\.vpnTunnels\.(insert|delete)"
OR protoPayload.methodName=~"compute\.interconnectAttachments\.(insert|delete|patch)"
-- Compute instance tampering: SA swap, metadata injection, IAM
OR protoPayload.methodName=~"compute\.instances\.(setServiceAccount|setMetadata|setIamPolicy)"
OR protoPayload.methodName="beta.compute.projects.setCommonInstanceMetadata"
OR protoPayload.methodName="compute.projects.setCommonInstanceMetadata"
-- GCS bucket ACL and policy changes
OR protoPayload.methodName=~"storage\.(setIamPermissions|putBucketAcl|putObjectAcl|putBucketPolicy)"
-- KMS key lifecycle
OR protoPayload.methodName=~"cloudkms\..*\.(Create|Destroy|Disable|Enable|Import|UpdateCryptoKey)"
-- Org policy changes
OR protoPayload.methodName=~"orgpolicy\..*\.(Create|Update|Delete)"
-- Secret Manager: secret and version lifecycle
OR protoPayload.methodName=~"secretmanager\.googleapis\.com/.*\.(Create|Delete|AddVersion|SetIamPolicy)"
-- Cloud SQL: data export and authorized network changes
OR protoPayload.methodName=~"cloudsql\.instances\.(export|update)"
-- GKE cluster lifecycle and config changes
OR protoPayload.methodName=~"container\.clusters\.(create|delete|update)"
OR protoPayload.methodName=~"container\.projects\.locations\.clusters\.(create|delete|update)"
-- Cloud Run: IAM (public exposure) and service deletion
OR protoPayload.methodName=~"run\.googleapis\.com/.*\.(SetIamPolicy|DeleteService)"
-- Cloud Functions: IAM (public exposure) and deletion
OR protoPayload.methodName=~"cloudfunctions\.functions\.(setIamPolicy|delete)"
OR protoPayload.methodName=~"cloudfunctions\.googleapis\.com/.*\.(SetIamPolicy|DeleteFunction)"
-- Logging sink integrity: deleting or updating sinks blinds this alerting pipeline
OR protoPayload.methodName=("logging.sinks.delete"
OR "logging.sinks.update"
OR "logging.exclusions.create"
OR "logging.exclusions.update"
OR "logging.exclusions.delete"
)
-- Access Context Manager: VPC service control perimeter changes
OR protoPayload.methodName=~"accesscontextmanager\..*\.(Create|Update|Delete)"
-- BigQuery: dataset IAM and public sharing
OR protoPayload.methodName=~"bigquery\.datasets\.(update|patch)"
OR protoPayload.methodName="google.iam.v1.IAMPolicy.SetIamPolicy"
-- Cloud Armor: WAF policy changes
OR protoPayload.methodName=~"compute\.securityPolicies\.(insert|patch|delete)"
-- Artifact Registry and Container Registry: image push/delete
OR protoPayload.methodName=~"artifactregistry\..*\.(Create|Delete|Update)"
OR protoPayload.methodName=~"containerregistry\..*"
-- Binary Authorization: policy relaxation
OR protoPayload.methodName=~"binaryauthorization\..*\.(Update|Delete)"
-- Cloud Scheduler and Cloud Tasks: new jobs targeting internal endpoints
OR protoPayload.methodName=~"cloudscheduler\..*\.(Create|Update|Delete)"
OR protoPayload.methodName=~"cloudtasks\..*\.(Create|Update|Delete)"
-- Billing account changes
OR protoPayload.methodName=~"billing\.accounts\..*\.update"
OR protoPayload.methodName="billing.resourceAssociations.create"
)
EOT
# Use the override if provided, otherwise use the curated default.
effective_log_filter = var.log_filter != "" ? var.log_filter : local.default_log_filter
}
# ---------------------------------------------------------------------------
# Service account for the Cloud Function (least-privilege)
# ---------------------------------------------------------------------------
resource "google_service_account" "function_sa" {
account_id = "${var.name_prefix}-fn-sa"
display_name = "Security Alerts Cloud Function"
description = "Service account used by the ${var.name_prefix} Cloud Function to write logs."
}
# Allow the function SA to write logs (needed for structured logging via Cloud Logging).
resource "google_project_iam_member" "function_sa_log_writer" {
project = var.project_id
role = "roles/logging.logWriter"
member = "serviceAccount:${google_service_account.function_sa.email}"
}
# Allow the function SA to invoke the Cloud Run service backing the Gen 2 function.
# Pub/Sub uses this SA as the OIDC identity when pushing messages, so without this
# role every push is rejected with "The request was not authenticated".
resource "google_project_iam_member" "function_sa_run_invoker" {
project = var.project_id
role = "roles/run.invoker"
member = "serviceAccount:${google_service_account.function_sa.email}"
}
# ---------------------------------------------------------------------------
# Pub/Sub topic
# ---------------------------------------------------------------------------
resource "google_pubsub_topic" "security_alerts" {
name = "${var.name_prefix}-topic"
# Retain undelivered messages for 7 days so nothing is lost if the function is down.
message_retention_duration = "604800s"
}
# Dead-letter topic for messages the function fails to process after max retries.
resource "google_pubsub_topic" "dead_letter" {
name = "${var.name_prefix}-dead-letter"
}
# ---------------------------------------------------------------------------
# Log sink → Pub/Sub
# ---------------------------------------------------------------------------
resource "google_logging_project_sink" "security_alerts_sink" {
name = "${var.name_prefix}-sink"
destination = "pubsub.googleapis.com/${google_pubsub_topic.security_alerts.id}"
filter = local.effective_log_filter
unique_writer_identity = true
}
# Grant the sink's auto-generated writer identity permission to publish.
resource "google_pubsub_topic_iam_member" "sink_publisher" {
topic = google_pubsub_topic.security_alerts.name
role = "roles/pubsub.publisher"
member = google_logging_project_sink.security_alerts_sink.writer_identity
}
# ---------------------------------------------------------------------------
# Cloud Storage bucket for function source
# ---------------------------------------------------------------------------
resource "google_storage_bucket" "function_source" {
name = "${var.project_id}-${var.name_prefix}-fn-src"
location = var.region
uniform_bucket_level_access = true
# Allow terraform destroy to remove the bucket even if it still has objects.
force_destroy = true
versioning {
enabled = true
}
}
# Zip the function source directory. The zip is re-created whenever any file inside changes.
data "archive_file" "function_zip" {
type = "zip"
source_dir = "${path.module}/function"
output_path = "${path.module}/.terraform/function.zip"
}
resource "google_storage_bucket_object" "function_source" {
# Use the content hash in the object name so a new deploy is triggered on any code change.
name = "function-${data.archive_file.function_zip.output_md5}.zip"
bucket = google_storage_bucket.function_source.name
source = data.archive_file.function_zip.output_path
}
# ---------------------------------------------------------------------------
# Cloud Function (Gen 2)
# ---------------------------------------------------------------------------
resource "google_cloudfunctions2_function" "security_alerts" {
name = "${var.name_prefix}-fn"
location = var.region
description = "Forwards GCP security audit events to a webhook in real time."
build_config {
runtime = "python312"
entry_point = "security_alert"
source {
storage_source {
bucket = google_storage_bucket.function_source.name
object = google_storage_bucket_object.function_source.name
}
}
}
service_config {
available_memory = "${var.function_memory_mb}M"
timeout_seconds = var.function_timeout_seconds
max_instance_count = 10
min_instance_count = 0
service_account_email = google_service_account.function_sa.email
ingress_settings = "ALLOW_INTERNAL_ONLY"
all_traffic_on_latest_revision = true
environment_variables = {
WEBHOOK_URL = var.webhook_url
LOG_LEVEL = "INFO"
}
}
event_trigger {
trigger_region = var.region
event_type = "google.cloud.pubsub.topic.v1.messagePublished"
pubsub_topic = google_pubsub_topic.security_alerts.id
retry_policy = "RETRY_POLICY_RETRY"
service_account_email = google_service_account.function_sa.email
}
}