oficina / equipo Public

awsjob: audit the VM subnet's routes to the proxies over one peering

Config gains PeeringID, ServicesVPCID, ServicesRouteTableID and
ProxyRoutes (each one IPv4 /32). With a peering, RouteOutAbsent holds
only for local routes plus exactly one route to each proxy over the
pinned, active peering, and a services table whose only peering route
is the VM subnet's block back over it. A peering outside the two VPCs,
the connector's account or the region is an error. No peering keeps
slice 1a's local-only audit. The controller config wires the four
optional keys; with a peering, egress must equal the egress manifest's
proxy and bootstrap listeners.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8aa09e2e33bb4089ce40ac4e09542df5be2a46e9 parent 842d4d5
8 files changed, +775 −29
  • cmd/equipo-hosted-controller/config.go +62 −6
  • cmd/equipo-hosted-controller/config_test.go +64 −0
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +24 −0
  • internal/isolatedjob/awsjob/network.go +155 −19
  • internal/isolatedjob/awsjob/network_test.go +402 −0
  • internal/isolatedjob/awsjob/runner.go +60 −0
  • internal/isolatedjob/awsjob/runner_test.go +1 −0
  • internal/isolatedjob/isolatedjob.go +7 −4
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go
index f9bc53fc..f439e098 100644
--- a/cmd/equipo-hosted-controller/config.go
+++ b/cmd/equipo-hosted-controller/config.go
@@ -8,6 +8,7 @@ import (
"net"
"net/netip"
"os"
+ "slices"
"strconv"
"strings"
@@ -23,7 +24,7 @@ import (
// fileConfig is the -config file: one JSON object read with
// hostedwire.DecodeStrict, so an unknown or repeated key is refused. Every
-// field is required.
+// field is required but the four peering keys.
//
// Keys. Each controller has verify keys of its own, and each key stays under
// one key ID for good: the key ID is not signed, so a key reused by another
@@ -54,10 +55,24 @@ type fileConfig struct {
// ConnectorARN is the version-qualified ARN of the VPC_EGRESS connector.
ConnectorARN string `json:"connector_arn"`
// Egress is every "address:port" VMs may reach, as the network audit
- // expects it. Slice 1a has no egress stack, so it must be empty ([]):
- // the VM security group has no outbound rules (ruling R30).
+ // expects it. Without a peering (slice 1a's network) it must be empty
+ // ([]): the VM security group has no outbound rules (ruling R30). With
+ // one it must be exactly the egress manifest's proxy and bootstrap
+ // listeners.
Egress []string `json:"egress"`
SNSTopicARN string `json:"sns_topic_arn"`
+ // PeeringID, ServicesVPCID, ServicesRouteTableID and ProxyRoutes pin
+ // the peered network (decision S2-4): the VM VPC's one VPC peering, to
+ // the services VPC where the proxies run; the services route table that
+ // routes the VM subnet back over it; and one "a.b.c.d/32" route per
+ // proxy address, the addresses egress names. These four keys are the
+ // only optional ones: all four absent or empty keeps slice 1a's
+ // network, whose VM subnet routes nowhere outside its VPC
+ // (awsjob.Config).
+ PeeringID string `json:"peering_id"`
+ ServicesVPCID string `json:"services_vpc_id"`
+ ServicesRouteTableID string `json:"services_route_table_id"`
+ ProxyRoutes []string `json:"proxy_routes"`
// EgressManifestFile is the egress manifest (ctlegress.Load): the exact
// service hosts VMs may reach through the proxies, and the proxies. A
// service named but unset loads, and blocks launches until it is set.
@@ -191,6 +206,11 @@ func (fc fileConfig) check() (config, error) {
if c.ctl.Manifest, err = readManifest(fc.EgressManifestFile); err != nil {
return config{}, err
}
+ if fc.PeeringID != "" {
+ if err := proxyEgress(c.aws.Egress, c.ctl.Manifest); err != nil {
+ return config{}, err
+ }
+ }
c.ctl.Certs, c.ctl.Candidates = ctlcert.NewSet(c.aws.ImageVersion), ctlops.NewCandidates(c.aws.ImageVersion)
c.ctl.Files = ctlops.Files{CertKeys: fc.CertKeysFile, Certificates: fc.CertificatesFile,
CertificationImages: fc.CertificationImagesFile, Operators: fc.OperatorsFile}
@@ -259,6 +279,24 @@ func readPrivate(path, what string) ([]byte, error) {
return raw, nil
}
+// proxyEgress checks that egress is exactly m's proxy and bootstrap
+// listeners, in any order: what the VM security group must allow in the
+// peered network.
+func proxyEgress(egress []netip.AddrPort, m ctlegress.Manifest) error {
+ listeners := append(slices.Clone(m.Proxies), m.ProxyBoot...)
+ for _, e := range egress {
+ if !slices.Contains(listeners, e) {
+ return fmt.Errorf("egress %s is not a proxy listener in the egress manifest", e)
+ }
+ }
+ for _, l := range listeners {
+ if !slices.Contains(egress, l) {
+ return fmt.Errorf("egress lacks the egress manifest's proxy listener %s", l)
+ }
+ }
+ return nil
+}
+
// readManifest reads and checks the egress manifest at path.
func readManifest(path string) (ctlegress.Manifest, error) {
raw, err := os.ReadFile(path)
@@ -336,7 +374,8 @@ func verifyKeys(entries []keyEntry) (map[hostedwire.KeyID]hostedwire.VerifyKey,
// which makes no provider call; main builds the real Runner later.
func (fc fileConfig) awsConfig() (awsjob.Config, error) {
ac := awsjob.Config{Region: fc.Region, ConnectorID: fc.ConnectorARN, VPCID: fc.VPCID, VMSubnetID: fc.VMSubnetID,
- VMSecurityGroupID: fc.VMSecurityGroupID, Images: map[isolatedjob.ImageDigest]awsjob.Image{}}
+ VMSecurityGroupID: fc.VMSecurityGroupID, Images: map[isolatedjob.ImageDigest]awsjob.Image{},
+ PeeringID: fc.PeeringID, ServicesVPCID: fc.ServicesVPCID, ServicesRouteTableID: fc.ServicesRouteTableID}
for _, img := range fc.Images {
d := isolatedjob.ImageDigest(img.Digest)
if !validDigest(img.Digest) {
@@ -351,8 +390,25 @@ func (fc fileConfig) awsConfig() (awsjob.Config, error) {
}
ac.Images[d] = awsjob.Image{ARN: img.ARN, Versions: versions}
}
- if len(fc.Egress) > 0 {
- return awsjob.Config{}, fmt.Errorf("egress lists %d destinations; slice 1a has no egress stack, so it must be empty", len(fc.Egress))
+ if fc.PeeringID == "" && len(fc.Egress) > 0 {
+ return awsjob.Config{}, fmt.Errorf("egress lists %d destinations; without a peering there is no egress stack, so it must be empty", len(fc.Egress))
+ }
+ for _, e := range fc.Egress {
+ ap, err := netip.ParseAddrPort(e)
+ if err != nil {
+ return awsjob.Config{}, fmt.Errorf("egress %q is not address:port", e)
+ }
+ if slices.Contains(ac.Egress, ap) {
+ return awsjob.Config{}, fmt.Errorf("egress %s is listed twice", ap)
+ }
+ ac.Egress = append(ac.Egress, ap)
+ }
+ for _, r := range fc.ProxyRoutes {
+ p, err := netip.ParsePrefix(r)
+ if err != nil {
+ return awsjob.Config{}, fmt.Errorf("proxy route %q is not address/32", r)
+ }
+ ac.ProxyRoutes = append(ac.ProxyRoutes, p)
}
if _, err := awsjob.New(ac, awsjob.NewAPI(nil, nil, nil)); err != nil {
return awsjob.Config{}, err
diff --git a/cmd/equipo-hosted-controller/config_test.go b/cmd/equipo-hosted-controller/config_test.go
index e971a7bc..39056ba6 100644
--- a/cmd/equipo-hosted-controller/config_test.go
+++ b/cmd/equipo-hosted-controller/config_test.go
@@ -6,6 +6,7 @@ import (
"encoding/base64"
"encoding/json"
"errors"
+ "net/netip"
"os"
"path/filepath"
"reflect"
@@ -490,3 +491,66 @@ func TestConfigEnabledOnlyFromEnv(t *testing.T) {
t.Errorf("config with \"enabled\": loaded %v, Enabled %v; want a refusal", err == nil, c.ctl.Enabled)
}
}
+
+// TestConfigPeeredNetwork: the peered network's four keys (decision S2-4)
+// reach the adapter, and with them egress must be exactly the egress
+// manifest's proxy and bootstrap listeners. Without them slice 1a's rule
+// stands: egress empty ("egress in slice 1a" above).
+func TestConfigPeeredNetwork(t *testing.T) {
+ t.Parallel()
+ peered := func(t *testing.T, dir string) fileConfig {
+ t.Helper()
+ fc := validConfig(t, dir)
+ two := `{"services":{"instance":{"host":"equipo.example.com","port":443,"class":"instance"}},` +
+ `"proxies":["10.42.1.10:8443","10.42.2.10:8443"],"proxy_boot":["10.42.1.10:8444","10.42.2.10:8444"],` +
+ `"proxy_ca_pin":"` + testPin + `"}`
+ if err := os.WriteFile(fc.EgressManifestFile, []byte(two), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ fc.PeeringID, fc.ServicesVPCID, fc.ServicesRouteTableID = "pcx-1", "vpc-svc", "rtb-svc"
+ fc.ProxyRoutes = []string{"10.42.1.10/32", "10.42.2.10/32"}
+ fc.Egress = []string{"10.42.2.10:8444", "10.42.1.10:8443", "10.42.1.10:8444", "10.42.2.10:8443"}
+ return fc
+ }
+
+ dir := t.TempDir()
+ c, err := loadFC(t, dir, peered(t, dir))
+ if err != nil {
+ t.Fatalf("peered config: %v", err)
+ }
+ if c.aws.PeeringID != "pcx-1" || c.aws.ServicesVPCID != "vpc-svc" || c.aws.ServicesRouteTableID != "rtb-svc" {
+ t.Errorf("adapter peering = %q, %q, %q", c.aws.PeeringID, c.aws.ServicesVPCID, c.aws.ServicesRouteTableID)
+ }
+ if want := []netip.Prefix{netip.MustParsePrefix("10.42.1.10/32"), netip.MustParsePrefix("10.42.2.10/32")}; !reflect.DeepEqual(c.aws.ProxyRoutes, want) {
+ t.Errorf("adapter proxy routes = %v, want %v", c.aws.ProxyRoutes, want)
+ }
+ want := []netip.AddrPort{netip.MustParseAddrPort("10.42.2.10:8444"), netip.MustParseAddrPort("10.42.1.10:8443"),
+ netip.MustParseAddrPort("10.42.1.10:8444"), netip.MustParseAddrPort("10.42.2.10:8443")}
+ if !reflect.DeepEqual(c.aws.Egress, want) || !reflect.DeepEqual(c.ctl.Egress, want) {
+ t.Errorf("egress: adapter %v, controller %v; want %v in both", c.aws.Egress, c.ctl.Egress, want)
+ }
+
+ for name, edit := range map[string]func(*fileConfig){
+ "a /24 proxy route": func(f *fileConfig) { f.ProxyRoutes[0] = "10.42.1.0/24" },
+ "a proxy route with no length": func(f *fileConfig) { f.ProxyRoutes[0] = "10.42.1.10" },
+ "a proxy route that is a name": func(f *fileConfig) { f.ProxyRoutes[0] = "proxy-a/32" },
+ "a proxy with no route": func(f *fileConfig) { f.ProxyRoutes = f.ProxyRoutes[:1] },
+ "no services route table": func(f *fileConfig) { f.ServicesRouteTableID = "" },
+ "no services VPC": func(f *fileConfig) { f.ServicesVPCID = "" },
+ "services VPC the VM VPC": func(f *fileConfig) { f.ServicesVPCID = f.VPCID },
+ "routes without a peering": func(f *fileConfig) { f.PeeringID = "" },
+ "no egress": func(f *fileConfig) { f.Egress = []string{} },
+ "a bootstrap listener missing": func(f *fileConfig) { f.Egress = f.Egress[:3] },
+ "egress to another port": func(f *fileConfig) { f.Egress[0] = "10.42.2.10:9000" },
+ "egress listed twice": func(f *fileConfig) { f.Egress = append(f.Egress, f.Egress[0]) },
+ "egress that is not host:port": func(f *fileConfig) { f.Egress[0] = "10.42.2.10" },
+ "egress to an unrouted address": func(f *fileConfig) { f.Egress[0] = "10.42.3.10:8444" },
+ } {
+ sub := t.TempDir()
+ fc := peered(t, sub)
+ edit(&fc)
+ if _, err := loadFC(t, sub, fc); err == nil {
+ t.Errorf("%s: config loaded, want a refusal", name)
+ }
+ }
+}
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 360dd681..5ceacff1 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -406,3 +406,27 @@ Mutation checks (each applied by script, `CGO_ENABLED=0 go test ./internal/vmini
61. No stop-intent check. TestTerminateDuringLaunch: FAIL, `before_the_runner_exists: init_test.go:592: /run = 200, want 409`, `init_test.go:597: launches 1, signals []; want none`. Restored.
Also run: `go test ./internal/vminit -count=1` ok (23 tests); `-count=20` ok (4.2 s); `-race` once ok (3.4 s); `GOOS=linux go build ./cmd/equipo-vm-init` ok; staticcheck v0.7.0 clean; gofmt clean; `git diff --check` clean; `make budget build vet` ok (`internal/vminit` 1455 source and 1266 test lines).
+
+## Task 9
+
+The network audit accepts exactly the peered topology (decision S2-4). `awsjob.Config` gains `PeeringID`, `ServicesVPCID`, `ServicesRouteTableID` and `ProxyRoutes []netip.Prefix`; all four empty keeps slice 1a's local-only audit (every existing audit test unchanged and passing). `EC2API` gains `DescribeVpcPeeringConnections` only (the services table is read through the existing `DescribeRouteTables`, filter `route-table-id`). With a peering, `RouteOutAbsent` holds only when the VM subnet's table has local routes plus exactly one route to each configured `/32` over the pinned peering (nothing else, none missing), the peering is `active`, and the services table's only route over any peering is the VM subnet's IPv4 block over the same one. Errors (the zero audit): the peering not one answer for the pinned ID, not between the VM VPC and the services VPC (either way round), a side not in the connector ARN's account or the configured region; the services table not one table in the services VPC; the VM subnet without an IPv4 block. `New` refuses a partial peering config, a services VPC equal to the VM VPC, a proxy route that is not one IPv4 `/32`, a duplicate route, and (peered only) egress addresses not exactly the proxy routes' addresses. The controller config gains optional `peering_id`, `services_vpc_id`, `services_route_table_id` and `proxy_routes`; without a peering, egress must still be empty; with one, egress must be exactly the egress manifest's `proxies` and `proxy_boot` listeners (four entries for two proxies). `NetworkAudit.RouteOutAbsent`'s doc now states the peered meaning; no new field, so hostedctl is untouched.
+
+RED: first a build failure (`c.PeeringID undefined` and the rest, `network_test.go:477`); then, with only the fields and the interface method added, `CGO_ENABLED=0 go test ./internal/isolatedjob/... -run 'TestAudit' -count=1` FAIL: TestAuditAcceptsPinnedPeering (`RouteOutAbsent:false`, `the peering was not read`), TestAuditRefusesMissingProxyRoute (`RouteOutAbsent:true ... the audit passes`, from the stub default), TestAuditRefusesInactivePeering (12 error subtests: `want an error`), TestAuditRefusesMissingReturnRoute (4 error subtests), TestAuditPeeringConfig (16 cases `New = <nil>, want ErrInvalid`). TestAuditRefusesOtherPeeringRoute and the inactive-state subtests passed at RED because slice 1a's `onlyLocal` refuses every peering route; they bite once a peering route can be accepted (mutations 1 and 2). Controller: `go test ./cmd/equipo-hosted-controller -run TestConfigPeeredNetwork` FAIL, `peered config: ... egress lists 4 destinations; slice 1a has no egress stack, so it must be empty`.
+
+GREEN: `CGO_ENABLED=0 go test ./internal/isolatedjob/... -run 'TestAudit' -count=1` ok.
+
+Mutation checks (each applied by script, the named test run with `CGO_ENABLED=0 go test <pkg> -run '^<Test>$' -count=1`, the file restored and checked by SHA-256):
+
+1. Accept any route via the peering (`proxyRoutesOnly`: `if !ok || !slices.Contains(proxies, dest)` became `if aws.ToString(rt.VpcPeeringConnectionId) != peering`). TestAuditRefusesOtherPeeringRoute: FAIL in `a /24 over the same peering`, `a /32 to an address not a proxy`, `the default route over the peering`, `an ipv6 route over the peering`, `a prefix list over the peering`, `a /32 over the peering with a second target`, each `network_test.go:643: AuditNetwork = {... RouteOutAbsent:true ...}, want {... RouteOutAbsent:false ...} (the route out present)` and `the audit passes`. Restored.
+2. Peering state ignored (`return true, nil`). TestAuditRefusesInactivePeering: FAIL for `pending-acceptance`, `provisioning`, `deleted`, ... (`network_test.go:687: ... RouteOutAbsent:true ...`, `the audit passes`). Restored.
+3. Return route not judged (`returnRouteOnly(...)` became `true`). TestAuditRefusesMissingReturnRoute: FAIL, `no return route`, `return route over another peering`, `return route to the whole VM VPC`, ... (`network_test.go:749`, `:754`: `the audit passes`). Restored.
+4. Return route to any destination (`dest != vm` became `!dest.IsValid()`). TestAuditRefusesMissingReturnRoute: FAIL, `return_route_to_the_whole_VM_VPC: network_test.go:759: ... RouteOutAbsent:true ...`, `the audit passes`. Restored. (The first form, `if !ok {`, did not compile and was redone.)
+5. Peering VPC pair unchecked (`if false {`). TestAuditRefusesInactivePeering: FAIL, `to another VPC`, `from another VPC`, `the VM VPC to itself`: `network_test.go:716: AuditNetwork = {...}, nil; want an error`. Restored.
+6. Peering account and region unchecked. TestAuditRefusesInactivePeering: FAIL, `owner unknown`, `accepter in another account`, `requester in another account`, `accepter in another region` (`network_test.go:716: ... want an error`). Restored.
+7. Missing proxy route allowed (`seen[p] != 1` became `seen[p] > 1`). TestAuditRefusesMissingProxyRoute: FAIL, `network_test.go:667` and `:671`: `RouteOutAbsent:true ...`, `the audit passes`. Restored.
+8. Proxy route wider than /32 accepted (`p.Bits() != 32` dropped). TestAuditPeeringConfig: FAIL, `network_test.go:860: a /31 proxy route: New = <nil>, want ErrInvalid`. The `/24` case still refused, by the egress-address check (its network address is not an egress address). Restored.
+9. Egress not checked against the proxy routes (`if !routed[e.Addr()]` became `if false`). TestAuditPeeringConfig: FAIL, `egress to an unrouted address: New = <nil>, want ErrInvalid`. Restored.
+10. Controller egress not checked against the manifest (`if fc.PeeringID != ""` before `proxyEgress` became `if false`). TestConfigPeeredNetwork: FAIL, `config_test.go:553: a bootstrap listener missing: config loaded, want a refusal`, `egress to another port: config loaded, want a refusal`. Restored.
+11. Controller egress allowed without a peering (`if false && len(fc.Egress) > 0`). TestConfigRefusesMissingListenOrKeys: FAIL, `config_test.go:390: egress in slice 1a: config loaded, want a refusal`. Restored.
+
+Also run: `CGO_ENABLED=0 go test ./internal/isolatedjob/... ./cmd/equipo-hosted-controller -count=1` ok; `go vet -tags hostedlive ./internal/isolatedjob/...` ok; `make budget build vet` ok (129 directories within budget); staticcheck v0.7.0 clean on both packages; gofmt and `git diff --check` clean.
diff --git a/internal/isolatedjob/awsjob/network.go b/internal/isolatedjob/awsjob/network.go
index 5efeaf82..c755446b 100644
--- a/internal/isolatedjob/awsjob/network.go
+++ b/internal/isolatedjob/awsjob/network.go
@@ -26,14 +26,24 @@ import (
// - 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.
+// gateway endpoints included, counts as a route out. In the peered
+// network (Config.PeeringID set, decision S2-4) the table may also hold,
+// for each of Config.ProxyRoutes, exactly one route to it over the
+// pinned peering, and must hold every one of them; the peering must be
+// active; and the services route table must route the VM subnet's IPv4
+// block back over the same peering and nothing else over any peering.
+// Anything else, a missing route included, fails this property.
// - 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
+// port range, another protocol, a prefix list or a group). In the peered
+// network it also does so when the peering is not the one configured
+// between the VM VPC and the services VPC with both sides in this account
+// (the connector's) and region, the services route table is not one table
+// in the services VPC, or the VM subnet has no IPv4 block: what it cannot
// establish is never assumed.
func (r *Runner) AuditNetwork(ctx context.Context) (isolatedjob.NetworkAudit, error) {
a, err := r.audit(ctx)
@@ -58,11 +68,15 @@ func (r *Runner) audit(ctx context.Context) (isolatedjob.NetworkAudit, error) {
}
a.ResolverDisabled = support != nil && !*support && hostnames != nil && !*hostnames
- table, err := r.subnetRouteTable(ctx)
+ subnet, table, err := r.subnetRouteTable(ctx)
if err != nil {
return a, err
}
- a.RouteOutAbsent = table != nil && onlyLocal(table.Routes)
+ if r.cfg.PeeringID == "" {
+ a.RouteOutAbsent = table != nil && onlyLocal(table.Routes)
+ } else if a.RouteOutAbsent, err = r.peeredRoutes(ctx, subnet, table); err != nil {
+ return a, err
+ }
sgs, err := r.api.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{GroupIds: []string{r.cfg.VMSecurityGroupID}})
if err != nil {
@@ -140,33 +154,89 @@ func (r *Runner) vpcAttribute(ctx context.Context, name ec2types.VpcAttributeNam
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) {
+// subnetRouteTable returns the VM subnet and the route table it uses: the
+// one associated with it, or else the VPC's main table. A nil table means
+// none was found.
+func (r *Runner) subnetRouteTable(ctx context.Context) (ec2types.Subnet, *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)
+ return ec2types.Subnet{}, 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)
+ return ec2types.Subnet{}, nil, fmt.Errorf("subnet %s is not one subnet in %s", r.cfg.VMSubnetID, r.cfg.VPCID)
}
+ subnet := subnets.Subnets[0]
tables, err := r.routeTables(ctx, filter("association.subnet-id", r.cfg.VMSubnetID))
if err != nil {
- return nil, err
+ return subnet, 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
+ return subnet, nil, err
}
}
switch len(tables) {
case 0:
- return nil, nil
+ return subnet, nil, nil
case 1:
- return &tables[0], nil
+ return subnet, &tables[0], nil
+ }
+ return subnet, nil, fmt.Errorf("subnet %s matches %d route tables", r.cfg.VMSubnetID, len(tables))
+}
+
+// peeredRoutes reports whether the peered network holds (see AuditNetwork,
+// RouteOutAbsent): the VM table routes only locally and to each proxy over
+// the pinned peering, the peering is active, and the services table's only
+// route over a peering is the one back to the VM subnet over this one.
+func (r *Runner) peeredRoutes(ctx context.Context, subnet ec2types.Subnet, table *ec2types.RouteTable) (bool, error) {
+ vm, err := netip.ParsePrefix(aws.ToString(subnet.CidrBlock))
+ if err != nil || !vm.Addr().Is4() {
+ return false, fmt.Errorf("subnet %s has no IPv4 block (%q)", r.cfg.VMSubnetID, aws.ToString(subnet.CidrBlock))
+ }
+ active, err := r.peeringActive(ctx)
+ if err != nil {
+ return false, err
+ }
+ services, err := r.routeTables(ctx, filter("route-table-id", r.cfg.ServicesRouteTableID))
+ if err != nil {
+ return false, err
+ }
+ if len(services) != 1 || aws.ToString(services[0].RouteTableId) != r.cfg.ServicesRouteTableID ||
+ aws.ToString(services[0].VpcId) != r.cfg.ServicesVPCID {
+ return false, fmt.Errorf("route table %s is not one table in %s", r.cfg.ServicesRouteTableID, r.cfg.ServicesVPCID)
+ }
+ return active && table != nil && proxyRoutesOnly(table.Routes, r.cfg.PeeringID, r.cfg.ProxyRoutes) &&
+ returnRouteOnly(services[0].Routes, r.cfg.PeeringID, vm), nil
+}
+
+// peeringActive reads the pinned peering. It is an error for it not to be
+// one peering between the VM VPC and the services VPC, either way round,
+// with both sides in this account and region; then it reports whether the
+// peering is active.
+func (r *Runner) peeringActive(ctx context.Context) (bool, error) {
+ id := r.cfg.PeeringID
+ out, err := r.api.DescribeVpcPeeringConnections(ctx, &ec2.DescribeVpcPeeringConnectionsInput{VpcPeeringConnectionIds: []string{id}})
+ if err != nil {
+ return false, fmt.Errorf("describe peering %s: %w", id, err)
+ }
+ if len(out.VpcPeeringConnections) != 1 || aws.ToString(out.VpcPeeringConnections[0].VpcPeeringConnectionId) != id {
+ return false, fmt.Errorf("peering %s is not one peering", id)
+ }
+ p := out.VpcPeeringConnections[0]
+ if p.RequesterVpcInfo == nil || p.AccepterVpcInfo == nil {
+ return false, fmt.Errorf("peering %s has no requester or accepter", id)
+ }
+ ends := []string{aws.ToString(p.RequesterVpcInfo.VpcId), aws.ToString(p.AccepterVpcInfo.VpcId)}
+ if !slices.Equal(ends, []string{r.cfg.VPCID, r.cfg.ServicesVPCID}) && !slices.Equal(ends, []string{r.cfg.ServicesVPCID, r.cfg.VPCID}) {
+ return false, fmt.Errorf("peering %s joins %q, want %s and %s", id, ends, r.cfg.VPCID, r.cfg.ServicesVPCID)
}
- return nil, fmt.Errorf("subnet %s matches %d route tables", r.cfg.VMSubnetID, len(tables))
+ for _, side := range []*ec2types.VpcPeeringConnectionVpcInfo{p.RequesterVpcInfo, p.AccepterVpcInfo} {
+ if owner, region := aws.ToString(side.OwnerId), aws.ToString(side.Region); owner != r.cfg.account() || region != r.cfg.Region {
+ return false, fmt.Errorf("peering %s has %s in account %q, region %q; want %s in %s",
+ id, aws.ToString(side.VpcId), owner, region, r.cfg.account(), r.cfg.Region)
+ }
+ }
+ return p.Status != nil && p.Status.Code == ec2types.VpcPeeringConnectionStateReasonCodeActive, nil
}
func (r *Runner) routeTables(ctx context.Context, filters ...ec2types.Filter) ([]ec2types.RouteTable, error) {
@@ -199,16 +269,82 @@ func filter(name, value string) ec2types.Filter {
// "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 {
+ if !local(rt) {
return false
}
}
return true
}
+func local(rt ec2types.Route) bool {
+ return aws.ToString(rt.GatewayId) == "local" && rt.VpcPeeringConnectionId == nil && !otherTarget(rt)
+}
+
+// otherTarget reports whether rt has a target besides a gateway and a
+// peering.
+func otherTarget(rt ec2types.Route) bool {
+ return 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.IgwFirewall != nil
+}
+
+// overPeering returns the IPv4 destination of rt when its only target is
+// peering and its destination one IPv4 block; ok is false for any other
+// route.
+func overPeering(rt ec2types.Route, peering string) (dest netip.Prefix, ok bool) {
+ if aws.ToString(rt.VpcPeeringConnectionId) != peering || rt.GatewayId != nil || otherTarget(rt) ||
+ rt.DestinationIpv6CidrBlock != nil || rt.DestinationPrefixListId != nil {
+ return netip.Prefix{}, false
+ }
+ dest, err := netip.ParsePrefix(aws.ToString(rt.DestinationCidrBlock))
+ if err != nil || !dest.Addr().Is4() || dest != dest.Masked() {
+ return netip.Prefix{}, false
+ }
+ return dest, true
+}
+
+// proxyRoutesOnly reports whether routes are local routes and, for each
+// proxy prefix, exactly one route to it over peering: no other route, and
+// none missing.
+func proxyRoutesOnly(routes []ec2types.Route, peering string, proxies []netip.Prefix) bool {
+ seen := map[netip.Prefix]int{}
+ for _, rt := range routes {
+ if local(rt) {
+ continue
+ }
+ dest, ok := overPeering(rt, peering)
+ if !ok || !slices.Contains(proxies, dest) {
+ return false
+ }
+ seen[dest]++
+ }
+ for _, p := range proxies {
+ if seen[p] != 1 {
+ return false
+ }
+ }
+ return true
+}
+
+// returnRouteOnly reports whether the services table's routes over any
+// peering are exactly one: to the VM subnet's block vm over peering.
+// Routes with no peering (local, the internet gateway) are the services
+// VPC's own and not judged here.
+func returnRouteOnly(routes []ec2types.Route, peering string, vm netip.Prefix) bool {
+ found := 0
+ for _, rt := range routes {
+ if rt.VpcPeeringConnectionId == nil {
+ continue
+ }
+ dest, ok := overPeering(rt, peering)
+ if !ok || dest != vm {
+ return false
+ }
+ found++
+ }
+ return found == 1
+}
+
// 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) {
diff --git a/internal/isolatedjob/awsjob/network_test.go b/internal/isolatedjob/awsjob/network_test.go
index 34567786..529d636f 100644
--- a/internal/isolatedjob/awsjob/network_test.go
+++ b/internal/isolatedjob/awsjob/network_test.go
@@ -459,3 +459,405 @@ func TestAuditNetwork(t *testing.T) {
})
}
}
+
+func (s *stub) DescribeVpcPeeringConnections(_ context.Context, in *ec2.DescribeVpcPeeringConnectionsInput, _ ...func(*ec2.Options)) (*ec2.DescribeVpcPeeringConnectionsOutput, error) {
+ s.record("DescribeVpcPeeringConnections")
+ if s.peerings != nil {
+ return s.peerings(in)
+ }
+ return nil, errors.New("no peering in slice 1a's network")
+}
+
+// The peered network (decision S2-4): the VM VPC vpc-1, its subnet
+// 10.0.0.0/24, two proxies at 10.42.1.10 and 10.42.2.10 in the services
+// VPC vpc-svc, and the one peering pcx-1 between them.
+
+func peeredConfig() Config {
+ c := testConfig()
+ c.PeeringID, c.ServicesVPCID, c.ServicesRouteTableID = "pcx-1", "vpc-svc", "rtb-svc"
+ c.ProxyRoutes = []netip.Prefix{netip.MustParsePrefix("10.42.1.10/32"), netip.MustParsePrefix("10.42.2.10/32")}
+ c.Egress = []netip.AddrPort{
+ netip.MustParseAddrPort("10.42.1.10:8443"), netip.MustParseAddrPort("10.42.2.10:8443"),
+ netip.MustParseAddrPort("10.42.1.10:8444"), netip.MustParseAddrPort("10.42.2.10:8444"),
+ }
+ return c
+}
+
+func peerRoute(dest, peering string) ec2types.Route {
+ return ec2types.Route{DestinationCidrBlock: aws.String(dest), VpcPeeringConnectionId: aws.String(peering)}
+}
+
+// peeredNet is the peered network as peeredConfig expects it; a test
+// changes a field before building its stub.
+type peeredNet struct {
+ vmRoutes []ec2types.Route // the VM subnet's table
+ svcRoutes []ec2types.Route // the services route table
+ peering ec2types.VpcPeeringConnection
+}
+
+func goodPeeredNet() *peeredNet {
+ return &peeredNet{
+ vmRoutes: []ec2types.Route{
+ {DestinationCidrBlock: aws.String("10.0.0.0/16"), GatewayId: aws.String("local")},
+ peerRoute("10.42.1.10/32", "pcx-1"),
+ peerRoute("10.42.2.10/32", "pcx-1"),
+ },
+ svcRoutes: []ec2types.Route{
+ {DestinationCidrBlock: aws.String("10.42.0.0/16"), GatewayId: aws.String("local")},
+ {DestinationCidrBlock: aws.String("0.0.0.0/0"), GatewayId: aws.String("igw-svc")},
+ peerRoute("10.0.0.0/24", "pcx-1"),
+ },
+ peering: ec2types.VpcPeeringConnection{
+ VpcPeeringConnectionId: aws.String("pcx-1"),
+ Status: &ec2types.VpcPeeringConnectionStateReason{Code: ec2types.VpcPeeringConnectionStateReasonCodeActive},
+ RequesterVpcInfo: &ec2types.VpcPeeringConnectionVpcInfo{VpcId: aws.String("vpc-1"), OwnerId: aws.String("123456789012"), Region: aws.String("eu-west-1")},
+ AccepterVpcInfo: &ec2types.VpcPeeringConnectionVpcInfo{VpcId: aws.String("vpc-svc"), OwnerId: aws.String("123456789012"), Region: aws.String("eu-west-1")},
+ },
+ }
+}
+
+func (n *peeredNet) stub() *stub {
+ return &stub{
+ subnets: func(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error) {
+ return &ec2.DescribeSubnetsOutput{Subnets: []ec2types.Subnet{{SubnetId: aws.String("subnet-1"), VpcId: aws.String("vpc-1"),
+ CidrBlock: aws.String("10.0.0.0/24")}}}, nil
+ },
+ routeTables: func(in *ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ switch {
+ case filterValue(in.Filters, "association.subnet-id") == "subnet-1":
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{{RouteTableId: aws.String("rtb-1"),
+ VpcId: aws.String("vpc-1"), Routes: n.vmRoutes}}}, nil
+ case filterValue(in.Filters, "route-table-id") == "rtb-svc":
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{{RouteTableId: aws.String("rtb-svc"),
+ VpcId: aws.String("vpc-svc"), Routes: n.svcRoutes}}}, nil
+ }
+ return &ec2.DescribeRouteTablesOutput{}, nil
+ },
+ securityGroups: func(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) {
+ g := goodGroup()
+ g.IpPermissionsEgress = []ec2types.IpPermission{
+ hostRule(8443, "10.42.1.10/32", "10.42.2.10/32"),
+ hostRule(8444, "10.42.1.10/32", "10.42.2.10/32"),
+ }
+ return &ec2.DescribeSecurityGroupsOutput{SecurityGroups: []ec2types.SecurityGroup{g}}, nil
+ },
+ peerings: func(in *ec2.DescribeVpcPeeringConnectionsInput) (*ec2.DescribeVpcPeeringConnectionsOutput, error) {
+ if !reflect.DeepEqual(in.VpcPeeringConnectionIds, []string{"pcx-1"}) {
+ return &ec2.DescribeVpcPeeringConnectionsOutput{}, nil
+ }
+ return &ec2.DescribeVpcPeeringConnectionsOutput{VpcPeeringConnections: []ec2types.VpcPeeringConnection{n.peering}}, nil
+ },
+ }
+}
+
+// auditPeered runs the audit of n under peeredConfig.
+func auditPeered(t *testing.T, n *peeredNet) (isolatedjob.NetworkAudit, error) {
+ t.Helper()
+ r, err := New(peeredConfig(), n.stub())
+ if err != nil {
+ t.Fatalf("New(peered) = %v", err)
+ }
+ return r.AuditNetwork(context.Background())
+}
+
+// wantRouteOut checks that the audit of n read everything and failed on
+// its routes alone: so OK refuses it, naming the route out.
+func wantRouteOut(t *testing.T, n *peeredNet) {
+ t.Helper()
+ got, err := auditPeered(t, n)
+ if err != nil {
+ t.Fatalf("AuditNetwork = %v, want a reading", err)
+ }
+ want := isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, EgressOnly: peeredConfig().Egress}
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("AuditNetwork = %+v, want %+v (the route out present)", got, want)
+ }
+ if got.OK(peeredConfig().Egress) == nil {
+ t.Error("the audit passes")
+ }
+}
+
+// wantError checks that the audit of n fails to establish the network:
+// an error and the zero audit.
+func wantError(t *testing.T, n *peeredNet) {
+ t.Helper()
+ got, err := auditPeered(t, n)
+ if err == nil {
+ t.Fatalf("AuditNetwork = %+v, nil; want an error", got)
+ }
+ if !reflect.DeepEqual(got, isolatedjob.NetworkAudit{}) {
+ t.Errorf("AuditNetwork with an error = %+v, want the zero audit", got)
+ }
+}
+
+func TestAuditAcceptsPinnedPeering(t *testing.T) {
+ n := goodPeeredNet()
+ s := n.stub()
+ r, err := New(peeredConfig(), s)
+ if err != nil {
+ t.Fatalf("New(peered) = %v", err)
+ }
+ got, err := r.AuditNetwork(context.Background())
+ if err != nil {
+ t.Fatalf("AuditNetwork = %v", err)
+ }
+ want := peeredConfig().Egress
+ if !reflect.DeepEqual(got, isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true, EgressOnly: want}) {
+ t.Errorf("AuditNetwork = %+v, want every property held and the four proxy listeners", got)
+ }
+ if err := got.OK(want); err != nil {
+ t.Errorf("OK = %v", err)
+ }
+ if !slices.Contains(s.calls, "DescribeVpcPeeringConnections") {
+ t.Errorf("calls %v: the peering was not read", s.calls)
+ }
+
+ // Either side may have asked for the peering, and the proxy routes may
+ // come in any order.
+ n = goodPeeredNet()
+ n.peering.RequesterVpcInfo, n.peering.AccepterVpcInfo = n.peering.AccepterVpcInfo, n.peering.RequesterVpcInfo
+ n.vmRoutes[1], n.vmRoutes[2] = n.vmRoutes[2], n.vmRoutes[1]
+ if got, err := auditPeered(t, n); err != nil || got.OK(want) != nil {
+ t.Errorf("accepted by the VM VPC, routes reordered: (%+v, %v)", got, err)
+ }
+}
+
+func TestAuditRefusesOtherPeeringRoute(t *testing.T) {
+ for name, route := range map[string]ec2types.Route{
+ "a /24 over the same peering": peerRoute("10.42.1.0/24", "pcx-1"),
+ "a /32 to an address not a proxy": peerRoute("10.42.1.11/32", "pcx-1"),
+ "a second peering": peerRoute("10.42.1.10/32", "pcx-2"),
+ "another network over a second peering": peerRoute("172.16.0.0/12", "pcx-2"),
+ "the default route over the peering": peerRoute("0.0.0.0/0", "pcx-1"),
+ "an ipv6 route over the peering": {DestinationIpv6CidrBlock: aws.String("2001:db8::/64"),
+ VpcPeeringConnectionId: aws.String("pcx-1")},
+ "a prefix list over the peering": {DestinationPrefixListId: aws.String("pl-1"),
+ VpcPeeringConnectionId: aws.String("pcx-1")},
+ "a /32 over the peering with a second target": {DestinationCidrBlock: aws.String("10.42.3.10/32"),
+ VpcPeeringConnectionId: aws.String("pcx-1"), TransitGatewayId: aws.String("tgw-1")},
+ "an internet gateway": {DestinationCidrBlock: aws.String("0.0.0.0/0"), GatewayId: aws.String("igw-1")},
+ } {
+ t.Run(name, func(t *testing.T) {
+ n := goodPeeredNet()
+ n.vmRoutes = append(n.vmRoutes, route)
+ wantRouteOut(t, n)
+ })
+ }
+ t.Run("a proxy route twice", func(t *testing.T) {
+ n := goodPeeredNet()
+ n.vmRoutes = append(n.vmRoutes, peerRoute("10.42.1.10/32", "pcx-1"))
+ wantRouteOut(t, n)
+ })
+ t.Run("a proxy route with a second target", func(t *testing.T) {
+ n := goodPeeredNet()
+ n.vmRoutes[1].NatGatewayId = aws.String("nat-1")
+ wantRouteOut(t, n)
+ })
+ t.Run("a proxy route over another peering", func(t *testing.T) {
+ n := goodPeeredNet()
+ n.vmRoutes[1] = peerRoute("10.42.1.10/32", "pcx-2")
+ wantRouteOut(t, n)
+ })
+}
+
+func TestAuditRefusesMissingProxyRoute(t *testing.T) {
+ for i := range 2 {
+ n := goodPeeredNet()
+ n.vmRoutes = slices.Delete(n.vmRoutes, i+1, i+2)
+ wantRouteOut(t, n)
+ }
+ n := goodPeeredNet()
+ n.vmRoutes = n.vmRoutes[:1]
+ wantRouteOut(t, n)
+}
+
+func TestAuditRefusesInactivePeering(t *testing.T) {
+ for _, code := range []ec2types.VpcPeeringConnectionStateReasonCode{
+ ec2types.VpcPeeringConnectionStateReasonCodePendingAcceptance,
+ ec2types.VpcPeeringConnectionStateReasonCodeProvisioning,
+ ec2types.VpcPeeringConnectionStateReasonCodeDeleted,
+ ec2types.VpcPeeringConnectionStateReasonCodeExpired,
+ ec2types.VpcPeeringConnectionStateReasonCodeRejected,
+ ec2types.VpcPeeringConnectionStateReasonCodeFailed,
+ "something-new",
+ } {
+ t.Run(string(code), func(t *testing.T) {
+ n := goodPeeredNet()
+ n.peering.Status.Code = code
+ wantRouteOut(t, n)
+ })
+ }
+ t.Run("no status", func(t *testing.T) {
+ n := goodPeeredNet()
+ n.peering.Status = nil
+ wantRouteOut(t, n)
+ })
+
+ // A peering that is not the configured one, between other VPCs or with
+ // a side in another account or region, cannot be audited at all.
+ for name, change := range map[string]func(*ec2types.VpcPeeringConnection){
+ "another peering answered": func(p *ec2types.VpcPeeringConnection) { p.VpcPeeringConnectionId = aws.String("pcx-2") },
+ "to another VPC": func(p *ec2types.VpcPeeringConnection) { p.AccepterVpcInfo.VpcId = aws.String("vpc-other") },
+ "from another VPC": func(p *ec2types.VpcPeeringConnection) { p.RequesterVpcInfo.VpcId = aws.String("vpc-other") },
+ "the VM VPC to itself": func(p *ec2types.VpcPeeringConnection) { p.AccepterVpcInfo.VpcId = aws.String("vpc-1") },
+ "accepter in another account": func(p *ec2types.VpcPeeringConnection) {
+ p.AccepterVpcInfo.OwnerId = aws.String("210987654321")
+ },
+ "requester in another account": func(p *ec2types.VpcPeeringConnection) {
+ p.RequesterVpcInfo.OwnerId = aws.String("210987654321")
+ },
+ "owner unknown": func(p *ec2types.VpcPeeringConnection) { p.AccepterVpcInfo.OwnerId = nil },
+ "accepter in another region": func(p *ec2types.VpcPeeringConnection) { p.AccepterVpcInfo.Region = aws.String("us-east-1") },
+ "no accepter": func(p *ec2types.VpcPeeringConnection) { p.AccepterVpcInfo = nil },
+ } {
+ t.Run(name, func(t *testing.T) {
+ n := goodPeeredNet()
+ change(&n.peering)
+ wantError(t, n)
+ })
+ }
+ for name, answer := range map[string]func(*ec2.DescribeVpcPeeringConnectionsInput) (*ec2.DescribeVpcPeeringConnectionsOutput, error){
+ "peering read fails": func(*ec2.DescribeVpcPeeringConnectionsInput) (*ec2.DescribeVpcPeeringConnectionsOutput, error) {
+ return nil, errors.New("denied")
+ },
+ "peering not found": func(*ec2.DescribeVpcPeeringConnectionsInput) (*ec2.DescribeVpcPeeringConnectionsOutput, error) {
+ return &ec2.DescribeVpcPeeringConnectionsOutput{}, nil
+ },
+ "two peerings answered": func(*ec2.DescribeVpcPeeringConnectionsInput) (*ec2.DescribeVpcPeeringConnectionsOutput, error) {
+ p := goodPeeredNet().peering
+ return &ec2.DescribeVpcPeeringConnectionsOutput{VpcPeeringConnections: []ec2types.VpcPeeringConnection{p, p}}, nil
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ s := goodPeeredNet().stub()
+ s.peerings = answer
+ r, err := New(peeredConfig(), s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, err := r.AuditNetwork(context.Background()); err == nil || !reflect.DeepEqual(got, isolatedjob.NetworkAudit{}) {
+ t.Errorf("AuditNetwork = (%+v, %v), want the zero audit and an error", got, err)
+ }
+ })
+ }
+}
+
+func TestAuditRefusesMissingReturnRoute(t *testing.T) {
+ t.Run("no return route", func(t *testing.T) {
+ n := goodPeeredNet()
+ n.svcRoutes = n.svcRoutes[:2]
+ wantRouteOut(t, n)
+ })
+ t.Run("return route over another peering", func(t *testing.T) {
+ n := goodPeeredNet()
+ n.svcRoutes[2] = peerRoute("10.0.0.0/24", "pcx-2")
+ wantRouteOut(t, n)
+ })
+ t.Run("return route to the whole VM VPC", func(t *testing.T) {
+ n := goodPeeredNet()
+ n.svcRoutes[2] = peerRoute("10.0.0.0/16", "pcx-1")
+ wantRouteOut(t, n)
+ })
+ for name, route := range map[string]ec2types.Route{
+ "another network over the peering": peerRoute("10.0.1.0/24", "pcx-1"),
+ "anything over a second peering": peerRoute("192.168.0.0/16", "pcx-2"),
+ "the return route twice": peerRoute("10.0.0.0/24", "pcx-1"),
+ } {
+ t.Run(name, func(t *testing.T) {
+ n := goodPeeredNet()
+ n.svcRoutes = append(n.svcRoutes, route)
+ wantRouteOut(t, n)
+ })
+ }
+
+ // The services table must be the configured one, in the services VPC.
+ for name, answer := range map[string]func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error){
+ "services table not found": func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ return &ec2.DescribeRouteTablesOutput{}, nil
+ },
+ "services table in another VPC": func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{{RouteTableId: aws.String("rtb-svc"),
+ VpcId: aws.String("vpc-1"), Routes: goodPeeredNet().svcRoutes}}}, nil
+ },
+ "services table read fails": func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ return nil, errors.New("denied")
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ s := goodPeeredNet().stub()
+ vm := s.routeTables
+ s.routeTables = func(in *ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ if filterValue(in.Filters, "route-table-id") != "" {
+ return answer(in)
+ }
+ return vm(in)
+ }
+ r, err := New(peeredConfig(), s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, err := r.AuditNetwork(context.Background()); err == nil || !reflect.DeepEqual(got, isolatedjob.NetworkAudit{}) {
+ t.Errorf("AuditNetwork = (%+v, %v), want the zero audit and an error", got, err)
+ }
+ })
+ }
+ t.Run("VM subnet without an IPv4 block", func(t *testing.T) {
+ s := goodPeeredNet().stub()
+ s.subnets = func(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error) {
+ return &ec2.DescribeSubnetsOutput{Subnets: []ec2types.Subnet{{SubnetId: aws.String("subnet-1"), VpcId: aws.String("vpc-1")}}}, nil
+ }
+ r, err := New(peeredConfig(), s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, err := r.AuditNetwork(context.Background()); err == nil || !reflect.DeepEqual(got, isolatedjob.NetworkAudit{}) {
+ t.Errorf("AuditNetwork = (%+v, %v), want the zero audit and an error", got, err)
+ }
+ })
+}
+
+// TestAuditPeeringConfig: New takes the four peering fields together or
+// not at all, each proxy route one IPv4 address, and in the peered network
+// the egress addresses are exactly the proxy routes' addresses.
+func TestAuditPeeringConfig(t *testing.T) {
+ if _, err := New(peeredConfig(), &stub{}); err != nil {
+ t.Fatalf("New(peered) = %v", err)
+ }
+ for name, edit := range map[string]func(*Config){
+ "no services VPC": func(c *Config) { c.ServicesVPCID = "" },
+ "services VPC the VM VPC": func(c *Config) { c.ServicesVPCID = c.VPCID },
+ "no services route table": func(c *Config) { c.ServicesRouteTableID = "" },
+ "no proxy routes": func(c *Config) { c.ProxyRoutes = nil },
+ "a /24 proxy route": func(c *Config) { c.ProxyRoutes[0] = netip.MustParsePrefix("10.42.1.0/24") },
+ "a /31 proxy route": func(c *Config) { c.ProxyRoutes[0] = netip.MustParsePrefix("10.42.1.10/31") },
+ "an ipv6 proxy route": func(c *Config) { c.ProxyRoutes[0] = netip.MustParsePrefix("2001:db8::1/128") },
+ "a mapped proxy route": func(c *Config) { c.ProxyRoutes[0] = netip.MustParsePrefix("::ffff:10.42.1.10/128") },
+ "an invalid proxy route": func(c *Config) { c.ProxyRoutes[0] = netip.Prefix{} },
+ "a proxy route twice": func(c *Config) { c.ProxyRoutes[1] = c.ProxyRoutes[0] },
+ "egress to an unrouted address": func(c *Config) {
+ c.Egress = append(c.Egress, netip.MustParseAddrPort("10.42.3.10:8443"))
+ },
+ "a routed address with no egress": func(c *Config) {
+ c.ProxyRoutes = append(c.ProxyRoutes, netip.MustParsePrefix("10.42.3.10/32"))
+ },
+ "routes without a peering": func(c *Config) { c.PeeringID = "" },
+ "a services table without a peering": func(c *Config) {
+ *c = testConfig()
+ c.ServicesRouteTableID = "rtb-svc"
+ },
+ "a services VPC without a peering": func(c *Config) {
+ *c = testConfig()
+ c.ServicesVPCID = "vpc-svc"
+ },
+ "proxy routes without a peering": func(c *Config) {
+ *c = testConfig()
+ c.ProxyRoutes = []netip.Prefix{netip.MustParsePrefix("10.0.1.10/32")}
+ },
+ } {
+ c := peeredConfig()
+ edit(&c)
+ if _, err := New(c, &stub{}); !errors.Is(err, isolatedjob.ErrInvalid) {
+ t.Errorf("%s: New = %v, want ErrInvalid", name, err)
+ }
+ }
+}
diff --git a/internal/isolatedjob/awsjob/runner.go b/internal/isolatedjob/awsjob/runner.go
index 723239da..6f0a4399 100644
--- a/internal/isolatedjob/awsjob/runner.go
+++ b/internal/isolatedjob/awsjob/runner.go
@@ -39,6 +39,7 @@ type EC2API interface {
DescribeSubnets(context.Context, *ec2.DescribeSubnetsInput, ...func(*ec2.Options)) (*ec2.DescribeSubnetsOutput, error)
DescribeRouteTables(context.Context, *ec2.DescribeRouteTablesInput, ...func(*ec2.Options)) (*ec2.DescribeRouteTablesOutput, error)
DescribeSecurityGroups(context.Context, *ec2.DescribeSecurityGroupsInput, ...func(*ec2.Options)) (*ec2.DescribeSecurityGroupsOutput, error)
+ DescribeVpcPeeringConnections(context.Context, *ec2.DescribeVpcPeeringConnectionsInput, ...func(*ec2.Options)) (*ec2.DescribeVpcPeeringConnectionsOutput, error)
}
// ConnectorAPI is the part of the Lambda core client the network audit
@@ -97,6 +98,18 @@ type Config struct {
// reach: the shared proxies. Empty means none: the group has no
// outbound rules, as in slice 1a, which has no egress stack.
Egress []netip.AddrPort
+ // PeeringID pins the VM VPC's one VPC peering, to ServicesVPCID, where
+ // the proxies run (decision S2-4). ServicesRouteTableID is the services
+ // VPC's route table that routes the VM subnet back over it, and
+ // ProxyRoutes the /32 routes, one per proxy address, the VM subnet
+ // sends over it; their addresses are exactly the addresses in Egress.
+ // The peering is in this account (the connector's) and region. All four
+ // empty keeps slice 1a's network, whose VM subnet routes nowhere outside
+ // its VPC.
+ PeeringID string
+ ServicesVPCID string
+ ServicesRouteTableID string
+ ProxyRoutes []netip.Prefix
}
// Runner is the isolatedjob.Runner and isolatedjob.NetworkAuditor for AWS
@@ -156,9 +169,56 @@ func (c Config) check() error {
return fmt.Errorf("egress %v is not an address and port", e)
}
}
+ return c.checkPeering()
+}
+
+// checkPeering checks the peered network's fields: all four or none, each
+// proxy route one IPv4 address (a /32), and the proxy routes' addresses
+// exactly the egress addresses.
+func (c Config) checkPeering() error {
+ if c.PeeringID == "" {
+ if c.ServicesVPCID != "" || c.ServicesRouteTableID != "" || len(c.ProxyRoutes) > 0 {
+ return errors.New("services VPC, services route table or proxy routes set without a peering")
+ }
+ return nil
+ }
+ if c.ServicesVPCID == "" || c.ServicesRouteTableID == "" || len(c.ProxyRoutes) == 0 {
+ return fmt.Errorf("peering %s needs a services VPC, a services route table and proxy routes", c.PeeringID)
+ }
+ if c.ServicesVPCID == c.VPCID {
+ return fmt.Errorf("services VPC %s is the VM VPC", c.ServicesVPCID)
+ }
+ routed := map[netip.Addr]bool{}
+ for _, p := range c.ProxyRoutes {
+ if !p.IsValid() || !p.Addr().Is4() || p.Bits() != 32 {
+ return fmt.Errorf("proxy route %v is not one IPv4 address (/32)", p)
+ }
+ if routed[p.Addr()] {
+ return fmt.Errorf("proxy route %v is listed twice", p)
+ }
+ routed[p.Addr()] = true
+ }
+ egress := map[netip.Addr]bool{}
+ for _, e := range c.Egress {
+ if !routed[e.Addr()] {
+ return fmt.Errorf("egress %v has no proxy route", e)
+ }
+ egress[e.Addr()] = true
+ }
+ for a := range routed {
+ if !egress[a] {
+ return fmt.Errorf("proxy route %v/32 is no egress address", a)
+ }
+ }
return nil
}
+// account is the AWS account of the connector's ARN, which the network
+// audit takes for this account.
+func (c Config) account() string {
+ return strings.Split(c.ConnectorID, ":")[4]
+}
+
// qualifiedConnector reports whether arn has the form
// arn:PARTITION:lambda:region:ACCOUNT:network-connector:ID:VERSION with a
// numeric version.
diff --git a/internal/isolatedjob/awsjob/runner_test.go b/internal/isolatedjob/awsjob/runner_test.go
index bf9e1c89..e422d4f1 100644
--- a/internal/isolatedjob/awsjob/runner_test.go
+++ b/internal/isolatedjob/awsjob/runner_test.go
@@ -100,6 +100,7 @@ type stub struct {
routeTables func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error)
securityGroups func(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error)
connector func(*lambdacore.GetNetworkConnectorInput) (*lambdacore.GetNetworkConnectorOutput, error)
+ peerings func(*ec2.DescribeVpcPeeringConnectionsInput) (*ec2.DescribeVpcPeeringConnectionsOutput, error)
}
func (s *stub) record(op string) {
diff --git a/internal/isolatedjob/isolatedjob.go b/internal/isolatedjob/isolatedjob.go
index 66478c29..5d590c11 100644
--- a/internal/isolatedjob/isolatedjob.go
+++ b/internal/isolatedjob/isolatedjob.go
@@ -173,10 +173,13 @@ type NetworkAuditor interface {
// NetworkAudit is one reading of the network hosted VMs launch into.
type NetworkAudit struct {
- ResolverDisabled bool // the provider's managed DNS is off
- IngressClosed bool // VMs take no inbound connections
- RouteOutAbsent bool // the VMs' subnet has no internet route
- EgressOnly []netip.AddrPort // every destination VMs are allowed to reach
+ ResolverDisabled bool // the provider's managed DNS is off
+ IngressClosed bool // VMs take no inbound connections
+ // RouteOutAbsent: the VMs' subnet routes nowhere outside its network
+ // except, where the provider pins a peering to the proxies' network,
+ // one route to each proxy address over it, which must all be present.
+ RouteOutAbsent bool
+ EgressOnly []netip.AddrPort // every destination VMs are allowed to reach
}
// OK returns nil only when the resolver is off, ingress is closed, no route