github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/internal/adapters/terraform/nifcloud/computing/security_group.go (about) 1 package computing 2 3 import ( 4 "github.com/khulnasoft-lab/defsec/pkg/providers/nifcloud/computing" 5 "github.com/khulnasoft-lab/defsec/pkg/terraform" 6 defsecTypes "github.com/khulnasoft-lab/defsec/pkg/types" 7 ) 8 9 type sgAdapter struct { 10 sgRuleIDs terraform.ResourceIDResolutions 11 } 12 13 func (a *sgAdapter) adaptSecurityGroups(modules terraform.Modules) []computing.SecurityGroup { 14 var securityGroups []computing.SecurityGroup 15 for _, resource := range modules.GetResourcesByType("nifcloud_security_group") { 16 securityGroups = append(securityGroups, a.adaptSecurityGroup(resource, modules)) 17 } 18 orphanResources := modules.GetResourceByIDs(a.sgRuleIDs.Orphans()...) 19 if len(orphanResources) > 0 { 20 orphanage := computing.SecurityGroup{ 21 Metadata: defsecTypes.NewUnmanagedMetadata(), 22 Description: defsecTypes.StringDefault("", defsecTypes.NewUnmanagedMetadata()), 23 IngressRules: nil, 24 } 25 for _, sgRule := range orphanResources { 26 if sgRule.GetAttribute("type").Equals("IN") { 27 orphanage.IngressRules = append(orphanage.IngressRules, adaptSGRule(sgRule, modules)) 28 } 29 if sgRule.GetAttribute("type").Equals("OUT") { 30 orphanage.EgressRules = append(orphanage.EgressRules, adaptSGRule(sgRule, modules)) 31 } 32 } 33 securityGroups = append(securityGroups, orphanage) 34 } 35 36 return securityGroups 37 } 38 39 func (a *sgAdapter) adaptSecurityGroup(resource *terraform.Block, module terraform.Modules) computing.SecurityGroup { 40 var ingressRules, egressRules []computing.SecurityGroupRule 41 42 descriptionAttr := resource.GetAttribute("description") 43 descriptionVal := descriptionAttr.AsStringValueOrDefault("", resource) 44 45 rulesBlocks := module.GetReferencingResources(resource, "nifcloud_security_group_rule", "security_group_names") 46 for _, ruleBlock := range rulesBlocks { 47 a.sgRuleIDs.Resolve(ruleBlock.ID()) 48 if ruleBlock.GetAttribute("type").Equals("IN") { 49 ingressRules = append(ingressRules, adaptSGRule(ruleBlock, module)) 50 } 51 if ruleBlock.GetAttribute("type").Equals("OUT") { 52 egressRules = append(egressRules, adaptSGRule(ruleBlock, module)) 53 } 54 } 55 56 return computing.SecurityGroup{ 57 Metadata: resource.GetMetadata(), 58 Description: descriptionVal, 59 IngressRules: ingressRules, 60 EgressRules: egressRules, 61 } 62 } 63 64 func adaptSGRule(resource *terraform.Block, modules terraform.Modules) computing.SecurityGroupRule { 65 ruleDescAttr := resource.GetAttribute("description") 66 ruleDescVal := ruleDescAttr.AsStringValueOrDefault("", resource) 67 68 cidrAttr := resource.GetAttribute("cidr_ip") 69 cidrVal := cidrAttr.AsStringValueOrDefault("", resource) 70 71 return computing.SecurityGroupRule{ 72 Metadata: resource.GetMetadata(), 73 Description: ruleDescVal, 74 CIDR: cidrVal, 75 } 76 }