feat(ec2): publish ports open to every address under security-group enforcement (#8610)

With security-group enforcement on, the socat publisher was switched
off, so an application port a security group opened was never reachable
from the host. Docker can replace a host client's address (Docker
Desktop shows every client as its gateway), so no rule narrower than the
whole internet can be judged on it.

Host-published access now counts as traffic from outside the VPC: with
enforcement on, a port is published only when an ingress rule opens it
to 0.0.0.0/0, or failing that ::/0, which admit a client whatever
address it arrives with. The sidecar dials the instance through its
protected namespace's helper, on the helper's network: on its IPv4
address, or on its Docker IPv6 address for a port only ::/0 opens, which
is not published on a network without IPv6. A client's family is still
seen on the host, so a port only one family's rule opens binds only that
family's host addresses. A port whose rules move family is republished,
the family is persisted for restore, and a restart brings each running
instance's forwards in line with its current rules. Ports opened after
launch publish and revoking removes them, as with enforcement off; a
port only a narrower CIDR, a prefix list or a group reference opens
stays reachable on the direct container path.

Also brings Ec2ServiceTest's never-allocates check onto the
three-argument allocatePrivateIp that #8598 introduced, which left
main's tests not compiling after #8576.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 13:26:43 -04:00
1 parent 269a00fe75
commit d8460bc305
13 files changed
+440 -71

No files matched your search

@@ -3685,7 +3685,8 @@ public interface EmulatorConfig {
/**
* When true, TCP ports opened by an instance's security-group ingress rules are
* published on the host via a socat sidecar container, both at launch and on later
* authorize-security-group-ingress. Set false to keep security groups as metadata only.
* authorize-security-group-ingress. With security-group enforcement on, only ports a rule
* opens to every address (0.0.0.0/0 or ::/0) are. Set false to publish none.
*/
@WithDefault("true")
boolean publishSecurityGroupPorts();
@@ -444,23 +444,24 @@ public class Ec2ContainerManager {
* @param region AWS region (for CloudWatch log group naming)
*/
public void launch(Instance instance, String dockerImage, String publicKey, String region) {
launch(instance, ResolvedAmiImage.minimal(dockerImage), publicKey, region, Set.of());
launch(instance, ResolvedAmiImage.minimal(dockerImage), publicKey, region);
}
public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region) {
launch(instance, image, publicKey, region, Set.of());
launch(instance, image, publicKey, region, Ec2PortForwardManager.DesiredPorts.NONE);
}
/**
* @param appPorts TCP ports opened by the instance's security groups to publish on the host
* via socat sidecars once the container is running (empty for none)
* via socat sidecars once the container is running ({@code DesiredPorts.NONE} for none)
*/
public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region, Set<Integer> appPorts) {
public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region,
Ec2PortForwardManager.DesiredPorts appPorts) {
launch(instance, image, publicKey, region, appPorts, List.of(), Map.of());
}
public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region,
Set<Integer> appPorts, List<SecurityGroup> groups,
Ec2PortForwardManager.DesiredPorts appPorts, List<SecurityGroup> groups,
Map<String, List<String>> prefixLists) {
instance.setState(InstanceState.pending());
@@ -594,7 +595,7 @@ public class Ec2ContainerManager {
installInstanceConnectTrustAnchor(containerId, instanceId);
// Publish security-group TCP ingress ports on the host via socat sidecars.
if (appPorts != null && !appPorts.isEmpty()) {
if (appPorts != null && !appPorts.ports().isEmpty()) {
portForwardManager.reconcile(instance, appPorts);
}
@@ -1129,9 +1129,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return false;
}
putForOwner(instances, entry, instance);
// Container is running: re-reserve host ports and recreate any missing socat sidecars.
// Container is running: re-reserve host ports and recreate any missing socat sidecars, then
// bring them to what the current rules publish, since a forward may come from other rules or
// another enforcement setting.
if (portForwardManager != null) {
portForwardManager.restore(instance);
portForwardManager.reconcile(instance, desiredPublishedPorts(instance.getRegion(), instance));
}
return true;
}
@@ -4524,11 +4527,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
/**
* Resolves the TCP ingress ports Floci should publish on the host for an instance, aggregated
* across its attached security groups. Empty when publishing is disabled or nothing is opened.
* across its attached security groups: with enforcement on, only those opened to every address.
* Empty when publishing is disabled or nothing is opened.
*/
private Set<Integer> desiredPublishedPorts(String region, Instance inst) {
private Ec2PortForwardManager.DesiredPorts desiredPublishedPorts(String region, Instance inst) {
if (!config.services().ec2().publishSecurityGroupPorts()) {
return Set.of();
return Ec2PortForwardManager.DesiredPorts.NONE;
}
List<SecurityGroup> sgs = new ArrayList<>();
if (inst.getSecurityGroups() != null) {
@@ -4536,8 +4540,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
securityGroups.get(key(region, gi.getGroupId())).ifPresent(sgs::add);
}
}
return Ec2PortForwardManager.extractPublishablePorts(
sgs, config.services().ec2().maxPublishedPortsPerInstance());
int max = config.services().ec2().maxPublishedPortsPerInstance();
return securityGroupEnforcementEnabled()
? Ec2PortForwardManager.extractWorldOpenPorts(sgs, max)
: Ec2PortForwardManager.DesiredPorts.anyFamily(Ec2PortForwardManager.extractPublishablePorts(sgs, max));
}
private Map<String, List<String>> policyPrefixLists(String region, List<SecurityGroup> groups) {
@@ -106,6 +106,9 @@ public class Instance {
// Security-group ingress ports published on the host via socat sidecars:
// container app port -> allocated host port. Not part of the AWS wire format.
private Map<Integer, Integer> publishedPorts = new LinkedHashMap<>();
// The family each published port admits, when it is not ANY: with security-group enforcement on,
// a port only one family's world-open rule opens. Not part of the AWS wire format.
private Map<Integer, PublishedPortFamily> publishedPortFamilies = new LinkedHashMap<>();
public Instance() {}
@@ -272,6 +275,16 @@ public class Instance {
}
public void setPublishedPorts(Map<Integer, Integer> publishedPorts) { this.publishedPorts = publishedPorts; }
public Map<Integer, PublishedPortFamily> getPublishedPortFamilies() {
if (publishedPortFamilies == null) {
publishedPortFamilies = new LinkedHashMap<>();
}
return publishedPortFamilies;
}
public void setPublishedPortFamilies(Map<Integer, PublishedPortFamily> publishedPortFamilies) {
this.publishedPortFamilies = publishedPortFamilies;
}
public String getRootVolumeId() { return rootVolumeId; }
public void setRootVolumeId(String rootVolumeId) { this.rootVolumeId = rootVolumeId; }
@@ -0,0 +1,17 @@
package io.floci.aws.services.ec2.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* The client family a host-published application port admits: the host addresses its sidecar binds
* and the instance address it dials. Not part of the AWS wire format.
*/
@RegisterForReflection
public enum PublishedPortFamily {
/** Every host address, dialling the instance's IPv4 address. */
ANY,
/** Host IPv4 addresses only, dialling the instance's IPv4 address. */
IPV4,
/** Host IPv6 addresses only, dialling the instance's Docker IPv6 address. */
IPV6
}
@@ -10,8 +10,10 @@ import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.common.docker.PortAllocator;
import io.floci.aws.services.ec2.SecurityGroupPolicy;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.IpPermission;
import io.floci.aws.services.ec2.model.PublishedPortFamily;
import io.floci.aws.services.ec2.model.SecurityGroup;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
@@ -27,6 +29,9 @@ import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* Publishes EC2 instance application ports on the host, driven by the TCP ingress
@@ -49,6 +54,10 @@ import java.util.function.Consumer;
* <p>Because each forward is a fresh container, ports opened <em>after</em> launch via
* {@code authorize-security-group-ingress} are handled the same way as ports present at
* launch. The instance container itself is never modified.
*
* <p>With security-group enforcement on, the sidecar's connection reaches the instance through
* its protected namespace's firewall like any traffic from outside the VPC, so only ports an
* ingress rule opens to every address are published (see {@link #extractWorldOpenPorts}).
*/
@ApplicationScoped
public class Ec2PortForwardManager {
@@ -58,6 +67,13 @@ public class Ec2PortForwardManager {
/** SSH is already published on its own host port by the container manager; never re-forward it. */
static final int SSH_PORT = 22;
/** The network mode prefix of a container that joins another container's network namespace. */
private static final String CONTAINER_NETWORK_MODE = "container:";
/** Host addresses a forward binds when it admits one family only (Docker's IPv4-only and IPv6-only forms). */
private static final String IPV4_HOST_ADDRESSES = "0.0.0.0";
private static final String IPV6_HOST_ADDRESSES = "::";
private final DockerClient dockerClient;
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -92,19 +108,31 @@ public class Ec2PortForwardManager {
executor.shutdownNow();
}
/** The application ports to publish, each with the client family it admits. */
public record DesiredPorts(Map<Integer, PublishedPortFamily> ports) {
public static final DesiredPorts NONE = new DesiredPorts(Map.of());
/** Ports that admit every client, as with security-group enforcement off. */
public static DesiredPorts anyFamily(Set<Integer> ports) {
Map<Integer, PublishedPortFamily> families = new LinkedHashMap<>();
ports.forEach(port -> families.put(port, PublishedPortFamily.ANY));
return new DesiredPorts(families);
}
}
/**
* Reconciles the instance's live forwards against the desired port set: publishes ports
* that are newly opened and unpublishes ports that no longer have an ingress rule. Runs
* asynchronously so it does not block the calling API thread.
*/
public void reconcile(Instance instance, Set<Integer> desiredPorts) {
public void reconcile(Instance instance, DesiredPorts desiredPorts) {
if (!enabled() || instance == null || instance.getDockerContainerId() == null) {
return;
}
executor.submit(() -> reconcileNow(instance, desiredPorts));
}
void reconcileNow(Instance instance, Set<Integer> desiredPorts) {
void reconcileNow(Instance instance, DesiredPorts desiredPorts) {
synchronized (instance) {
// A reconcile queued before a stop/terminate must not republish against the
// removed container: stop/terminate flip the state before their async
@@ -114,13 +142,18 @@ public class Ec2PortForwardManager {
if (!"running".equals(state)) {
return;
}
for (int port : desiredPorts) {
for (Map.Entry<Integer, PublishedPortFamily> desired : desiredPorts.ports().entrySet()) {
int port = desired.getKey();
// The rules opening the port changed family: its sidecar binds or dials the wrong addresses.
if (instance.getPublishedPorts().containsKey(port) && desired.getValue() != family(instance, port)) {
unpublish(instance, port);
}
if (!instance.getPublishedPorts().containsKey(port)) {
publish(instance, port);
publish(instance, port, desired.getValue());
}
}
for (Integer port : new ArrayList<>(instance.getPublishedPorts().keySet())) {
if (!desiredPorts.contains(port)) {
if (!desiredPorts.ports().containsKey(port)) {
unpublish(instance, port);
}
}
@@ -143,9 +176,7 @@ public class Ec2PortForwardManager {
}
boolean enabled() {
return config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock()
&& (config.network() == null || config.network().securityGroupEnforcement() == null
|| !config.network().securityGroupEnforcement().enabled());
return config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock();
}
/** Sets the callback used to persist an instance after its forwards change. */
@@ -176,11 +207,12 @@ public class Ec2PortForwardManager {
config, instance.getInstanceId(), appPort)).isEmpty()) {
LOG.infov("Recreating missing port-forward sidecar for EC2 instance {0} app port {1}",
instance.getInstanceId(), appPort);
if (!publishOn(instance, appPort, hostPort)) {
if (!publishOn(instance, appPort, hostPort, family(instance, appPort))) {
portAllocator.release(hostPort);
// Drop the stale mapping so a later reconcile can re-publish the port
// instead of seeing it as already published.
instance.getPublishedPorts().remove(appPort);
instance.getPublishedPortFamilies().remove(appPort);
persist(instance);
}
} else {
@@ -190,35 +222,53 @@ public class Ec2PortForwardManager {
}
}
void publish(Instance instance, int appPort) {
void publish(Instance instance, int appPort, PublishedPortFamily family) {
int hostPort = portAllocator.allocate(
config.services().ec2().appPortRangeStart(),
config.services().ec2().appPortRangeEnd());
if (!publishOn(instance, appPort, hostPort)) {
if (!publishOn(instance, appPort, hostPort, family)) {
portAllocator.release(hostPort);
}
}
private boolean publishOn(Instance instance, int appPort, int hostPort) {
/** The family a published port admits; a forward persisted before families were kept admits every client. */
private static PublishedPortFamily family(Instance instance, int appPort) {
return instance.getPublishedPortFamilies().getOrDefault(appPort, PublishedPortFamily.ANY);
}
private boolean publishOn(Instance instance, int appPort, int hostPort, PublishedPortFamily family) {
String instanceId = instance.getInstanceId();
boolean ipv6 = family == PublishedPortFamily.IPV6;
try {
NetworkTarget target = resolveInstanceTarget(instance);
NetworkTarget target = resolveInstanceTarget(instance, ipv6);
if (target == null) {
LOG.warnv("Could not resolve container IP for EC2 instance {0}; not publishing port {1}",
instanceId, appPort);
if (ipv6) {
LOG.warnv("EC2 instance {0} has no Docker IPv6 address; not publishing port {1} (::/0 only)",
instanceId, appPort);
} else {
LOG.warnv("Could not resolve container IP for EC2 instance {0}; not publishing port {1}",
instanceId, appPort);
}
return false;
}
String address = ipv6 ? "[" + target.ip() + "]" : target.ip();
String name = forwardContainerName(config, instanceId, appPort);
ContainerStorageHelper.removeStaleContainer(config, lifecycleManager, name);
// An IPv6-only host binding can reach the sidecar on its own IPv6 address, so its listener takes both.
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(config.services().ec2().socatImage())
.withName(name)
.withEntrypoint(List.of("socat"))
.withCmd(List.of(
"TCP-LISTEN:" + appPort + ",fork,reuseaddr,nodelay,backlog=" + ListenBacklog.ACCEPT,
"TCP:" + target.ip() + ":" + appPort + ",nodelay"))
.withPortBinding(appPort, hostPort)
(ipv6 ? "TCP6-LISTEN:" + appPort + ",ipv6only=0" : "TCP-LISTEN:" + appPort)
+ ",fork,reuseaddr,nodelay,backlog=" + ListenBacklog.ACCEPT,
(ipv6 ? "TCP6:" : "TCP:") + address + ":" + appPort + ",nodelay"))
.withPortBinding(appPort, hostPort, switch (family) {
case IPV4 -> IPV4_HOST_ADDRESSES;
case IPV6 -> IPV6_HOST_ADDRESSES;
case ANY -> null;
})
.withLogRotation();
if (target.network() != null) {
specBuilder.withNetworkMode(target.network());
@@ -229,9 +279,14 @@ public class Ec2PortForwardManager {
lifecycleManager.startCreated(containerId, spec);
instance.getPublishedPorts().put(appPort, hostPort);
if (family == PublishedPortFamily.ANY) {
instance.getPublishedPortFamilies().remove(appPort);
} else {
instance.getPublishedPortFamilies().put(appPort, family);
}
persist(instance);
LOG.infov("Published EC2 instance {0} app port {1} on host port {2} (socat -> {3}:{1})",
instanceId, appPort, hostPort, target.ip());
instanceId, appPort, hostPort, address);
return true;
} catch (Exception e) {
LOG.warnv("Failed to publish EC2 instance {0} app port {1}: {2}", instanceId, appPort, e.getMessage());
@@ -243,6 +298,7 @@ public class Ec2PortForwardManager {
String name = forwardContainerName(config, instance.getInstanceId(), appPort);
ContainerStorageHelper.removeStaleContainer(config, lifecycleManager, name);
Integer hostPort = instance.getPublishedPorts().remove(appPort);
instance.getPublishedPortFamilies().remove(appPort);
if (hostPort != null) {
portAllocator.release(hostPort);
persist(instance);
@@ -277,15 +333,22 @@ public class Ec2PortForwardManager {
return ContainerStorageHelper.legacyDockerName(config, forwardContainerToken(instanceId, appPort));
}
private NetworkTarget resolveInstanceTarget(Instance instance) {
private NetworkTarget resolveInstanceTarget(Instance instance, boolean ipv6) {
String containerId = instance.getDockerContainerId();
if (containerId != null) {
try {
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(containerId).exec();
// With enforcement on, the instance joins its protected namespace's network, so the
// namespace's helper holds the addresses and the network to dial them on.
String mode = inspect.getHostConfig() == null ? null : inspect.getHostConfig().getNetworkMode();
if (mode != null && mode.startsWith(CONTAINER_NETWORK_MODE)) {
inspect = dockerClient.inspectContainerCmd(mode.substring(CONTAINER_NETWORK_MODE.length())).exec();
}
if (inspect.getNetworkSettings() != null) {
Map<String, ContainerNetwork> networks = inspect.getNetworkSettings().getNetworks();
NetworkTarget target = pickTarget(networks);
if (target != null) {
NetworkTarget target = pickTarget(networks,
ipv6 ? ContainerNetwork::getGlobalIPv6Address : ContainerNetwork::getIpAddress);
if (target != null || ipv6) {
return target;
}
String ip = inspect.getNetworkSettings().getIpAddress();
@@ -298,6 +361,9 @@ public class Ec2PortForwardManager {
instance.getInstanceId(), e.getMessage());
}
}
if (ipv6) {
return null;
}
String stored = instance.getContainerBridgeIp();
if (stored != null && !stored.isBlank()) {
return new NetworkTarget(null, stored);
@@ -310,30 +376,34 @@ public class Ec2PortForwardManager {
* falls back to the default bridge with a null network name (the sidecar stays on the bridge
* the instance is already on).
*/
static NetworkTarget pickTarget(Map<String, ContainerNetwork> networks) {
static NetworkTarget pickTarget(Map<String, ContainerNetwork> networks,
Function<ContainerNetwork, String> address) {
if (networks == null || networks.isEmpty()) {
return null;
}
for (Map.Entry<String, ContainerNetwork> entry : networks.entrySet()) {
String ip = entry.getValue() != null ? entry.getValue().getIpAddress() : null;
String ip = entry.getValue() != null ? address.apply(entry.getValue()) : null;
if (!"bridge".equals(entry.getKey()) && ip != null && !ip.isBlank()) {
return new NetworkTarget(entry.getKey(), ip);
}
}
ContainerNetwork bridge = networks.get("bridge");
if (bridge != null && bridge.getIpAddress() != null && !bridge.getIpAddress().isBlank()) {
return new NetworkTarget(null, bridge.getIpAddress());
String bridgeIp = bridge != null ? address.apply(bridge) : null;
if (bridgeIp != null && !bridgeIp.isBlank()) {
return new NetworkTarget(null, bridgeIp);
}
for (ContainerNetwork network : networks.values()) {
if (network != null && network.getIpAddress() != null && !network.getIpAddress().isBlank()) {
return new NetworkTarget(null, network.getIpAddress());
String ip = network != null ? address.apply(network) : null;
if (ip != null && !ip.isBlank()) {
return new NetworkTarget(null, ip);
}
}
return null;
}
/**
* Extracts the set of TCP ports to publish for an instance from its security groups.
* Extracts the set of TCP ports to publish for an instance from its security groups while
* security-group enforcement is off.
*
* <p>Only CIDR-sourced TCP rules are published: AWS makes a port opened to a referenced
* security group reachable from that group's private IPs, not from the host, so rules
@@ -343,13 +413,60 @@ public class Ec2PortForwardManager {
* spawn thousands of sidecars. The total is capped at {@code maxPerInstance}.
*/
public static Set<Integer> extractPublishablePorts(List<SecurityGroup> securityGroups, int maxPerInstance) {
return extractPorts(securityGroups, maxPerInstance, Ec2PortForwardManager::hasCidrSource);
}
/**
* The ports to publish while security-group enforcement is on. Host-published access is traffic
* from outside the VPC whose client address Docker may replace (Docker Desktop shows every host
* client as its gateway), so a port is published only when an ingress rule opens it to every
* address of a family, whatever that client is. A client's family is still seen on the host, so
* a port only {@code 0.0.0.0/0} opens binds the host's IPv4 addresses, one only {@code ::/0}
* opens binds its IPv6 addresses and is reached on the instance's Docker IPv6 address, which is
* what that rule admits, and one both open binds every address. A port only a narrower CIDR, a
* prefix list or a group reference opens stays reachable on the direct container path, where the
* firewall sees the peer's own ENI. Spans, SSH and the per-instance cap are handled as in
* {@link #extractPublishablePorts}.
*/
public static DesiredPorts extractWorldOpenPorts(List<SecurityGroup> securityGroups, int maxPerInstance) {
Set<Integer> ipv4 = extractPorts(securityGroups, maxPerInstance,
perm -> opensToEveryAddress(perm.getIpRanges() == null ? Stream.empty()
: perm.getIpRanges().stream().map(range -> range.getCidrIp())));
Set<Integer> ipv6 = extractPorts(securityGroups, maxPerInstance,
perm -> opensToEveryAddress(perm.getIpv6Ranges() == null ? Stream.empty()
: perm.getIpv6Ranges().stream().map(range -> range.getCidrIpv6())));
Map<Integer, PublishedPortFamily> ports = new LinkedHashMap<>();
for (Integer port : ipv4) {
ports.put(port, ipv6.contains(port) ? PublishedPortFamily.ANY : PublishedPortFamily.IPV4);
}
for (Integer port : ipv6) {
if (ports.containsKey(port)) {
continue;
}
if (ports.size() >= maxPerInstance) {
LOG.warnv("Capping published ports at {0} per instance", maxPerInstance);
break;
}
ports.put(port, PublishedPortFamily.IPV6);
}
return new DesiredPorts(ports);
}
/** Whether any of the CIDRs is a valid one with a prefix length of 0, which every address of its family matches. */
static boolean opensToEveryAddress(Stream<String> cidrs) {
return cidrs.filter(cidr -> cidr != null).map(String::trim)
.anyMatch(cidr -> cidr.endsWith("/0") && SecurityGroupPolicy.validCidr(cidr));
}
private static Set<Integer> extractPorts(List<SecurityGroup> securityGroups, int maxPerInstance,
Predicate<IpPermission> source) {
Set<Integer> ports = new LinkedHashSet<>();
for (SecurityGroup sg : securityGroups) {
if (sg == null || sg.getIpPermissions() == null) {
continue;
}
for (IpPermission perm : sg.getIpPermissions()) {
if (!isTcp(perm.getIpProtocol()) || !hasCidrSource(perm)) {
if (!isTcp(perm.getIpProtocol()) || !source.test(perm)) {
continue;
}
Integer from = perm.getFromPort();