package awsjob import ( "context" "fmt" "net/netip" "slices" "amadan.net/oficina/equipo/internal/isolatedjob" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/ec2" ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/aws/aws-sdk-go-v2/service/lambdacore" coretypes "github.com/aws/aws-sdk-go-v2/service/lambdacore/types" ) // AuditNetwork reads the egress connector and the configured VPC, subnet and // security group as they are now. First the connector, by its pinned // version, must be an ACTIVE VPC_EGRESS connector for MicroVMs at that // version, without service-managed Elastic IP addresses, whose subnets and // security groups are exactly VMSubnetID and VMSecurityGroupID; so the // resources audited below are the ones VM traffic uses. Then: // // - ResolverDisabled: the VPC has both enableDnsSupport and // enableDnsHostnames read as false. // - IngressClosed: the security group has no inbound rules. // - RouteOutAbsent: the subnet's route table (its own, or the VPC's main // table when it has none) has only "local" routes. Any other target, // gateway endpoints included, counts as a route out. // - EgressOnly: every host and port the security group's outbound rules // allow. It equals Config.Egress when the group is right. // // It returns an error, and the zero audit in which every property has // failed, when the connector check fails, a read fails, an ID is missing or outside the VPC, or an // outbound rule allows more than single TCP hosts and ports (a network, a // port range, another protocol, a prefix list or a group): what it cannot // establish is never assumed. func (r *Runner) AuditNetwork(ctx context.Context) (isolatedjob.NetworkAudit, error) { a, err := r.audit(ctx) if err != nil { return isolatedjob.NetworkAudit{}, fmt.Errorf("awsjob: network audit: %w", err) } return a, nil } func (r *Runner) audit(ctx context.Context) (isolatedjob.NetworkAudit, error) { var a isolatedjob.NetworkAudit if err := r.checkConnector(ctx); err != nil { return a, err } support, err := r.vpcAttribute(ctx, ec2types.VpcAttributeNameEnableDnsSupport) if err != nil { return a, err } hostnames, err := r.vpcAttribute(ctx, ec2types.VpcAttributeNameEnableDnsHostnames) if err != nil { return a, err } a.ResolverDisabled = support != nil && !*support && hostnames != nil && !*hostnames table, err := r.subnetRouteTable(ctx) if err != nil { return a, err } a.RouteOutAbsent = table != nil && onlyLocal(table.Routes) sgs, err := r.api.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{GroupIds: []string{r.cfg.VMSecurityGroupID}}) if err != nil { return a, fmt.Errorf("describe security group %s: %w", r.cfg.VMSecurityGroupID, err) } if len(sgs.SecurityGroups) != 1 || aws.ToString(sgs.SecurityGroups[0].VpcId) != r.cfg.VPCID { return a, fmt.Errorf("security group %s is not one group in %s", r.cfg.VMSecurityGroupID, r.cfg.VPCID) } sg := sgs.SecurityGroups[0] a.IngressClosed = len(sg.IpPermissions) == 0 for _, p := range sg.IpPermissionsEgress { dests, err := hostPorts(p) if err != nil { return a, fmt.Errorf("security group %s: %w", r.cfg.VMSecurityGroupID, err) } for _, d := range dests { if !slices.Contains(a.EgressOnly, d) { a.EgressOnly = append(a.EgressOnly, d) } } } return a, nil } // checkConnector establishes that the pinned connector version sends VM // traffic through exactly the configured subnet and security group. func (r *Runner) checkConnector(ctx context.Context) error { id := r.cfg.ConnectorID out, err := r.api.GetNetworkConnector(ctx, &lambdacore.GetNetworkConnectorInput{Identifier: aws.String(id)}) if err != nil { return fmt.Errorf("get network connector %s: %w", id, err) } if got := aws.ToString(out.VersionArn); got != id { return fmt.Errorf("network connector %s answered for version %q, not the pinned one", id, got) } if out.State != coretypes.NetworkConnectorStateActive { return fmt.Errorf("network connector %s is %s, not ACTIVE", id, out.State) } vpc, ok := out.Configuration.(*coretypes.NetworkConnectorConfigurationMemberVpcEgressConfiguration) if !ok { return fmt.Errorf("network connector %s is not a VPC egress connector (%T)", id, out.Configuration) } c := vpc.Value if !slices.Equal(c.AssociatedComputeResourceTypes, []coretypes.ComputeResourceType{coretypes.ComputeResourceTypeMicroVm}) { return fmt.Errorf("network connector %s serves %v, want MicroVm only", id, c.AssociatedComputeResourceTypes) } if !slices.Equal(c.SubnetIds, []string{r.cfg.VMSubnetID}) { return fmt.Errorf("network connector %s uses subnets %q, want only %s", id, c.SubnetIds, r.cfg.VMSubnetID) } if !slices.Equal(c.SecurityGroupIds, []string{r.cfg.VMSecurityGroupID}) { return fmt.Errorf("network connector %s uses security groups %q, want only %s", id, c.SecurityGroupIds, r.cfg.VMSecurityGroupID) } if e := c.ElasticIpConfiguration; e != nil && e.Type != coretypes.ElasticIpTypeNone { return fmt.Errorf("network connector %s gives its interfaces %s Elastic IP addresses", id, e.Type) } return nil } // vpcAttribute reads one boolean VPC attribute; nil means AWS gave no value. func (r *Runner) vpcAttribute(ctx context.Context, name ec2types.VpcAttributeName) (*bool, error) { out, err := r.api.DescribeVpcAttribute(ctx, &ec2.DescribeVpcAttributeInput{VpcId: aws.String(r.cfg.VPCID), Attribute: name}) if err != nil { return nil, fmt.Errorf("describe %s of %s: %w", name, r.cfg.VPCID, err) } var v *ec2types.AttributeBooleanValue switch name { case ec2types.VpcAttributeNameEnableDnsSupport: v = out.EnableDnsSupport case ec2types.VpcAttributeNameEnableDnsHostnames: v = out.EnableDnsHostnames } if v == nil { return nil, nil } return v.Value, nil } // subnetRouteTable returns the route table the VM subnet uses: the one // associated with it, or else the VPC's main table. nil means none was // found. func (r *Runner) subnetRouteTable(ctx context.Context) (*ec2types.RouteTable, error) { subnets, err := r.api.DescribeSubnets(ctx, &ec2.DescribeSubnetsInput{SubnetIds: []string{r.cfg.VMSubnetID}}) if err != nil { return nil, fmt.Errorf("describe subnet %s: %w", r.cfg.VMSubnetID, err) } if len(subnets.Subnets) != 1 || aws.ToString(subnets.Subnets[0].VpcId) != r.cfg.VPCID { return nil, fmt.Errorf("subnet %s is not one subnet in %s", r.cfg.VMSubnetID, r.cfg.VPCID) } tables, err := r.routeTables(ctx, filter("association.subnet-id", r.cfg.VMSubnetID)) if err != nil { return nil, err } if len(tables) == 0 { if tables, err = r.routeTables(ctx, filter("vpc-id", r.cfg.VPCID), filter("association.main", "true")); err != nil { return nil, err } } switch len(tables) { case 0: return nil, nil case 1: return &tables[0], nil } return nil, fmt.Errorf("subnet %s matches %d route tables", r.cfg.VMSubnetID, len(tables)) } func (r *Runner) routeTables(ctx context.Context, filters ...ec2types.Filter) ([]ec2types.RouteTable, error) { var tables []ec2types.RouteTable var token *string seen := map[string]bool{} for { out, err := r.api.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: filters, NextToken: token}) if err != nil { return nil, fmt.Errorf("describe route tables: %w", err) } tables = append(tables, out.RouteTables...) next := aws.ToString(out.NextToken) if next == "" { return tables, nil } if seen[next] { return nil, fmt.Errorf("describe route tables repeats a page token") } seen[next] = true token = aws.String(next) } } func filter(name, value string) ec2types.Filter { return ec2types.Filter{Name: aws.String(name), Values: []string{value}} } // onlyLocal reports whether every route stays inside the VPC: target // "local" and nothing else. func onlyLocal(routes []ec2types.Route) bool { for _, rt := range routes { other := rt.CarrierGatewayId != nil || rt.CoreNetworkArn != nil || rt.EgressOnlyInternetGatewayId != nil || rt.InstanceId != nil || rt.LocalGatewayId != nil || rt.NatGatewayId != nil || rt.NetworkInterfaceId != nil || rt.OdbNetworkArn != nil || rt.TransitGatewayId != nil || rt.VpcPeeringConnectionId != nil || rt.IgwFirewall != nil if aws.ToString(rt.GatewayId) != "local" || other { return false } } return true } // hostPorts turns one outbound rule into the hosts and port it allows, or // an error when it allows more than single hosts on one TCP port. func hostPorts(p ec2types.IpPermission) ([]netip.AddrPort, error) { proto := aws.ToString(p.IpProtocol) if proto != "tcp" && proto != "6" { return nil, fmt.Errorf("outbound rule for protocol %q, want tcp only", proto) } if p.FromPort == nil || p.ToPort == nil || *p.FromPort != *p.ToPort || *p.FromPort < 1 || *p.FromPort > 65535 { return nil, fmt.Errorf("outbound rule for ports %d to %d, want one port", aws.ToInt32(p.FromPort), aws.ToInt32(p.ToPort)) } if len(p.PrefixListIds) > 0 || len(p.UserIdGroupPairs) > 0 { return nil, fmt.Errorf("outbound rule to a prefix list or group on port %d, want single hosts", *p.FromPort) } var cidrs []string for _, r := range p.IpRanges { cidrs = append(cidrs, aws.ToString(r.CidrIp)) } for _, r := range p.Ipv6Ranges { cidrs = append(cidrs, aws.ToString(r.CidrIpv6)) } var out []netip.AddrPort for _, c := range cidrs { prefix, err := netip.ParsePrefix(c) if err != nil || !prefix.IsSingleIP() { return nil, fmt.Errorf("outbound rule to %q on port %d, want a single host", c, *p.FromPort) } out = append(out, netip.AddrPortFrom(prefix.Addr(), uint16(*p.FromPort))) } return out, nil }