| 1 | package awsjob |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "net/netip" |
| 7 | "slices" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 10 | "github.com/aws/aws-sdk-go-v2/aws" |
| 11 | "github.com/aws/aws-sdk-go-v2/service/ec2" |
| 12 | ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" |
| 13 | "github.com/aws/aws-sdk-go-v2/service/lambdacore" |
| 14 | coretypes "github.com/aws/aws-sdk-go-v2/service/lambdacore/types" |
| 15 | ) |
| 16 | |
| 17 | // AuditNetwork reads the egress connector and the configured VPC, subnet and |
| 18 | // security group as they are now. First the connector, by its pinned |
| 19 | // version, must be an ACTIVE VPC_EGRESS connector for MicroVMs at that |
| 20 | // version, without service-managed Elastic IP addresses, whose subnets and |
| 21 | // security groups are exactly VMSubnetID and VMSecurityGroupID; so the |
| 22 | // resources audited below are the ones VM traffic uses. Then: |
| 23 | // |
| 24 | // - ResolverDisabled: the VPC has both enableDnsSupport and |
| 25 | // enableDnsHostnames read as false. |
| 26 | // - IngressClosed: the security group has no inbound rules. |
| 27 | // - RouteOutAbsent: the subnet's route table (its own, or the VPC's main |
| 28 | // table when it has none) has only "local" routes. Any other target, |
| 29 | // gateway endpoints included, counts as a route out. |
| 30 | // - EgressOnly: every host and port the security group's outbound rules |
| 31 | // allow. It equals Config.Egress when the group is right. |
| 32 | // |
| 33 | // It returns an error, and the zero audit in which every property has |
| 34 | // failed, when the connector check fails, a read fails, an ID is missing or outside the VPC, or an |
| 35 | // outbound rule allows more than single TCP hosts and ports (a network, a |
| 36 | // port range, another protocol, a prefix list or a group): what it cannot |
| 37 | // establish is never assumed. |
| 38 | func (r *Runner) AuditNetwork(ctx context.Context) (isolatedjob.NetworkAudit, error) { |
| 39 | a, err := r.audit(ctx) |
| 40 | if err != nil { |
| 41 | return isolatedjob.NetworkAudit{}, fmt.Errorf("awsjob: network audit: %w", err) |
| 42 | } |
| 43 | return a, nil |
| 44 | } |
| 45 | |
| 46 | func (r *Runner) audit(ctx context.Context) (isolatedjob.NetworkAudit, error) { |
| 47 | var a isolatedjob.NetworkAudit |
| 48 | if err := r.checkConnector(ctx); err != nil { |
| 49 | return a, err |
| 50 | } |
| 51 | support, err := r.vpcAttribute(ctx, ec2types.VpcAttributeNameEnableDnsSupport) |
| 52 | if err != nil { |
| 53 | return a, err |
| 54 | } |
| 55 | hostnames, err := r.vpcAttribute(ctx, ec2types.VpcAttributeNameEnableDnsHostnames) |
| 56 | if err != nil { |
| 57 | return a, err |
| 58 | } |
| 59 | a.ResolverDisabled = support != nil && !*support && hostnames != nil && !*hostnames |
| 60 | |
| 61 | table, err := r.subnetRouteTable(ctx) |
| 62 | if err != nil { |
| 63 | return a, err |
| 64 | } |
| 65 | a.RouteOutAbsent = table != nil && onlyLocal(table.Routes) |
| 66 | |
| 67 | sgs, err := r.api.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{GroupIds: []string{r.cfg.VMSecurityGroupID}}) |
| 68 | if err != nil { |
| 69 | return a, fmt.Errorf("describe security group %s: %w", r.cfg.VMSecurityGroupID, err) |
| 70 | } |
| 71 | if len(sgs.SecurityGroups) != 1 || aws.ToString(sgs.SecurityGroups[0].VpcId) != r.cfg.VPCID { |
| 72 | return a, fmt.Errorf("security group %s is not one group in %s", r.cfg.VMSecurityGroupID, r.cfg.VPCID) |
| 73 | } |
| 74 | sg := sgs.SecurityGroups[0] |
| 75 | a.IngressClosed = len(sg.IpPermissions) == 0 |
| 76 | for _, p := range sg.IpPermissionsEgress { |
| 77 | dests, err := hostPorts(p) |
| 78 | if err != nil { |
| 79 | return a, fmt.Errorf("security group %s: %w", r.cfg.VMSecurityGroupID, err) |
| 80 | } |
| 81 | for _, d := range dests { |
| 82 | if !slices.Contains(a.EgressOnly, d) { |
| 83 | a.EgressOnly = append(a.EgressOnly, d) |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | return a, nil |
| 88 | } |
| 89 | |
| 90 | // checkConnector establishes that the pinned connector version sends VM |
| 91 | // traffic through exactly the configured subnet and security group. |
| 92 | func (r *Runner) checkConnector(ctx context.Context) error { |
| 93 | id := r.cfg.ConnectorID |
| 94 | out, err := r.api.GetNetworkConnector(ctx, &lambdacore.GetNetworkConnectorInput{Identifier: aws.String(id)}) |
| 95 | if err != nil { |
| 96 | return fmt.Errorf("get network connector %s: %w", id, err) |
| 97 | } |
| 98 | if got := aws.ToString(out.VersionArn); got != id { |
| 99 | return fmt.Errorf("network connector %s answered for version %q, not the pinned one", id, got) |
| 100 | } |
| 101 | if out.State != coretypes.NetworkConnectorStateActive { |
| 102 | return fmt.Errorf("network connector %s is %s, not ACTIVE", id, out.State) |
| 103 | } |
| 104 | vpc, ok := out.Configuration.(*coretypes.NetworkConnectorConfigurationMemberVpcEgressConfiguration) |
| 105 | if !ok { |
| 106 | return fmt.Errorf("network connector %s is not a VPC egress connector (%T)", id, out.Configuration) |
| 107 | } |
| 108 | c := vpc.Value |
| 109 | if !slices.Equal(c.AssociatedComputeResourceTypes, []coretypes.ComputeResourceType{coretypes.ComputeResourceTypeMicroVm}) { |
| 110 | return fmt.Errorf("network connector %s serves %v, want MicroVm only", id, c.AssociatedComputeResourceTypes) |
| 111 | } |
| 112 | if !slices.Equal(c.SubnetIds, []string{r.cfg.VMSubnetID}) { |
| 113 | return fmt.Errorf("network connector %s uses subnets %q, want only %s", id, c.SubnetIds, r.cfg.VMSubnetID) |
| 114 | } |
| 115 | if !slices.Equal(c.SecurityGroupIds, []string{r.cfg.VMSecurityGroupID}) { |
| 116 | return fmt.Errorf("network connector %s uses security groups %q, want only %s", id, c.SecurityGroupIds, r.cfg.VMSecurityGroupID) |
| 117 | } |
| 118 | if e := c.ElasticIpConfiguration; e != nil && e.Type != coretypes.ElasticIpTypeNone { |
| 119 | return fmt.Errorf("network connector %s gives its interfaces %s Elastic IP addresses", id, e.Type) |
| 120 | } |
| 121 | return nil |
| 122 | } |
| 123 | |
| 124 | // vpcAttribute reads one boolean VPC attribute; nil means AWS gave no value. |
| 125 | func (r *Runner) vpcAttribute(ctx context.Context, name ec2types.VpcAttributeName) (*bool, error) { |
| 126 | out, err := r.api.DescribeVpcAttribute(ctx, &ec2.DescribeVpcAttributeInput{VpcId: aws.String(r.cfg.VPCID), Attribute: name}) |
| 127 | if err != nil { |
| 128 | return nil, fmt.Errorf("describe %s of %s: %w", name, r.cfg.VPCID, err) |
| 129 | } |
| 130 | var v *ec2types.AttributeBooleanValue |
| 131 | switch name { |
| 132 | case ec2types.VpcAttributeNameEnableDnsSupport: |
| 133 | v = out.EnableDnsSupport |
| 134 | case ec2types.VpcAttributeNameEnableDnsHostnames: |
| 135 | v = out.EnableDnsHostnames |
| 136 | } |
| 137 | if v == nil { |
| 138 | return nil, nil |
| 139 | } |
| 140 | return v.Value, nil |
| 141 | } |
| 142 | |
| 143 | // subnetRouteTable returns the route table the VM subnet uses: the one |
| 144 | // associated with it, or else the VPC's main table. nil means none was |
| 145 | // found. |
| 146 | func (r *Runner) subnetRouteTable(ctx context.Context) (*ec2types.RouteTable, error) { |
| 147 | subnets, err := r.api.DescribeSubnets(ctx, &ec2.DescribeSubnetsInput{SubnetIds: []string{r.cfg.VMSubnetID}}) |
| 148 | if err != nil { |
| 149 | return nil, fmt.Errorf("describe subnet %s: %w", r.cfg.VMSubnetID, err) |
| 150 | } |
| 151 | if len(subnets.Subnets) != 1 || aws.ToString(subnets.Subnets[0].VpcId) != r.cfg.VPCID { |
| 152 | return nil, fmt.Errorf("subnet %s is not one subnet in %s", r.cfg.VMSubnetID, r.cfg.VPCID) |
| 153 | } |
| 154 | tables, err := r.routeTables(ctx, filter("association.subnet-id", r.cfg.VMSubnetID)) |
| 155 | if err != nil { |
| 156 | return nil, err |
| 157 | } |
| 158 | if len(tables) == 0 { |
| 159 | if tables, err = r.routeTables(ctx, filter("vpc-id", r.cfg.VPCID), filter("association.main", "true")); err != nil { |
| 160 | return nil, err |
| 161 | } |
| 162 | } |
| 163 | switch len(tables) { |
| 164 | case 0: |
| 165 | return nil, nil |
| 166 | case 1: |
| 167 | return &tables[0], nil |
| 168 | } |
| 169 | return nil, fmt.Errorf("subnet %s matches %d route tables", r.cfg.VMSubnetID, len(tables)) |
| 170 | } |
| 171 | |
| 172 | func (r *Runner) routeTables(ctx context.Context, filters ...ec2types.Filter) ([]ec2types.RouteTable, error) { |
| 173 | var tables []ec2types.RouteTable |
| 174 | var token *string |
| 175 | seen := map[string]bool{} |
| 176 | for { |
| 177 | out, err := r.api.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: filters, NextToken: token}) |
| 178 | if err != nil { |
| 179 | return nil, fmt.Errorf("describe route tables: %w", err) |
| 180 | } |
| 181 | tables = append(tables, out.RouteTables...) |
| 182 | next := aws.ToString(out.NextToken) |
| 183 | if next == "" { |
| 184 | return tables, nil |
| 185 | } |
| 186 | if seen[next] { |
| 187 | return nil, fmt.Errorf("describe route tables repeats a page token") |
| 188 | } |
| 189 | seen[next] = true |
| 190 | token = aws.String(next) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | func filter(name, value string) ec2types.Filter { |
| 195 | return ec2types.Filter{Name: aws.String(name), Values: []string{value}} |
| 196 | } |
| 197 | |
| 198 | // onlyLocal reports whether every route stays inside the VPC: target |
| 199 | // "local" and nothing else. |
| 200 | func onlyLocal(routes []ec2types.Route) bool { |
| 201 | for _, rt := range routes { |
| 202 | other := rt.CarrierGatewayId != nil || rt.CoreNetworkArn != nil || rt.EgressOnlyInternetGatewayId != nil || |
| 203 | rt.InstanceId != nil || rt.LocalGatewayId != nil || rt.NatGatewayId != nil || rt.NetworkInterfaceId != nil || |
| 204 | rt.OdbNetworkArn != nil || rt.TransitGatewayId != nil || rt.VpcPeeringConnectionId != nil || rt.IgwFirewall != nil |
| 205 | if aws.ToString(rt.GatewayId) != "local" || other { |
| 206 | return false |
| 207 | } |
| 208 | } |
| 209 | return true |
| 210 | } |
| 211 | |
| 212 | // hostPorts turns one outbound rule into the hosts and port it allows, or |
| 213 | // an error when it allows more than single hosts on one TCP port. |
| 214 | func hostPorts(p ec2types.IpPermission) ([]netip.AddrPort, error) { |
| 215 | proto := aws.ToString(p.IpProtocol) |
| 216 | if proto != "tcp" && proto != "6" { |
| 217 | return nil, fmt.Errorf("outbound rule for protocol %q, want tcp only", proto) |
| 218 | } |
| 219 | if p.FromPort == nil || p.ToPort == nil || *p.FromPort != *p.ToPort || *p.FromPort < 1 || *p.FromPort > 65535 { |
| 220 | return nil, fmt.Errorf("outbound rule for ports %d to %d, want one port", aws.ToInt32(p.FromPort), aws.ToInt32(p.ToPort)) |
| 221 | } |
| 222 | if len(p.PrefixListIds) > 0 || len(p.UserIdGroupPairs) > 0 { |
| 223 | return nil, fmt.Errorf("outbound rule to a prefix list or group on port %d, want single hosts", *p.FromPort) |
| 224 | } |
| 225 | var cidrs []string |
| 226 | for _, r := range p.IpRanges { |
| 227 | cidrs = append(cidrs, aws.ToString(r.CidrIp)) |
| 228 | } |
| 229 | for _, r := range p.Ipv6Ranges { |
| 230 | cidrs = append(cidrs, aws.ToString(r.CidrIpv6)) |
| 231 | } |
| 232 | var out []netip.AddrPort |
| 233 | for _, c := range cidrs { |
| 234 | prefix, err := netip.ParsePrefix(c) |
| 235 | if err != nil || !prefix.IsSingleIP() { |
| 236 | return nil, fmt.Errorf("outbound rule to %q on port %d, want a single host", c, *p.FromPort) |
| 237 | } |
| 238 | out = append(out, netip.AddrPortFrom(prefix.Addr(), uint16(*p.FromPort))) |
| 239 | } |
| 240 | return out, nil |
| 241 | } |
| 242 | |