diff --git a/README.md b/README.md index b74d5a2abd..85b7859699 100644 --- a/README.md +++ b/README.md @@ -444,6 +444,16 @@ docker run -d --name floci \ floci/floci:latest ``` +### Security group enforcement + +By default, security groups on EC2 instances and ECS `awsvpc` tasks are stored, returned and used to decide which ports to publish, but they do not filter traffic. With `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`, Floci gives each Docker-backed instance and `awsvpc` task its own network namespace with an nftables default-deny policy, and filters new connections between Floci-managed containers by the sender's egress rules and the receiver's ingress rules, matched against the ENIs' own IPv4 and IPv6 addresses and group memberships. Replies to an allowed connection pass through connection tracking. It does not emulate VPC routing, network ACLs, NAT gateways or peering. + +- It needs rootful Docker running Linux containers. Rootless Docker and Windows containers are not supported. +- Turn it on with `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`; it is off by default. +- While it is on, SSH is published, but an application port a security group opens after launch is not published on the host. + +See [Security Group Port Publishing](docs/services/ec2.md#security-group-port-publishing) for the details. + ### Overriding default images | Variable | Default | diff --git a/docs/services/ec2.md b/docs/services/ec2.md index e28ec3dfb0..b0ef6f68ca 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -226,6 +226,8 @@ When the image lacks `sshd` or `scp`, Floci first installs OpenSSH with the imag With `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`, Floci prepares a separate Linux network namespace and an nftables default-deny policy before starting each Docker-backed instance. It checks new managed connections against both the sender's egress rules and the receiver's ingress rules, using emulated ENI addresses and security-group membership before translating to Docker addresses. Established replies use connection tracking. This filters packets but does not emulate VPC routing, NACLs, NAT gateways, or peering. Rootless Docker and Windows containers are unsupported. +An ENI's IPv6 addresses are part of its identity too. A rule naming an IPv6 range matches a managed peer on any IPv6 address its ENI holds, and admits that peer's traffic only on its helper's Docker IPv6 address, never on its IPv4 one. On a Docker network without IPv6 the helper has no IPv6 address, so such a rule has nothing to match. `AssignIpv6Addresses` and `UnassignIpv6Addresses` update the ENI's firewall identity at once. + Security-group permissions on a host-published port use the source visible inside Docker. Docker Desktop may replace the original external-client address. The legacy socat application publisher is disabled while enforcement is enabled because it obscures that source. SSH is published directly by the protected namespace. Application host ports remain available through the legacy publisher only when enforcement is explicitly disabled. Direct managed container traffic uses the logical ENI identity. When enforcement is disabled, an instance's security groups can open a TCP port to a CIDR source and Floci publishes that port on the host so you can reach the app from `localhost`. For each opened port Floci starts a small `alpine/socat` sidecar container that binds an allocated host port (default range 30000–30999) and forwards it to the instance container's IP, with `TCP_NODELAY` on both sockets so a request the client sends as two small writes is not held for the first write's delayed ACK (about 40 ms per round trip otherwise). The listen socket also takes a `backlog` of 4096 (socat's default is 5), so a burst of connections is queued rather than silently dropped from a full accept queue; the kernel caps the backlog at `net.core.somaxconn`. This works both for rules present at launch and for rules added later with `authorize-security-group-ingress`; revoking the rule removes the forward. The mapping (`app port -> host port`) is written to the logs: diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java index 46a27c3381..0754def972 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java @@ -183,6 +183,13 @@ public class Ec2ContainerManager { } } + /** Gives a protected ENI's firewall the IPv6 addresses the ENI holds now; nothing when enforcement is off. */ + public void updateIpv6Addresses(String eniId, List addresses) { + if (firewallManager != null && firewallManager.enabled()) { + firewallManager.updateIpv6Addresses(eniId, addresses); + } + } + public void updateSecurityGroups(String eniId, Set groupIds, Map groups, Map> prefixLists) { @@ -211,13 +218,14 @@ public class Ec2ContainerManager { || !ALIASES.matches(labels, LABEL_OWNER, ownerIdentity())) { throw new IllegalStateException("EC2 workload network namespace is not Floci protected"); } - String address = helper.getNetworkSettings().getNetworks().values().stream() - .map(network -> network.getIpAddress()).filter(ip -> ip != null && !ip.isBlank()) - .findFirst().orElseThrow(() -> new IllegalStateException("EC2 firewall helper has no Docker IP")); - return new ProtectedNamespace(helperId, address); + Map networks = helper.getNetworkSettings().getNetworks(); + String address = SecurityGroupFirewallManager.firstAddress(networks, ContainerNetwork::getIpAddress) + .orElseThrow(() -> new IllegalStateException("EC2 firewall helper has no Docker IP")); + return new ProtectedNamespace(helperId, address, + SecurityGroupFirewallManager.firstAddress(networks, ContainerNetwork::getGlobalIPv6Address).orElse(null)); } - private record ProtectedNamespace(String helperId, String transportAddress) {} + private record ProtectedNamespace(String helperId, String transportAddress, String transportIpv6Address) {} /** * The container whose network namespace this one joined through a {@code container:} network @@ -243,9 +251,9 @@ public class Ec2ContainerManager { String logical = instance.getLogicalPrivateIpAddress() != null ? instance.getLogicalPrivateIpAddress() : eni.getPrivateIpAddress(); firewallManager.register(new SecurityGroupNftCompiler.Endpoint(regionResolver.getAccountId(), region, - instance.getVpcId(), eni.getNetworkInterfaceId(), logical, address, - instance.getSecurityGroups().stream().map(GroupIdentifier::getGroupId) - .collect(Collectors.toSet()), groups), helperId, prefixLists); + instance.getVpcId(), eni.getNetworkInterfaceId(), logical, eni.getIpv6Addresses(), address, + namespace.transportIpv6Address(), instance.getSecurityGroups().stream() + .map(GroupIdentifier::getGroupId).collect(Collectors.toSet()), groups), helperId, prefixLists); } @Inject @@ -666,8 +674,8 @@ public class Ec2ContainerManager { namespace = firewallManager.createNamespace("ec2", instanceId, regionResolver.getAccountId(), region, Optional.empty(), Map.of(22, sshHostPort)); firewallManager.register(new SecurityGroupNftCompiler.Endpoint(regionResolver.getAccountId(), - region, instance.getVpcId(), eniId, eni.getPrivateIpAddress(), - namespace.transportAddress(), + region, instance.getVpcId(), eniId, eni.getPrivateIpAddress(), eni.getIpv6Addresses(), + namespace.transportAddress(), namespace.transportIpv6Address(), instance.getSecurityGroups().stream().map(g -> g.getGroupId()) .collect(Collectors.toSet()), groups), namespace.helperId(), prefixLists); diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 54f2382b51..73a477ea78 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -16492,6 +16492,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } requireIpv6Source(named, count); ensureDefaultResources(region); + return withResourceLock(instanceGroupLocks, ipv6LockKey(region, networkInterfaceId), + () -> assignIpv6AddressesLocked(region, networkInterfaceId, requested, count)); + } + + /** + * Stores the addresses first, which keeps them from every other interface, then gives them to the interface's + * firewall; a firewall that refuses them gets them back out of the store, so what is stored is what the caller + * is told. + */ + private List assignIpv6AddressesLocked(String region, String networkInterfaceId, List requested, + Integer count) { + boolean named = requested != null && !requested.isEmpty(); + Ipv6Change change; synchronized (attachmentTopologyLock(region)) { synchronized (privateIpAllocationLock) { Ipv6Holder holder = ipv6Holder(region, networkInterfaceId); @@ -16505,14 +16518,23 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab ? claimRequestedIpv6(region, subnet, requested, held).stream() .filter(address -> !held.contains(address)).toList() : allocateIpv6(region, subnet, count); + List updated = new ArrayList<>(held); + updated.addAll(added); if (!added.isEmpty()) { - List updated = new ArrayList<>(held); - updated.addAll(added); holder.store(updated); } - return added; + change = new Ipv6Change(added, updated, held); } } + try { + publishIpv6Change(networkInterfaceId, change); + } catch (RuntimeException e) { + if (!change.changed().isEmpty()) { + restoreIpv6Addresses(region, networkInterfaceId, change.before()); + } + throw e; + } + return change.changed(); } /** UnassignIpv6Addresses: returns only the named addresses the interface held, which it no longer does. */ @@ -16521,20 +16543,68 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab throw new AwsException("MissingParameter", "The request must contain the parameter Ipv6Addresses", 400); } ensureDefaultResources(region); + return withResourceLock(instanceGroupLocks, ipv6LockKey(region, networkInterfaceId), + () -> unassignIpv6AddressesLocked(region, networkInterfaceId, addresses)); + } + + /** The firewall first, as a group change does: if it refuses the smaller identity, nothing is stored. */ + private List unassignIpv6AddressesLocked(String region, String networkInterfaceId, + List addresses) { + Ipv6Change change; synchronized (attachmentTopologyLock(region)) { synchronized (privateIpAllocationLock) { - Ipv6Holder holder = ipv6Holder(region, networkInterfaceId); - List held = holder.addresses(); + List held = ipv6Holder(region, networkInterfaceId).addresses(); List removed = addresses.stream().map(address -> canonicalIpv6(address).orElse(address)) .filter(held::contains).distinct().toList(); - if (!removed.isEmpty()) { - List updated = new ArrayList<>(held); - updated.removeAll(removed); - holder.store(updated); - } - return removed; + List updated = new ArrayList<>(held); + updated.removeAll(removed); + change = new Ipv6Change(removed, updated, held); } } + publishIpv6Change(networkInterfaceId, change); + if (!change.changed().isEmpty()) { + synchronized (attachmentTopologyLock(region)) { + synchronized (privateIpAllocationLock) { + ipv6Holder(region, networkInterfaceId).store(change.held()); + } + } + } + return change.changed(); + } + + /** + * IPv6 changes to one interface take this lock through their firewall update, so two of them reach the firewall + * in the order they were stored. + */ + private String ipv6LockKey(String region, String networkInterfaceId) { + return "ipv6::" + callerAccountId() + "::" + key(region, networkInterfaceId); + } + + /** Puts back the addresses an interface held before a change its firewall refused; nothing if it is gone. */ + private void restoreIpv6Addresses(String region, String networkInterfaceId, List before) { + synchronized (attachmentTopologyLock(region)) { + synchronized (privateIpAllocationLock) { + try { + ipv6Holder(region, networkInterfaceId).store(before); + } catch (AwsException gone) { + LOG.debugv("Not restoring IPv6 addresses of {0}: {1}", networkInterfaceId, gone.getMessage()); + } + } + } + } + + /** What an IPv6 call changed, the addresses the interface holds after it, and those it held before. */ + private record Ipv6Change(List changed, List held, List before) { + } + + /** + * Gives the interface's security-group firewall the addresses it holds now, outside the stores' locks as group + * changes reach it, so peers' rules naming an IPv6 range match it on them. Nothing when nothing changed. + */ + private void publishIpv6Change(String networkInterfaceId, Ipv6Change change) { + if (!change.changed().isEmpty() && securityGroupEnforcementEnabled() && !config.services().ec2().mock()) { + containerManager.updateIpv6Addresses(networkInterfaceId, change.held()); + } } /** diff --git a/src/main/java/io/floci/aws/services/ec2/SecurityGroupFirewallManager.java b/src/main/java/io/floci/aws/services/ec2/SecurityGroupFirewallManager.java index 0795a755e8..4e4239e427 100644 --- a/src/main/java/io/floci/aws/services/ec2/SecurityGroupFirewallManager.java +++ b/src/main/java/io/floci/aws/services/ec2/SecurityGroupFirewallManager.java @@ -5,6 +5,7 @@ import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.Frame; import com.github.dockerjava.api.model.Info; import io.floci.aws.config.EmulatorConfig; @@ -33,6 +34,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; +import java.util.function.Function; /** Owns the protected namespace and the Floci-only nftables table for each managed ENI. */ @ApplicationScoped @@ -147,12 +149,13 @@ public class SecurityGroupFirewallManager { String helperId = null; try { helperId = lifecycleManager.createAndStart(spec).containerId(); - String ip = dockerClient.inspectContainerCmd(helperId).exec().getNetworkSettings() - .getNetworks().values().stream().map(n -> n.getIpAddress()) - .filter(address -> address != null && !address.isBlank()) - .findFirst().orElseThrow(() -> new IllegalStateException("Firewall helper has no Docker IP")); + Map networks = dockerClient.inspectContainerCmd(helperId).exec() + .getNetworkSettings().getNetworks(); + String ip = firstAddress(networks, ContainerNetwork::getIpAddress) + .orElseThrow(() -> new IllegalStateException("Firewall helper has no Docker IP")); apply(helperId, SecurityGroupNftCompiler.initialRuleset()); - return new Namespace(helperId, ip); + return new Namespace(helperId, ip, firstAddress(networks, ContainerNetwork::getGlobalIPv6Address) + .orElse(null)); } catch (Exception e) { if (helperId != null) { lifecycleManager.removeIfExists(helperId); @@ -223,13 +226,31 @@ public class SecurityGroupFirewallManager { quarantine(current.helperId()); throw new IllegalArgumentException("Protected endpoint needs valid security groups"); } - SecurityGroupNftCompiler.Endpoint updated = new SecurityGroupNftCompiler.Endpoint( - identity.accountId(), identity.region(), identity.vpcId(), identity.eniId(), - identity.logicalAddress(), identity.transportAddress(), Set.copyOf(groupIds), attached); + SecurityGroupNftCompiler.Endpoint updated = identity.withPolicy(Set.copyOf(groupIds), attached); endpoints.put(eniId, new ProtectedEndpoint(updated, current.helperId(), Map.copyOf(prefixLists))); reconcileAll(); } + /** + * Gives a protected ENI the IPv6 addresses it holds now, after AssignIpv6Addresses or UnassignIpv6Addresses, + * so peers' rules naming an IPv6 range match it on those addresses. Does nothing for an ENI not protected. + */ + public synchronized void updateIpv6Addresses(String eniId, List addresses) { + ProtectedEndpoint current = endpoints.get(eniId); + if (current == null) { + return; + } + endpoints.put(eniId, new ProtectedEndpoint(current.endpoint().withIpv6Addresses(addresses), + current.helperId(), current.prefixLists())); + try { + reconcileAll(); + } catch (RuntimeException e) { + // The ENI keeps the addresses the caller is told it still holds. + endpoints.computeIfPresent(eniId, (id, updated) -> current); + throw e; + } + } + public synchronized void reconcileAll() { for (Map.Entry entry : new ArrayList<>(endpoints.entrySet())) { boolean running; @@ -273,9 +294,7 @@ public class SecurityGroupFirewallManager { endpoints.values().forEach(endpoint -> quarantine(endpoint.helperId())); throw new IllegalStateException("A protected endpoint's security group disappeared"); } - SecurityGroupNftCompiler.Endpoint updated = new SecurityGroupNftCompiler.Endpoint( - identity.accountId(), identity.region(), identity.vpcId(), identity.eniId(), - identity.logicalAddress(), identity.transportAddress(), identity.groupIds(), attached); + SecurityGroupNftCompiler.Endpoint updated = identity.withPolicy(identity.groupIds(), attached); endpoints.put(entry.getKey(), new ProtectedEndpoint(updated, current.helperId(), Map.copyOf(prefixLists))); } @@ -373,7 +392,19 @@ public class SecurityGroupFirewallManager { } } - public record Namespace(String helperId, String transportAddress) {} + /** The address on any attached Docker network that {@code pick} gives, the first one set. */ + static Optional firstAddress(Map networks, + Function pick) { + return networks == null ? Optional.empty() : networks.values().stream().map(pick) + .filter(address -> address != null && !address.isBlank()).findFirst(); + } + + /** {@code transportIpv6Address} is null when the helper's Docker network has no IPv6. */ + public record Namespace(String helperId, String transportAddress, String transportIpv6Address) { + public Namespace(String helperId, String transportAddress) { + this(helperId, transportAddress, null); + } + } private record ProtectedEndpoint(SecurityGroupNftCompiler.Endpoint endpoint, String helperId, Map> prefixLists) {} } diff --git a/src/main/java/io/floci/aws/services/ec2/SecurityGroupNftCompiler.java b/src/main/java/io/floci/aws/services/ec2/SecurityGroupNftCompiler.java index e54d96f9e7..15ddb45d34 100644 --- a/src/main/java/io/floci/aws/services/ec2/SecurityGroupNftCompiler.java +++ b/src/main/java/io/floci/aws/services/ec2/SecurityGroupNftCompiler.java @@ -5,6 +5,7 @@ import io.floci.aws.services.ec2.model.SecurityGroup; import java.net.InetAddress; import java.net.UnknownHostException; +import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; @@ -17,12 +18,77 @@ public final class SecurityGroupNftCompiler { private SecurityGroupNftCompiler() {} + /** + * A managed ENI: its logical addresses (the ENI's own, which security-group rules are written against) and the + * Docker transport addresses its traffic actually carries. An ENI may hold several IPv6 addresses, all carried + * by the helper's one Docker IPv6 address, which is null on a Docker network without IPv6. + */ public record Endpoint(String accountId, String region, String vpcId, String eniId, - String logicalAddress, String transportAddress, Set groupIds, - List groups) { - SecurityGroupPolicy.Peer peer() { - return new SecurityGroupPolicy.Peer(logicalAddress, accountId, vpcId, groupIds); + String logicalAddress, List logicalIpv6Addresses, + String transportAddress, String transportIpv6Address, + Set groupIds, List groups) { + + public Endpoint(String accountId, String region, String vpcId, String eniId, + String logicalAddress, String transportAddress, Set groupIds, + List groups) { + this(accountId, region, vpcId, eniId, logicalAddress, List.of(), transportAddress, null, groupIds, + groups); } + + public Endpoint { + logicalIpv6Addresses = logicalIpv6Addresses == null ? List.of() : List.copyOf(logicalIpv6Addresses); + } + + /** The same ENI identity with the policy the manager re-resolved. */ + public Endpoint withPolicy(Set groupIds, List groups) { + return new Endpoint(accountId, region, vpcId, eniId, logicalAddress, logicalIpv6Addresses, + transportAddress, transportIpv6Address, groupIds, groups); + } + + /** The same ENI and policy, holding {@code addresses} as its IPv6 addresses now. */ + public Endpoint withIpv6Addresses(List addresses) { + return new Endpoint(accountId, region, vpcId, eniId, logicalAddress, addresses, transportAddress, + transportIpv6Address, groupIds, groups); + } + + SecurityGroupPolicy.Peer peer(String address) { + return new SecurityGroupPolicy.Peer(address, accountId, vpcId, groupIds); + } + + /** + * The (logical, transport) pairs a peer's rules are written for. An IPv6 address pairs only with the IPv6 + * transport: emitted against the IPv4 one, a rule allowing a peer's IPv6 range would admit IPv4 traffic no + * permission allows. + */ + List identities() { + List identities = new ArrayList<>(); + if (literal(logicalAddress) && literal(transportAddress)) { + identities.add(new AddressIdentity(logicalAddress, transportAddress)); + } + if (literal(transportIpv6Address)) { + for (String address : logicalIpv6Addresses) { + if (literal(address)) { + identities.add(new AddressIdentity(address, transportIpv6Address)); + } + } + } + return identities; + } + + /** Every Docker address the endpoint's traffic can carry, whether or not an identity uses it. */ + List transports() { + List transports = new ArrayList<>(2); + if (literal(transportAddress)) { + transports.add(transportAddress); + } + if (literal(transportIpv6Address)) { + transports.add(transportIpv6Address); + } + return transports; + } + } + + record AddressIdentity(String logical, String transport) { } public static String initialRuleset() { @@ -66,7 +132,7 @@ public final class SecurityGroupNftCompiler { List managed = peers == null ? List.of() : peers.stream() .filter(peer -> !target.eniId().equals(peer.eniId())) - .filter(peer -> peer.transportAddress() != null && literal(peer.transportAddress())) + .filter(peer -> !peer.transports().isEmpty()) .toList(); for (boolean egress : new boolean[]{false, true}) { @@ -84,19 +150,28 @@ public final class SecurityGroupNftCompiler { continue; } for (Endpoint peer : managed) { - if (target.accountId().equals(peer.accountId()) - && target.region().equals(peer.region()) - && target.vpcId().equals(peer.vpcId()) - && SecurityGroupPolicy.matchesPeer(group, permission, peer.peer(), prefixLists)) { - appendRule(rules, chain, addressField, peer.transportAddress(), protocol); + if (!target.accountId().equals(peer.accountId()) || !target.region().equals(peer.region()) + || !target.vpcId().equals(peer.vpcId())) { + continue; + } + for (AddressIdentity identity : peer.identities()) { + if (protocolFitsFamily(permission, identity.transport()) + && SecurityGroupPolicy.matchesPeer(group, permission, peer.peer(identity.logical()), + prefixLists)) { + appendRule(rules, chain, addressField, identity.transport(), protocol); + } } } } } // A managed peer must never fall through to a broad external CIDR rule // evaluated against its Docker bridge IP instead of its logical ENI address. - for (Endpoint peer : managed) { - appendRule(rules, chain, addressField, peer.transportAddress(), "drop"); + // Every transport a managed peer has, its IPv6 one included when its ENI holds no IPv6 address, so its + // traffic on that address cannot reach a broad IPv6 CIDR rule either. + Set transports = new LinkedHashSet<>(); + managed.forEach(peer -> transports.addAll(peer.transports())); + for (String transport : transports) { + appendRule(rules, chain, addressField, transport, "drop"); } for (SecurityGroup group : target.groups()) { List permissions = egress @@ -139,6 +214,20 @@ public final class SecurityGroupNftCompiler { .append(expression).append('\n'); } + /** + * Whether a permission's protocol can be written against {@code address}'s family: ICMP is IPv4's and ICMPv6 is + * IPv6's, and nftables refuses an {@code icmp} header match beside an {@code ip6} address, and the reverse. + */ + private static boolean protocolFitsFamily(IpPermission permission, String address) { + String protocol = permission.getIpProtocol() == null ? "" : permission.getIpProtocol().toLowerCase(Locale.ROOT); + boolean ipv6 = address.indexOf(':') >= 0; + return switch (protocol) { + case "icmp", "1" -> !ipv6; + case "icmpv6", "58" -> ipv6; + default -> true; + }; + } + private static String protocolExpression(IpPermission permission) { String protocol = permission.getIpProtocol(); if (protocol == null) { diff --git a/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java b/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java index 7f3a4e2c22..042c600b19 100644 --- a/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java +++ b/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java @@ -1370,8 +1370,9 @@ public class EcsContainerManager { .stream().map(PrefixListEntry::getCidr).toList())); } firewallManager.register(new SecurityGroupNftCompiler.Endpoint(regionResolver.getAccountId(), - region, eni.getVpcId(), eniId, eni.getPrivateIpAddress(), - namespace.transportAddress(), Set.copyOf(groupIds), groups), namespace.helperId(), prefixLists); + region, eni.getVpcId(), eniId, eni.getPrivateIpAddress(), eni.getIpv6Addresses(), + namespace.transportAddress(), namespace.transportIpv6Address(), Set.copyOf(groupIds), groups), + namespace.helperId(), prefixLists); task.setNetworkInterfaceId(eniId); task.setPrivateIpAddress(eni.getPrivateIpAddress()); return new PreparedNetwork(eni, namespace); diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2SecurityGroupPublicationRaceTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2SecurityGroupPublicationRaceTest.java index 48ff08323e..c26b1486a9 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2SecurityGroupPublicationRaceTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2SecurityGroupPublicationRaceTest.java @@ -12,6 +12,7 @@ import io.floci.aws.services.ec2.model.SecurityGroup; import io.floci.aws.services.ec2.model.SecurityGroupRule; import io.floci.aws.services.ec2.model.Tag; import io.floci.aws.services.ec2.model.UserIdGroupPair; +import io.floci.aws.services.ec2.model.Vpc; import io.floci.aws.services.ec2.model.VpcEndpoint; import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager; import io.floci.aws.testing.InMemoryStorageFactory; @@ -748,6 +749,118 @@ class Ec2SecurityGroupPublicationRaceTest { anySet()); } + /** A dual-stack subnet's interface, with enforcement on and the container manager a mock. */ + private record Ipv6Fixture(Ec2Service service, Ec2ContainerManager manager, String region, String eni, + String block) { + List held() { + return service.describeNetworkInterfaces(region, List.of(eni), Map.of()).networkInterfaces().getFirst() + .getIpv6Addresses(); + } + } + + private static Ipv6Fixture ipv6Fixture() { + TestStores factory = new TestStores(); + EmulatorConfig config = mockConfig(); + Ec2ContainerManager manager = mock(Ec2ContainerManager.class); + Ec2Service service = service(factory, config, manager); + String region = "us-east-1"; + Vpc vpc = service.createVpc(region, "10.0.0.0/16", false, true); + String block = vpc.getIpv6CidrBlockAssociationSet().getFirst().getIpv6CidrBlock(); + String subnet = service.createSubnet(region, vpc.getVpcId(), "10.0.1.0/24", region + "a", null, + block.substring(0, block.indexOf('/')) + "/64").getSubnetId(); + String eni = service.createNetworkInterface(region, subnet, null, null, List.of(), List.of(), List.of()) + .getNetworkInterfaceId(); + enableEnforcement(config); + return new Ipv6Fixture(service, manager, region, eni, block); + } + + // Catches: an IPv6 address change never reaching the interface's firewall, so peers' rules naming an IPv6 range + // keep missing it; a call that changes nothing reaches it with nothing. + @Test + void ipv6AddressChangesReachTheInterfaceFirewall() { + Ipv6Fixture fixture = ipv6Fixture(); + + List assigned = fixture.service().assignIpv6Addresses(fixture.region(), fixture.eni(), null, 1); + verify(fixture.manager()).updateIpv6Addresses(fixture.eni(), assigned); + String block = fixture.block(); + fixture.service().unassignIpv6Addresses(fixture.region(), fixture.eni(), + List.of(block.substring(0, block.indexOf("::")) + "::ffff")); + fixture.service().unassignIpv6Addresses(fixture.region(), fixture.eni(), assigned); + + verify(fixture.manager()).updateIpv6Addresses(fixture.eni(), List.of()); + verify(fixture.manager(), times(2)).updateIpv6Addresses(anyString(), anyList()); + } + + // Catches: an assign the firewall refuses answering an error while its addresses stay assigned. + @Test + void anAssignTheFirewallRefusesLeavesNoAddress() { + Ipv6Fixture fixture = ipv6Fixture(); + IllegalStateException failure = new IllegalStateException("Owned firewall failure"); + doThrow(failure).when(fixture.manager()).updateIpv6Addresses(anyString(), anyList()); + + assertSame(failure, assertThrows(IllegalStateException.class, + () -> fixture.service().assignIpv6Addresses(fixture.region(), fixture.eni(), null, 1))); + + assertEquals(List.of(), fixture.held()); + } + + // Catches: an unassign the firewall refuses answering an error while its addresses are gone from the store. + @Test + void anUnassignTheFirewallRefusesKeepsTheAddresses() { + Ipv6Fixture fixture = ipv6Fixture(); + List assigned = fixture.service().assignIpv6Addresses(fixture.region(), fixture.eni(), null, 1); + doThrow(new IllegalStateException("Owned firewall failure")).when(fixture.manager()) + .updateIpv6Addresses(anyString(), anyList()); + + assertThrows(IllegalStateException.class, + () -> fixture.service().unassignIpv6Addresses(fixture.region(), fixture.eni(), assigned)); + + assertEquals(assigned, fixture.held()); + } + + // Catches: two IPv6 changes on one interface reaching the firewall in another order than they were stored, so + // the firewall keeps an older address list than the interface holds. + @Test + void ipv6ChangesOnOneInterfaceReachTheFirewallInOrder() throws Exception { + Ipv6Fixture fixture = ipv6Fixture(); + CountDownLatch publishing = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + AtomicReference> firewall = new AtomicReference<>(); + doAnswer(invocation -> { + List addresses = invocation.getArgument(1); + if (firewall.get() == null) { + publishing.countDown(); + assertTrue(release.await(5, TimeUnit.SECONDS)); + } + firewall.set(List.copyOf(addresses)); + return null; + }).when(fixture.manager()).updateIpv6Addresses(anyString(), anyList()); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> + fixture.service().assignIpv6Addresses(fixture.region(), fixture.eni(), null, 1)); + assertTrue(publishing.await(5, TimeUnit.SECONDS), "First publication must reach the firewall"); + AtomicReference secondThread = new AtomicReference<>(); + Future second = executor.submit(() -> { + secondThread.set(Thread.currentThread()); + fixture.service().assignIpv6Addresses(fixture.region(), fixture.eni(), null, 1); + }); + awaitBlockedOrDone(secondThread, second); + boolean secondOvertook = second.isDone(); + release.countDown(); + first.get(5, TimeUnit.SECONDS); + second.get(5, TimeUnit.SECONDS); + + assertFalse(secondOvertook, "A second change on the interface must wait through the first publication"); + assertEquals(2, fixture.held().size()); + assertEquals(fixture.held(), firewall.get()); + } finally { + release.countDown(); + executor.shutdownNow(); + assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); + } + } + private static String interfaceGroup(Ec2Service service, String region, String eni) { return service.describeNetworkInterfaces(region, List.of(eni), Map.of()).networkInterfaces().getFirst() .getGroups().getFirst().getGroupId(); diff --git a/src/test/java/io/floci/aws/services/ec2/SecurityGroupNftCompilerTest.java b/src/test/java/io/floci/aws/services/ec2/SecurityGroupNftCompilerTest.java index 3db27697bd..8b452db06a 100644 --- a/src/test/java/io/floci/aws/services/ec2/SecurityGroupNftCompilerTest.java +++ b/src/test/java/io/floci/aws/services/ec2/SecurityGroupNftCompilerTest.java @@ -2,7 +2,9 @@ package io.floci.aws.services.ec2; import io.floci.aws.services.ec2.model.IpPermission; import io.floci.aws.services.ec2.model.IpRange; +import io.floci.aws.services.ec2.model.Ipv6Range; import io.floci.aws.services.ec2.model.SecurityGroup; +import io.floci.aws.services.ec2.model.UserIdGroupPair; import org.junit.jupiter.api.Test; import java.util.List; @@ -87,6 +89,123 @@ class SecurityGroupNftCompilerTest { assertFalse(nft.contains("daddr 172.18.0.2 accept"), "only DNS is allowed to the resolver"); } + /** A group allowing tcp/443 from {@code cidrIpv6} only. */ + private static SecurityGroup ipv6Group(String cidrIpv6) { + SecurityGroup group = new SecurityGroup(); + group.setVpcId("vpc-1"); + group.setOwnerId("000000000000"); + IpPermission permission = new IpPermission(); + permission.setIpProtocol("tcp"); + permission.setFromPort(443); + permission.setToPort(443); + Ipv6Range range = new Ipv6Range(); + range.setCidrIpv6(cidrIpv6); + permission.getIpv6Ranges().add(range); + group.getIpPermissions().add(permission); + return group; + } + + private static SecurityGroupNftCompiler.Endpoint dualStack(String eni, String logical, List logicalIpv6, + String transport, String transportIpv6, + SecurityGroup group) { + return new SecurityGroupNftCompiler.Endpoint("000000000000", "us-east-1", "vpc-1", eni, logical, logicalIpv6, + transport, transportIpv6, Set.of("sg-1"), List.of(group)); + } + + // Catches: a rule allowing a peer's IPv6 range never matching it, because only its IPv4 address was an identity. + @Test + void aRuleOnAnIpv6RangeMatchesThePeerOnItsIpv6Transport() { + SecurityGroup group = ipv6Group("2600:1f18:0:a600::/64"); + SecurityGroupNftCompiler.Endpoint target = dualStack("eni-a", "10.0.0.2", List.of("2600:1f18:0:a600::10"), + "172.17.0.2", "fd00:d0c::2", group); + SecurityGroupNftCompiler.Endpoint peer = dualStack("eni-b", "10.0.0.3", + List.of("2600:1f18:0:a600::20", "2600:1f18:0:a600::21"), "172.17.0.3", "fd00:d0c::3", group); + + String nft = SecurityGroupNftCompiler.compile(target, List.of(peer), Map.of()); + + assertTrue(nft.contains("ingress ip6 saddr fd00:d0c::3 tcp dport 443 accept")); + // An IPv6-only permission never admits the peer's IPv4 transport. + assertFalse(nft.contains("ip saddr 172.17.0.3 tcp dport 443 accept")); + assertTrue(nft.contains("ingress ip saddr 172.17.0.3 drop")); + assertTrue(nft.contains("ingress ip6 saddr fd00:d0c::3 drop")); + } + + // Catches: a peer's IPv6 address paired with its IPv4 transport when its Docker network has no IPv6, which + // would let IPv4 traffic through on a rule that only names an IPv6 range. + @Test + void aPeerWithoutAnIpv6TransportGetsNoIpv6Rule() { + SecurityGroup group = ipv6Group("2600:1f18:0:a600::/64"); + SecurityGroupNftCompiler.Endpoint target = dualStack("eni-a", "10.0.0.2", List.of(), "172.17.0.2", null, + group); + SecurityGroupNftCompiler.Endpoint peer = dualStack("eni-b", "10.0.0.3", List.of("2600:1f18:0:a600::20"), + "172.17.0.3", null, group); + + String nft = SecurityGroupNftCompiler.compile(target, List.of(peer), Map.of()); + + assertFalse(nft.contains("172.17.0.3 tcp dport 443 accept")); + assertTrue(nft.contains("ingress ip saddr 172.17.0.3 drop")); + } + + // Catches: an IPv4-only ENI on an IPv6-enabled Docker network sending on its helper's IPv6 address past the + // managed-peer drop, straight into a broad IPv6 CIDR rule. + @Test + void aPeersIpv6TransportIsDroppedEvenWithoutAnIpv6Address() { + SecurityGroup group = ipv6Group("::/0"); + SecurityGroupNftCompiler.Endpoint target = dualStack("eni-a", "10.0.0.2", List.of(), "172.17.0.2", + "fd00:d0c::2", group); + SecurityGroupNftCompiler.Endpoint ipv4Only = dualStack("eni-b", "10.0.0.3", List.of(), "172.17.0.3", + "fd00:d0c::3", group); + + String nft = SecurityGroupNftCompiler.compile(target, List.of(ipv4Only), Map.of()); + + assertTrue(nft.contains("ingress ip6 saddr fd00:d0c::3 drop")); + assertTrue(nft.indexOf("ingress ip6 saddr fd00:d0c::3 drop") + < nft.indexOf("ingress ip6 saddr ::/0 tcp dport 443 accept")); + } + + // Catches: a group-reference ICMP rule written against a peer's IPv6 transport, which nftables refuses + // ("ip6 saddr ... icmp type"), failing the whole policy. + @Test + void anIcmpGroupRuleIsWrittenOnlyForThePeersIpv4Identity() { + SecurityGroup group = new SecurityGroup(); + group.setVpcId("vpc-1"); + group.setOwnerId("000000000000"); + IpPermission echo = new IpPermission(); + echo.setIpProtocol("icmp"); + echo.setFromPort(8); + echo.setToPort(0); + UserIdGroupPair self = new UserIdGroupPair(); + self.setGroupId("sg-1"); + echo.getUserIdGroupPairs().add(self); + group.getIpPermissions().add(echo); + SecurityGroupNftCompiler.Endpoint target = dualStack("eni-a", "10.0.0.2", List.of("2600:1f18:0:a600::10"), + "172.17.0.2", "fd00:d0c::2", group); + SecurityGroupNftCompiler.Endpoint peer = dualStack("eni-b", "10.0.0.3", List.of("2600:1f18:0:a600::20"), + "172.17.0.3", "fd00:d0c::3", group); + + String nft = SecurityGroupNftCompiler.compile(target, List.of(peer), Map.of()); + + assertTrue(nft.contains("ingress ip saddr 172.17.0.3 icmp type 8 icmp code 0 accept")); + assertFalse(nft.contains("ip6 saddr fd00:d0c::3 icmp")); + } + + // Catches: an address change leaving the endpoint's identity as it was registered. + @Test + void anEndpointTakesNewIpv6AddressesKeepingItsPolicy() { + SecurityGroup group = ipv6Group("2600:1f18:0:a600::/64"); + SecurityGroupNftCompiler.Endpoint peer = dualStack("eni-b", "10.0.0.3", List.of(), "172.17.0.3", + "fd00:d0c::3", group); + SecurityGroupNftCompiler.Endpoint target = dualStack("eni-a", "10.0.0.2", List.of(), "172.17.0.2", + "fd00:d0c::2", group); + + String before = SecurityGroupNftCompiler.compile(target, List.of(peer), Map.of()); + String after = SecurityGroupNftCompiler.compile(target, + List.of(peer.withIpv6Addresses(List.of("2600:1f18:0:a600::20"))), Map.of()); + + assertFalse(before.contains("ip6 saddr fd00:d0c::3 tcp dport 443 accept")); + assertTrue(after.contains("ip6 saddr fd00:d0c::3 tcp dport 443 accept")); + } + private static SecurityGroupNftCompiler.Endpoint endpoint(String eni, String logical, String transport, SecurityGroup group) { return new SecurityGroupNftCompiler.Endpoint("000000000000", "us-east-1", "vpc-1",