-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.tf
More file actions
624 lines (539 loc) · 21.9 KB
/
Copy pathmain.tf
File metadata and controls
624 lines (539 loc) · 21.9 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
# =============================================================================
# CIS HARDENING TEST LAB - TERRAFORM CONFIGURATION
# =============================================================================
# Version: 2.1.0
# Purpose: Deploy cost-optimized Azure infrastructure for CIS benchmark testing
# =============================================================================
terraform {
required_version = ">= 1.2.0"
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 3.80"
}
random = {
source = "hashicorp/random"
version = "~> 3.5"
}
}
}
provider "azurerm" {
features {
key_vault {
purge_soft_delete_on_destroy = true
}
virtual_machine {
delete_os_disk_on_deletion = true
graceful_shutdown = false
skip_shutdown_and_force_delete = false
}
resource_group {
prevent_deletion_if_contains_resources = false
}
}
subscription_id = var.subscription_id
}
# =============================================================================
# VARIABLES
# =============================================================================
variable "subscription_id" {
description = "Azure subscription ID"
type = string
default = "<YOUR-SUBSCRIPTION-ID>"
validation {
condition = var.subscription_id != "<YOUR-SUBSCRIPTION-ID>"
error_message = "You must set subscription_id to your actual Azure subscription ID."
}
}
variable "location" {
description = "Azure region for resources (try eastus2, westus2, centralus if capacity issues)"
type = string
default = "eastus2"
}
variable "resource_group_name" {
description = "Name of the resource group"
type = string
default = "rg-hardening-lab"
}
variable "admin_username" {
description = "Admin username for VMs"
type = string
default = "adminuser"
}
variable "allowed_source_ip" {
description = "Your IP address for WinRM/RDP access"
type = string
default = "*" # Change this to your public IP for better security
}
variable "enable_auto_shutdown" {
description = "Enable automatic VM shutdown to save costs"
type = bool
default = true
}
variable "auto_shutdown_time" {
description = "Time for auto-shutdown in HHMM format (24-hour, UTC)"
type = string
default = "1900"
}
variable "vm_size" {
description = "VM size - use smaller for cost savings"
type = string
default = "Standard_D2s_v3"
}
variable "use_spot_instances" {
description = "Use Spot instances for cost savings (may be evicted - set to false for stability)"
type = bool
default = false # Disabled for stability during hardening
}
variable "os_configurations" {
description = "Map of OS configurations to deploy"
type = map(object({
enabled = bool
publisher = string
offer = string
sku = string
}))
default = {
# Windows 11 Enterprise
"win11" = {
enabled = true
publisher = "MicrosoftWindowsDesktop"
offer = "Windows-11"
sku = "win11-24h2-ent"
}
# Windows Server 2022 Datacenter
"2022" = {
enabled = true
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2022-datacenter-azure-edition-smalldisk"
}
# Windows Server 2025 Datacenter
"2025" = {
enabled = true
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2025-datacenter-azure-edition-smalldisk"
}
}
}
# =============================================================================
# DATA SOURCES
# =============================================================================
data "azurerm_client_config" "current" {}
# =============================================================================
# LOCAL VALUES
# =============================================================================
locals {
# Filter to only enabled OS configurations
enabled_os_list = {
for key, config in var.os_configurations : key => config
if config.enabled
}
# Common tags for all resources
common_tags = {
Environment = "Testing"
Project = "CIS-Hardening-Lab"
ManagedBy = "Terraform"
CostCenter = "Testing"
AutoShutdown = var.enable_auto_shutdown ? "Enabled" : "Disabled"
}
# VM-specific tags (includes os_type for dynamic inventory grouping)
vm_tags = {
for key, config in local.enabled_os_list : key => merge(local.common_tags, {
os_type = key
os_name = config.offer
os_sku = config.sku
})
}
}
# =============================================================================
# RANDOM RESOURCES
# =============================================================================
resource "random_id" "suffix" {
byte_length = 4
}
resource "random_password" "win_admin_pass" {
length = 20
special = true
override_special = "!#$%&*()-_=+[]{}<>:?"
min_lower = 2
min_upper = 2
min_numeric = 2
min_special = 2
}
# =============================================================================
# RESOURCE GROUP
# =============================================================================
resource "azurerm_resource_group" "lab" {
name = var.resource_group_name
location = var.location
tags = local.common_tags
}
# =============================================================================
# KEY VAULT & SECRETS
# =============================================================================
resource "azurerm_key_vault" "lab_kv" {
name = "kv-hard-lab-${random_id.suffix.hex}"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
enabled_for_disk_encryption = true
tenant_id = data.azurerm_client_config.current.tenant_id
soft_delete_retention_days = 7
purge_protection_enabled = false
sku_name = "standard"
tags = local.common_tags
access_policy {
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
secret_permissions = ["Get", "List", "Set", "Delete", "Purge", "Recover"]
}
}
resource "azurerm_key_vault_secret" "admin_secret" {
name = "win-admin-password"
value = random_password.win_admin_pass.result
key_vault_id = azurerm_key_vault.lab_kv.id
lifecycle {
ignore_changes = [value]
}
}
# =============================================================================
# NETWORKING
# =============================================================================
resource "azurerm_virtual_network" "vnet" {
name = "vnet-lab"
resource_group_name = azurerm_resource_group.lab.name
location = azurerm_resource_group.lab.location
address_space = ["10.0.0.0/16"]
tags = local.common_tags
}
resource "azurerm_subnet" "snet" {
name = "snet-vms"
virtual_network_name = azurerm_virtual_network.vnet.name
resource_group_name = azurerm_resource_group.lab.name
address_prefixes = ["10.0.1.0/24"]
}
# Network Security Group
resource "azurerm_network_security_group" "nsg" {
name = "nsg-hardening-lab"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
tags = local.common_tags
}
# NSG Rules - Allow WinRM HTTPS
resource "azurerm_network_security_rule" "allow_winrm_https" {
name = "AllowWinRM-HTTPS-5986"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "5986"
source_address_prefix = var.allowed_source_ip
destination_address_prefix = "*"
resource_group_name = azurerm_resource_group.lab.name
network_security_group_name = azurerm_network_security_group.nsg.name
description = "Allow WinRM HTTPS for Ansible"
}
# Deny WinRM HTTP (unencrypted)
resource "azurerm_network_security_rule" "deny_winrm_http" {
name = "DenyWinRM-HTTP-5985"
priority = 110
direction = "Inbound"
access = "Deny"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "5985"
source_address_prefix = "*"
destination_address_prefix = "*"
resource_group_name = azurerm_resource_group.lab.name
network_security_group_name = azurerm_network_security_group.nsg.name
description = "Deny unencrypted WinRM HTTP"
}
# Allow RDP for troubleshooting
resource "azurerm_network_security_rule" "allow_rdp" {
name = "AllowRDP-3389"
priority = 120
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "3389"
source_address_prefix = var.allowed_source_ip
destination_address_prefix = "*"
resource_group_name = azurerm_resource_group.lab.name
network_security_group_name = azurerm_network_security_group.nsg.name
description = "Allow RDP for troubleshooting"
}
resource "azurerm_subnet_network_security_group_association" "snet_assoc" {
subnet_id = azurerm_subnet.snet.id
network_security_group_id = azurerm_network_security_group.nsg.id
}
# Public IPs
resource "azurerm_public_ip" "pip" {
for_each = local.enabled_os_list
name = "pip-${each.key}"
resource_group_name = azurerm_resource_group.lab.name
location = azurerm_resource_group.lab.location
allocation_method = "Static"
sku = "Standard"
tags = local.common_tags
}
# Network Interfaces
resource "azurerm_network_interface" "nic" {
for_each = local.enabled_os_list
name = "nic-${each.key}"
location = azurerm_resource_group.lab.location
resource_group_name = azurerm_resource_group.lab.name
tags = local.common_tags
ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.snet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.pip[each.key].id
}
}
# =============================================================================
# VIRTUAL MACHINES
# =============================================================================
resource "azurerm_windows_virtual_machine" "vm" {
for_each = local.enabled_os_list
name = "vm-${each.key}"
resource_group_name = azurerm_resource_group.lab.name
location = azurerm_resource_group.lab.location
size = var.vm_size
admin_username = var.admin_username
admin_password = random_password.win_admin_pass.result
computer_name = "VM${upper(each.key)}"
tags = local.vm_tags[each.key]
# Spot instances (optional)
priority = var.use_spot_instances ? "Spot" : "Regular"
eviction_policy = var.use_spot_instances ? "Deallocate" : null
max_bid_price = var.use_spot_instances ? -1 : null
# Patch management settings - Windows 11 doesn't support AutomaticByPlatform
patch_mode = each.key == "win11" ? "Manual" : "AutomaticByPlatform"
patch_assessment_mode = each.key == "win11" ? "ImageDefault" : "AutomaticByPlatform"
provision_vm_agent = true
enable_automatic_updates = each.key == "win11" ? false : true
bypass_platform_safety_checks_on_user_schedule_enabled = each.key == "win11" ? false : true
network_interface_ids = [azurerm_network_interface.nic[each.key].id]
os_disk {
name = "osdisk-${each.key}"
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
disk_size_gb = 127
}
source_image_reference {
publisher = each.value.publisher
offer = each.value.offer
sku = each.value.sku
version = "latest"
}
lifecycle {
ignore_changes = [admin_password]
}
}
# =============================================================================
# AUTO-SHUTDOWN SCHEDULE (COST OPTIMIZATION)
# =============================================================================
resource "azurerm_dev_test_global_vm_shutdown_schedule" "auto_shutdown" {
for_each = var.enable_auto_shutdown ? local.enabled_os_list : {}
virtual_machine_id = azurerm_windows_virtual_machine.vm[each.key].id
location = azurerm_resource_group.lab.location
enabled = true
daily_recurrence_time = var.auto_shutdown_time
timezone = "UTC"
notification_settings {
enabled = false
}
tags = local.common_tags
}
# =============================================================================
# VM BOOTSTRAP EXTENSION
# =============================================================================
resource "azurerm_virtual_machine_extension" "bootstrap" {
for_each = azurerm_windows_virtual_machine.vm
name = "ansible-prep"
virtual_machine_id = each.value.id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
tags = local.common_tags
settings = jsonencode({
commandToExecute = "powershell -ExecutionPolicy Unrestricted -Command \"try { Set-ExecutionPolicy Unrestricted -Force -Scope LocalMachine; Get-NetConnectionProfile | Where-Object {$_.NetworkCategory -ne 'Private'} | Set-NetConnectionProfile -NetworkCategory Private; Enable-PSRemoting -Force -SkipNetworkProfileCheck; $cert = Get-ChildItem -Path Cert:\\LocalMachine\\My | Where-Object {$_.Subject -like '*localhost*'} | Select-Object -First 1; if (-not $cert) { $cert = New-SelfSignedCertificate -CertStoreLocation Cert:\\LocalMachine\\My -DnsName 'localhost' -NotAfter (Get-Date).AddYears(5) }; $listeners = Get-ChildItem -Path WSMan:\\localhost\\Listener | Where-Object {$_.Keys -contains 'Transport=HTTPS'}; if (-not $listeners) { New-Item -Path WSMan:\\localhost\\Listener -Address * -Transport HTTPS -HostName 'localhost' -CertificateThumbprint $cert.Thumbprint -Force }; Set-Item -Path WSMan:\\localhost\\Service\\Auth\\Basic -Value $true; Set-Item -Path WSMan:\\localhost\\Service\\AllowUnencrypted -Value $false; reg add 'HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System' /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f; $rule = Get-NetFirewallRule -Name 'Allow WinRM HTTPS' -ErrorAction SilentlyContinue; if (-not $rule) { New-NetFirewallRule -Name 'Allow WinRM HTTPS' -DisplayName 'Allow WinRM HTTPS' -Direction Inbound -Protocol TCP -LocalPort 5986 -Action Allow }; Restart-Service WinRM; Write-Output 'Bootstrap completed successfully' } catch { Write-Error $_.Exception.Message; exit 1 }\""
})
# Delete extension before VM is deleted, and don't block on extension deletion errors
lifecycle {
create_before_destroy = false
}
depends_on = [azurerm_windows_virtual_machine.vm]
}
# =============================================================================
# OUTPUTS
# =============================================================================
output "resource_group_name" {
description = "Name of the resource group"
value = azurerm_resource_group.lab.name
}
output "key_vault_uri" {
description = "URI of the Key Vault"
value = azurerm_key_vault.lab_kv.vault_uri
}
output "key_vault_name" {
description = "Name of the Key Vault"
value = azurerm_key_vault.lab_kv.name
}
output "vm_public_ips" {
description = "Public IP addresses of the VMs"
value = {
for key, pip in azurerm_public_ip.pip : key => pip.ip_address
}
}
output "vm_private_ips" {
description = "Private IP addresses of the VMs"
value = {
for key, nic in azurerm_network_interface.nic : key => nic.private_ip_address
}
}
output "admin_username" {
description = "Admin username for VMs"
value = var.admin_username
}
output "admin_password_keyvault_secret" {
description = "Key Vault secret name containing admin password"
value = azurerm_key_vault_secret.admin_secret.name
}
output "password_retrieval_command" {
description = "Command to retrieve admin password from Key Vault"
value = "az keyvault secret show --vault-name ${azurerm_key_vault.lab_kv.name} --name ${azurerm_key_vault_secret.admin_secret.name} --query value -o tsv"
}
output "ansible_test_command" {
description = "Command to test Ansible connectivity"
value = "ansible windows -i inventory.ini -m ansible.windows.win_ping"
}
# =============================================================================
# ANSIBLE INVENTORY FILE
# =============================================================================
resource "local_file" "ansible_inventory" {
filename = "${path.module}/inventory.ini"
file_permission = "0600"
content = <<-EOT
# =============================================================================
# ANSIBLE INVENTORY FOR CIS HARDENING LAB
# =============================================================================
# Generated by Terraform - Do not edit manually
# Generated: ${timestamp()}
# =============================================================================
[windows]
%{for key, vm in azurerm_windows_virtual_machine.vm~}
${key} ansible_host=${azurerm_public_ip.pip[key].ip_address}
%{endfor~}
# OS-specific groups (used by hardening playbook for OS detection)
%{for key, vm in azurerm_windows_virtual_machine.vm~}
[tag_os_type_${key}]
${key}
%{endfor~}
# =============================================================================
# CONNECTION VARIABLES
# =============================================================================
[windows:vars]
ansible_user=${var.admin_username}
ansible_password=${random_password.win_admin_pass.result}
ansible_connection=winrm
ansible_winrm_transport=basic
ansible_winrm_server_cert_validation=ignore
ansible_port=5986
ansible_winrm_operation_timeout_sec=120
ansible_winrm_read_timeout_sec=150
EOT
depends_on = [
azurerm_windows_virtual_machine.vm,
azurerm_public_ip.pip
]
}
# =============================================================================
# HELPER SCRIPT
# =============================================================================
resource "local_file" "helper_scripts" {
filename = "${path.module}/lab-helper.sh"
file_permission = "0755"
content = <<-SCRIPT
#!/bin/bash
# =============================================================================
# CIS HARDENING LAB HELPER SCRIPT
# =============================================================================
RG="${var.resource_group_name}"
KV_NAME="${azurerm_key_vault.lab_kv.name}"
INVENTORY="inventory.ini"
case "$1" in
start)
echo "Starting all VMs in $RG..."
az vm start --ids $(az vm list -g $RG --query "[].id" -o tsv) --no-wait
echo "VMs starting. Wait 2-3 minutes, then check with: $0 status"
;;
stop)
echo "Deallocating all VMs in $RG (stops billing for compute)..."
az vm deallocate --ids $(az vm list -g $RG --query "[].id" -o tsv) --no-wait
echo "VMs deallocating. Check status with: $0 status"
;;
restart)
echo "Restarting all VMs in $RG..."
az vm restart --ids $(az vm list -g $RG --query "[].id" -o tsv) --no-wait
echo "VMs restarting. Wait 2-3 minutes, then check with: $0 status"
;;
status)
echo "VM Status in $RG:"
az vm list -g $RG -d --query "[].{Name:name, State:powerState, PublicIP:publicIps, PrivateIP:privateIps}" -o table
;;
ips)
echo "VM IPs in $RG:"
az vm list-ip-addresses -g $RG -o table
;;
password)
echo "Retrieving admin password from Key Vault..."
az keyvault secret show --vault-name $KV_NAME --name win-admin-password --query value -o tsv
;;
test)
echo "Testing Ansible connectivity..."
ansible windows -i $INVENTORY -m ansible.windows.win_ping
;;
harden)
echo "Running CIS hardening playbook..."
ansible-playbook -i $INVENTORY cis_hardening_playbook.yml
;;
refresh)
echo "Refreshing Terraform state and regenerating inventory..."
terraform apply -refresh-only -auto-approve
terraform apply -auto-approve
;;
destroy)
echo "Starting VMs before destroy (required to delete extensions)..."
az vm start --ids $(az vm list -g $RG --query "[].id" -o tsv) 2>/dev/null || true
echo "Waiting 60 seconds for VMs to start..."
sleep 60
echo "Running terraform destroy..."
terraform destroy
;;
*)
echo "Usage: $0 {start|stop|restart|status|ips|password|test|harden|refresh|destroy}"
echo ""
echo "VM Management:"
echo " start - Start all VMs"
echo " stop - Deallocate all VMs (stops compute billing)"
echo " restart - Restart all VMs"
echo " status - Show VM power state and IPs"
echo " ips - Show VM IP addresses"
echo " password - Retrieve admin password from Key Vault"
echo ""
echo "Ansible:"
echo " test - Test Ansible connectivity"
echo " harden - Run CIS hardening playbook"
echo ""
echo "Terraform:"
echo " refresh - Refresh state and regenerate inventory"
echo " destroy - Start VMs and destroy all resources"
exit 1
;;
esac
SCRIPT
}