# This policy uses the Sentinel tfplan/v2 import to validate that no security group # rules have the CIDR "0.0.0.0/0" for ingress rules. It covers both the # aws_security_group and the aws_security_group_rule resources which can both # define rules. # Import the tfplan/v2 import, but use the alias "tfplan" import "tfplan/v2" as tfplan # Import common-functions/tfplan-functions/tfplan-functions.sentinel # with alias "plan" import "tfplan-functions" as plan # Forbidden CIDRs # Include "null" to forbid missing or computed values forbidden_cidrs = ["0.0.0.0/0"] # Get all Security Group Ingress Rules SGIngressRules = filter tfplan.resource_changes as address, rc { rc.type is "aws_security_group_rule" and rc.mode is "managed" and (rc.change.actions contains "create" or rc.change.actions contains "update" or rc.change.actions contains "read" or rc.change.actions contains "no-op") and rc.change.after.type is "ingress" } # Filter to Ingress Security Group Rules with violations # Warnings will be printed for all violations since the last parameter is true violatingSGRules = plan.filter_attribute_contains_items_from_list(SGIngressRules, "cidr_blocks",forbidden_cidrs, true) # Get all Security Groups allSGs = plan.find_resources("aws_security_group") # Validate Security Groups violatingSGsCount = 0 for allSGs as address, sg { # Find the ingress rules of the current SG ingressRules = plan.find_blocks(sg, "ingress") # Filter to violating CIDR blocks # Warnings will not be printed for violations since the last parameter is false violatingIRs = plan.filter_attribute_contains_items_from_list(ingressRules, "cidr_blocks", forbidden_cidrs, false) # Print violation messages if length(violatingIRs["messages"]) > 0 { violatingSGsCount += 1 print("SG Ingress Violation:", address, "has at least one ingress rule", "with forbidden cidr blocks") plan.print_violations(violatingIRs["messages"], "Ingress Rule") } // end if } // end for SGs # Main rule validated = length(violatingSGRules["messages"]) is 0 and violatingSGsCount is 0 main = rule { validated is true }