# SG Summary - Server
#     Ingress: 
#       22 - sync from other security centers
#       443 - User access
#     Egress:  
#       25 - smtp
#       443 - updates
#       tcp/1243 - "Communicating with Log Correlation Engine" (unneeded in xdr)
#       tcp/8834-8835 - Communicating With Nessus - to vpc-managers
resource "aws_security_group" "nessus_manager" {
  name_prefix = "nessus_manager"
  tags        = merge(var.standard_tags, var.tags, { Name = "nessus_manager" })
  vpc_id      = var.vpc_id
  description = "Nessus Security Scanner"
}

#-----------------------------------------------------------------
# Inbound access
#-----------------------------------------------------------------
resource "aws_security_group_rule" "nessus_manager_inbound_nessus" {
  security_group_id = aws_security_group.nessus_manager.id
  type              = "ingress"
  cidr_blocks       = ["10.0.0.0/8"]
  from_port         = 8834
  to_port           = 8834 # no 8835 according to https://docs.tenable.com/nessusagent/Content/RequirementsDataflow.htm
  protocol          = "tcp"
  description       = "Inbound Nessus"
}

resource "aws_security_group_rule" "http-in-external-c2-users" {
  # Wow. What was I thinking with c2_services_external_ips? 
  # Regardless, it's not used often to address 'all' customers.
  #
  # This deserves some explanation.  Terraform "for_each" expects to be
  # getting as input a map of values to iterate over as part of the foreach.
  # The keys of the map are used to name each of these objects created.  Looking
  # in the terraform plan output of a for_each you'll see things like:
  #
  # aws_security_group_rule.resource_name["key-value-from-foreach"] will be created
  #
  # Our c2_services_external_ips is a list of maps, not a map of maps.  The for-expression
  # makes a new thing that is a map of maps, where the key value is the description with
  # blanks removed.
  #
  # We could have made the variable more natively-friendly to for_each but this seemed
  # like a better solution for what we were trying to accomplish.
  for_each = { for s in var.c2_services_external_ips : replace(s.description, "/\\s*/", "") => s }

  description       = "inbound nessus agent - ${each.value.description}"
  type              = "ingress"
  from_port         = 8834
  to_port           = 8834
  protocol          = "tcp"
  cidr_blocks       = each.value.cidr_blocks
  security_group_id = aws_security_group.nessus_manager.id
}

#-----------------------------------------------------------------
# Outbound access
#-----------------------------------------------------------------
#resource "aws_security_group_rule" "nessus_manager_outbound_all_ports" {
#  security_group_id        = aws_security_group.nessus_manager.id
#  type                     = "egress"
#  cidr_blocks              = [ "10.0.0.0/8" ]
#  from_port                = -1
#  to_port                  = -1
#  protocol                 = "all"
#  description              = "Outbound to All Ports"
#}
