mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
269a00fe75
commit
d8460bc305
13 files changed
+440
-71
No files matched your search
@@ -450,7 +450,7 @@ By default, security groups on EC2 instances and ECS `awsvpc` tasks are stored,
|
||||
|
||||
- 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.
|
||||
- While it is on, SSH is published, and an application port is published on the host only when an ingress rule opens it to every address (`0.0.0.0/0` or `::/0`), at launch or later, and only on the host addresses of that rule's family. Docker can replace a host client's address, so a port that only a narrower CIDR, a prefix list or a referenced group opens is reachable only from the Floci-managed containers that rule admits, not from the host.
|
||||
|
||||
See [Security Group Port Publishing](docs/services/ec2.md#security-group-port-publishing) for the details.
|
||||
|
||||
|
||||
@@ -228,9 +228,9 @@ With `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`, Floci prepares a s
|
||||
|
||||
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.
|
||||
Security-group permissions on a host-published port use the source visible inside Docker, and Docker can replace the original client address (Docker Desktop shows every host client as its gateway). So while enforcement is enabled, host-published access counts as traffic from outside the VPC: Floci publishes an application port only when an ingress rule opens it to every address, `0.0.0.0/0` or `::/0`, since such a rule admits a client whatever address it arrives with. A client's family is still seen on the host, so a port only `0.0.0.0/0` opens is published on the host's IPv4 addresses, one only `::/0` opens on its IPv6 addresses, and one both open on every address. The socat sidecar described below dials the instance through its protected namespace, on the instance's IPv4 address, or on its Docker IPv6 address when only `::/0` opens the port; on a Docker network without IPv6 such a port is not published. A port that only a narrower CIDR, a prefix list or a referenced group opens stays reachable on the direct container path, where the firewall sees the peer's own ENI identity. Ports a rule opens after launch are published and revoking the rule removes the forward, as with enforcement disabled. SSH is published directly by the protected namespace.
|
||||
|
||||
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:
|
||||
When enforcement is disabled, an instance's security groups can open a TCP port to any 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:
|
||||
|
||||
```
|
||||
Published EC2 instance i-0abc... app port 80 on host port 30000 (socat -> 172.17.0.3:80)
|
||||
@@ -239,10 +239,11 @@ Published EC2 instance i-0abc... app port 80 on host port 30000 (socat -> 172.17
|
||||
Notes and limitations:
|
||||
|
||||
- The app inside the instance must listen on `0.0.0.0` (not `127.0.0.1`) for the forward to reach it.
|
||||
- Only CIDR-sourced TCP rules are published. A port opened only to a referenced security group (or via a prefix list) is not published, matching AWS: those grant reachability from the referenced group's private IPs, not from the host. The source CIDR value itself is not enforced, so a CIDR-sourced port is reachable whether the rule is `0.0.0.0/0` or narrower.
|
||||
- Only CIDR-sourced TCP rules are published. A port opened only to a referenced security group (or via a prefix list) is not published, matching AWS: those grant reachability from the referenced group's private IPs, not from the host. With enforcement disabled the source CIDR value itself is not enforced, so a CIDR-sourced port is reachable whether the rule is `0.0.0.0/0` or narrower; with it enabled only a rule open to every address publishes the port, as described above.
|
||||
- Ports are aggregated across all of the instance's security groups, SSH (22) is never re-forwarded, and any single rule whose port span exceeds `max-published-ports-per-instance` (default 20) is skipped so an allow-all range cannot spawn thousands of sidecars. The total published per instance is capped at the same limit.
|
||||
- Stopping an instance tears down its forwards; starting it again does not automatically restore them (re-run `authorize-security-group-ingress`, or recreate the instance).
|
||||
- With enforcement disabled, set `publish-security-group-ports: false` (`FLOCI_SERVICES_EC2_PUBLISH_SECURITY_GROUP_PORTS=false`) to keep security groups as metadata only.
|
||||
- When Floci restarts, each running instance's forwards are brought in line with its current rules: a forward a rule no longer opens, or that enforcement no longer allows, is removed, and one the rules now open is published.
|
||||
- Set `publish-security-group-ports: false` (`FLOCI_SERVICES_EC2_PUBLISH_SECURITY_GROUP_PORTS=false`) to publish no application port; with enforcement disabled, that keeps security groups as metadata only.
|
||||
|
||||
## UserData
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -3,8 +3,10 @@ package io.floci.aws.services.ec2;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.model.PublishedPortFamily;
|
||||
import io.floci.aws.services.ec2.model.Reservation;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import io.floci.aws.testing.IpPermissions;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
@@ -23,6 +25,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -106,6 +110,22 @@ class Ec2RestoreEveryAccountIntegrationTest {
|
||||
.anyMatch(listed -> listed.getInstanceId().equals(instance.getInstanceId()))));
|
||||
}
|
||||
|
||||
// Catches: a restart bringing back a forward the instance's current rules would not publish, one kept from a run
|
||||
// with enforcement off or from rules changed while Floci was down, and never publishing one they open.
|
||||
@Test
|
||||
void restoreBringsForwardsToTheInstancesCurrentRules() throws Throwable {
|
||||
Instance instance = runningInstanceOf(OTHER_ACCOUNT);
|
||||
String group = instance.getSecurityGroups().getFirst().getGroupId();
|
||||
RequestScopes.callAs(OTHER_ACCOUNT, () -> service.authorizeSecurityGroupIngress(REGION, group,
|
||||
List.of(IpPermissions.tcp(80, "0.0.0.0/0"), IpPermissions.tcp(8080, "10.0.0.0/8"))));
|
||||
clearInvocations(portForwardManager);
|
||||
|
||||
restoreOutsideAnyRequest();
|
||||
|
||||
verify(portForwardManager).reconcile(argThat(restored -> isSame(restored, instance)),
|
||||
eq(new Ec2PortForwardManager.DesiredPorts(Map.of(80, PublishedPortFamily.IPV4))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownWritesAnotherAccountsInstanceOnlyToItsOwnAccount() throws Throwable {
|
||||
Instance instance = runningInstanceOf(OTHER_ACCOUNT);
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.model.IpPermission;
|
||||
import io.floci.aws.services.ec2.model.NetworkInterface;
|
||||
import io.floci.aws.services.ec2.model.PublishedPortFamily;
|
||||
import io.floci.aws.services.ec2.model.Reservation;
|
||||
import io.floci.aws.services.ec2.model.SecurityGroup;
|
||||
import io.floci.aws.services.ec2.model.SecurityGroupRule;
|
||||
@@ -16,6 +17,7 @@ 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;
|
||||
import io.floci.aws.testing.IpPermissions;
|
||||
import io.floci.aws.testing.ParkingStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -741,12 +743,40 @@ class Ec2SecurityGroupPublicationRaceTest {
|
||||
|
||||
service.modifyNetworkInterfaceAttribute(region, secondary,
|
||||
new Ec2Service.NetworkInterfaceAttributeChange(List.of(replacement), null, null, null, null), false);
|
||||
verify(ports, never()).reconcile(any(), anySet());
|
||||
verify(ports, never()).reconcile(any(), any());
|
||||
|
||||
service.modifyNetworkInterfaceAttribute(region, primary,
|
||||
new Ec2Service.NetworkInterfaceAttributeChange(List.of(replacement), null, null, null, null), false);
|
||||
verify(ports).reconcile(argThat(reconciled -> instance.getInstanceId().equals(reconciled.getInstanceId())),
|
||||
anySet());
|
||||
any());
|
||||
}
|
||||
|
||||
// Catches: enforcement publishing a port only a narrower CIDR opens, judged on a host client address Docker may
|
||||
// have replaced, or publishing none at all; each port admits the family whose world-open rule opens it.
|
||||
@Test
|
||||
void withEnforcementOnlyRulesOpenToEveryAddressPublishPorts() {
|
||||
TestStores factory = new TestStores();
|
||||
EmulatorConfig config = mockConfig();
|
||||
Ec2PortForwardManager ports = mock(Ec2PortForwardManager.class);
|
||||
Ec2Service service = service(factory, config, mock(Ec2ContainerManager.class), ports);
|
||||
String region = "us-east-1";
|
||||
String vpc = service.createVpc(region, "10.0.0.0/16", false).getVpcId();
|
||||
String subnet = service.createSubnet(region, vpc, "10.0.1.0/24", region + "a").getSubnetId();
|
||||
String group = service.createSecurityGroup(region, "world-open", "world-open", vpc).getGroupId();
|
||||
Instance instance = service.runInstances(region, "ami-test", "t3.micro", 1, 1, null,
|
||||
List.of(group), subnet, null, List.of(), null, null).getInstances().getFirst();
|
||||
instance.setState(InstanceState.running());
|
||||
instance.setDockerContainerId("container-world-open");
|
||||
enableEnforcement(config);
|
||||
when(config.services().ec2().publishSecurityGroupPorts()).thenReturn(true);
|
||||
when(config.services().ec2().maxPublishedPortsPerInstance()).thenReturn(20);
|
||||
|
||||
service.authorizeSecurityGroupIngress(region, group, List.of(IpPermissions.tcp(80, "0.0.0.0/0"),
|
||||
IpPermissions.tcp(8080, "10.0.0.0/8"), IpPermissions.tcp(443, "::/0")));
|
||||
|
||||
verify(ports).reconcile(argThat(reconciled -> instance.getInstanceId().equals(reconciled.getInstanceId())),
|
||||
eq(new Ec2PortForwardManager.DesiredPorts(Map.of(80, PublishedPortFamily.IPV4,
|
||||
443, PublishedPortFamily.IPV6))));
|
||||
}
|
||||
|
||||
/** A dual-stack subnet's interface, with enforcement on and the container manager a mock. */
|
||||
|
||||
@@ -5325,7 +5325,7 @@ class Ec2ServiceTest {
|
||||
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
|
||||
() -> fixture.service().createNetworkInterface("us-east-1", fixture.subnetId(), null,
|
||||
null, List.of("10.50.1.20"), List.of(), List.of(), 2)).getErrorCode());
|
||||
verify(fixture.vpcNetworks(), never()).allocatePrivateIp(anyString(), anyString());
|
||||
verify(fixture.vpcNetworks(), never()).allocatePrivateIp(anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+150
-20
@@ -1,6 +1,9 @@
|
||||
package io.floci.aws.services.ec2.portforward;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectContainerCmd;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
@@ -12,9 +15,10 @@ import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
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.PublishedPortFamily;
|
||||
import io.floci.aws.services.ec2.model.SecurityGroup;
|
||||
import io.floci.aws.services.ec2.model.UserIdGroupPair;
|
||||
import io.floci.aws.testing.IpPermissions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
@@ -23,6 +27,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -31,6 +36,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.atLeast;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
@@ -67,13 +73,7 @@ class Ec2PortForwardManagerTest {
|
||||
|
||||
@Test
|
||||
void publishesIpv6SourcedRules() {
|
||||
IpPermission perm = new IpPermission();
|
||||
perm.setIpProtocol("tcp");
|
||||
perm.setFromPort(80);
|
||||
perm.setToPort(80);
|
||||
perm.getIpv6Ranges().add(new Ipv6Range("::/0"));
|
||||
|
||||
assertEquals(Set.of(80), extract(sg(perm)));
|
||||
assertEquals(Set.of(80), extract(sg(IpPermissions.tcp(80, "::/0"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -205,7 +205,7 @@ class Ec2PortForwardManagerTest {
|
||||
instance.setDockerContainerId("c1");
|
||||
instance.setState(InstanceState.shuttingDown());
|
||||
|
||||
manager.reconcileNow(instance, Set.of(80));
|
||||
manager.reconcileNow(instance, Ec2PortForwardManager.DesiredPorts.anyFamily(Set.of(80)));
|
||||
|
||||
assertTrue(instance.getPublishedPorts().isEmpty(),
|
||||
"a reconcile racing a terminate must not republish against the removed container");
|
||||
@@ -236,7 +236,7 @@ class Ec2PortForwardManagerTest {
|
||||
instance.setDockerContainerId("c1");
|
||||
instance.setState(InstanceState.running());
|
||||
|
||||
manager.reconcileNow(instance, Set.of(80));
|
||||
manager.reconcileNow(instance, Ec2PortForwardManager.DesiredPorts.anyFamily(Set.of(80)));
|
||||
|
||||
verify(portAllocator).allocate(30000, 30999);
|
||||
}
|
||||
@@ -245,6 +245,124 @@ class Ec2PortForwardManagerTest {
|
||||
void publishedForwardDisablesNagleAndBindsABurstTolerantAcceptBacklog() {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
when(dockerClient.inspectContainerCmd(anyString())).thenThrow(new RuntimeException("docker down"));
|
||||
Forwarding forwarding = forwarding(dockerClient);
|
||||
Instance instance = running();
|
||||
instance.setContainerBridgeIp("172.17.0.3");
|
||||
|
||||
forwarding.manager().reconcileNow(instance, Ec2PortForwardManager.DesiredPorts.anyFamily(Set.of(80)));
|
||||
|
||||
ContainerSpec spec = forwarding.created().getFirst();
|
||||
assertEquals("alpine/socat", spec.image());
|
||||
assertEquals(List.of("socat"), spec.entrypoint());
|
||||
assertEquals(List.of("TCP-LISTEN:80,fork,reuseaddr,nodelay,backlog=4096",
|
||||
"TCP:172.17.0.3:80,nodelay"), spec.cmd());
|
||||
assertEquals(Map.of(80, 30000), spec.portBindings());
|
||||
}
|
||||
|
||||
// Catches: enforcement publishing a port only a narrower CIDR, a group reference or SSH opens, judged on a host
|
||||
// client address Docker may have replaced; each port admits the family whose world-open rule opens it.
|
||||
@Test
|
||||
void underEnforcementOnlyPortsOpenToEveryAddressArePublished() {
|
||||
IpPermission groupOnly = new IpPermission();
|
||||
groupOnly.setIpProtocol("tcp");
|
||||
groupOnly.setFromPort(9000);
|
||||
groupOnly.setToPort(9000);
|
||||
UserIdGroupPair pair = new UserIdGroupPair();
|
||||
pair.setGroupId("sg-web");
|
||||
groupOnly.getUserIdGroupPairs().add(pair);
|
||||
SecurityGroup sg = sg(IpPermissions.tcp(80, "0.0.0.0/0"), IpPermissions.tcp(80, "::/0"),
|
||||
IpPermissions.tcp(8000, "0.0.0.0/0"), IpPermissions.tcp(8080, "10.0.0.0/8"),
|
||||
IpPermissions.tcp(443, "::/0"), IpPermissions.tcp(8443, "2600:1f18::/56"),
|
||||
IpPermissions.tcp(22, "0.0.0.0/0"), groupOnly);
|
||||
|
||||
Ec2PortForwardManager.DesiredPorts desired = Ec2PortForwardManager.extractWorldOpenPorts(List.of(sg), MAX);
|
||||
|
||||
assertEquals(Map.of(80, PublishedPortFamily.ANY, 8000, PublishedPortFamily.IPV4,
|
||||
443, PublishedPortFamily.IPV6), desired.ports());
|
||||
}
|
||||
|
||||
// Catches: the publisher still refusing to run while enforcement is on.
|
||||
@Test
|
||||
void thePublisherRunsWithEnforcementOn() {
|
||||
Forwarding forwarding = forwarding(mock(DockerClient.class));
|
||||
when(forwarding.config().services().ec2().publishSecurityGroupPorts()).thenReturn(true);
|
||||
when(forwarding.config().network().securityGroupEnforcement().enabled()).thenReturn(true);
|
||||
|
||||
assertTrue(forwarding.manager().enabled());
|
||||
}
|
||||
|
||||
// Catches: a sidecar dialling the instance container, which under enforcement holds no address of its own, rather
|
||||
// than its namespace's helper on the helper's network; a port only ::/0 opens dialled over IPv4, which that rule
|
||||
// never admits; and a port bound on every host address, which lets a client of the other family through.
|
||||
@Test
|
||||
void underEnforcementTheSidecarBindsAndDialsTheFamilyItsRuleOpens() {
|
||||
Forwarding forwarding = forwarding(protectedNamespace("172.18.0.5", "fd00:d0c::5"));
|
||||
Instance instance = running();
|
||||
|
||||
forwarding.manager().reconcileNow(instance, new Ec2PortForwardManager.DesiredPorts(Map.of(
|
||||
80, PublishedPortFamily.IPV4, 443, PublishedPortFamily.IPV6, 8080, PublishedPortFamily.ANY)));
|
||||
|
||||
Map<Integer, ContainerSpec> specs = forwarding.created().stream()
|
||||
.collect(Collectors.toMap(spec -> spec.portBindings().keySet().iterator().next(), spec -> spec));
|
||||
assertEquals(List.of("TCP-LISTEN:80,fork,reuseaddr,nodelay,backlog=4096", "TCP:172.18.0.5:80,nodelay"),
|
||||
specs.get(80).cmd());
|
||||
assertEquals(Map.of(80, "0.0.0.0"), specs.get(80).portBindingHostIps());
|
||||
assertEquals(List.of("TCP6-LISTEN:443,ipv6only=0,fork,reuseaddr,nodelay,backlog=4096",
|
||||
"TCP6:[fd00:d0c::5]:443,nodelay"), specs.get(443).cmd());
|
||||
assertEquals(Map.of(443, "::"), specs.get(443).portBindingHostIps());
|
||||
assertEquals("TCP:172.18.0.5:8080,nodelay", specs.get(8080).cmd().get(1));
|
||||
assertEquals(Map.of(), specs.get(8080).portBindingHostIps());
|
||||
assertEquals(Set.of("floci-net"), specs.values().stream().map(ContainerSpec::networkMode)
|
||||
.collect(Collectors.toSet()));
|
||||
assertEquals(Map.of(80, PublishedPortFamily.IPV4, 443, PublishedPortFamily.IPV6),
|
||||
instance.getPublishedPortFamilies());
|
||||
}
|
||||
|
||||
// Catches: a port whose opening rules moved family keeping a sidecar that binds or dials the old one, which
|
||||
// admits the wrong clients or which the firewall now drops.
|
||||
@Test
|
||||
void aPortWhoseRulesMoveFamilyIsRepublished() {
|
||||
Forwarding forwarding = forwarding(protectedNamespace("172.18.0.5", "fd00:d0c::5"));
|
||||
Instance instance = running();
|
||||
forwarding.manager().reconcileNow(instance, Ec2PortForwardManager.DesiredPorts.anyFamily(Set.of(80)));
|
||||
|
||||
forwarding.manager().reconcileNow(instance,
|
||||
new Ec2PortForwardManager.DesiredPorts(Map.of(80, PublishedPortFamily.IPV6)));
|
||||
forwarding.manager().reconcileNow(instance, Ec2PortForwardManager.DesiredPorts.anyFamily(Set.of(80)));
|
||||
|
||||
assertEquals(List.of("TCP:172.18.0.5:80,nodelay", "TCP6:[fd00:d0c::5]:80,nodelay", "TCP:172.18.0.5:80,nodelay"),
|
||||
forwarding.created().stream().map(spec -> spec.cmd().get(1)).toList());
|
||||
assertEquals(Map.of(80, 30000), instance.getPublishedPorts());
|
||||
assertEquals(Map.of(), instance.getPublishedPortFamilies());
|
||||
}
|
||||
|
||||
// Catches: a port only ::/0 opens published on a Docker network without IPv6, where its rule admits nothing, or
|
||||
// dialled on the stored IPv4 address instead.
|
||||
@Test
|
||||
void aPortOnlyIpv6OpensIsNotPublishedWithoutAnIpv6Address() {
|
||||
Forwarding forwarding = forwarding(protectedNamespace("172.18.0.5", null));
|
||||
Instance instance = running();
|
||||
instance.setContainerBridgeIp("172.18.0.5");
|
||||
|
||||
forwarding.manager().reconcileNow(instance,
|
||||
new Ec2PortForwardManager.DesiredPorts(Map.of(443, PublishedPortFamily.IPV6)));
|
||||
|
||||
assertTrue(forwarding.created().isEmpty());
|
||||
assertTrue(instance.getPublishedPorts().isEmpty());
|
||||
verify(forwarding.portAllocator()).release(30000);
|
||||
}
|
||||
|
||||
/** A manager that builds real sidecar specs, allocating host port 30000 for every forward. */
|
||||
private record Forwarding(Ec2PortForwardManager manager, ContainerLifecycleManager lifecycle,
|
||||
PortAllocator portAllocator, EmulatorConfig config) {
|
||||
List<ContainerSpec> created() {
|
||||
ArgumentCaptor<ContainerSpec> spec = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycle, atLeast(0)).create(spec.capture());
|
||||
return spec.getAllValues();
|
||||
}
|
||||
}
|
||||
|
||||
private static Forwarding forwarding(DockerClient dockerClient) {
|
||||
PortAllocator portAllocator = mock(PortAllocator.class);
|
||||
when(portAllocator.allocate(anyInt(), anyInt())).thenReturn(30000);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
@@ -261,22 +379,34 @@ class Ec2PortForwardManagerTest {
|
||||
dockerClient,
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, portAllocator, config);
|
||||
return new Forwarding(manager, lifecycleManager, portAllocator, config);
|
||||
}
|
||||
|
||||
private static Instance running() {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-1");
|
||||
instance.setDockerContainerId("c1");
|
||||
instance.setState(InstanceState.running());
|
||||
instance.setContainerBridgeIp("172.17.0.3");
|
||||
return instance;
|
||||
}
|
||||
|
||||
manager.reconcileNow(instance, Set.of(80));
|
||||
|
||||
ArgumentCaptor<ContainerSpec> spec = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycleManager).create(spec.capture());
|
||||
assertEquals("alpine/socat", spec.getValue().image());
|
||||
assertEquals(List.of("socat"), spec.getValue().entrypoint());
|
||||
assertEquals(List.of("TCP-LISTEN:80,fork,reuseaddr,nodelay,backlog=4096",
|
||||
"TCP:172.17.0.3:80,nodelay"), spec.getValue().cmd());
|
||||
assertEquals(Map.of(80, 30000), spec.getValue().portBindings());
|
||||
/** Instance container {@code c1} joins {@code helper-1}'s namespace, which holds the addresses on floci-net. */
|
||||
private static DockerClient protectedNamespace(String ipv4, String ipv6) {
|
||||
InspectContainerResponse instance = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
|
||||
when(instance.getHostConfig().getNetworkMode()).thenReturn("container:helper-1");
|
||||
ContainerNetwork network = mock(ContainerNetwork.class);
|
||||
when(network.getIpAddress()).thenReturn(ipv4);
|
||||
when(network.getGlobalIPv6Address()).thenReturn(ipv6);
|
||||
InspectContainerResponse helper = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
|
||||
when(helper.getNetworkSettings().getNetworks()).thenReturn(Map.of("floci-net", network));
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
InspectContainerCmd instanceCmd = mock(InspectContainerCmd.class);
|
||||
when(instanceCmd.exec()).thenReturn(instance);
|
||||
when(docker.inspectContainerCmd("c1")).thenReturn(instanceCmd);
|
||||
InspectContainerCmd helperCmd = mock(InspectContainerCmd.class);
|
||||
when(helperCmd.exec()).thenReturn(helper);
|
||||
when(docker.inspectContainerCmd("helper-1")).thenReturn(helperCmd);
|
||||
return docker;
|
||||
}
|
||||
|
||||
private static Set<Integer> extract(SecurityGroup sg) {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import io.floci.aws.services.ec2.model.IpPermission;
|
||||
import io.floci.aws.services.ec2.model.IpRange;
|
||||
import io.floci.aws.services.ec2.model.Ipv6Range;
|
||||
|
||||
/** Security-group permissions for tests. */
|
||||
public final class IpPermissions {
|
||||
|
||||
private IpPermissions() {
|
||||
}
|
||||
|
||||
/** A TCP permission on one port, open to each CIDR given: an IPv6 one goes to {@code Ipv6Ranges}. */
|
||||
public static IpPermission tcp(int port, String... cidrs) {
|
||||
return tcp(port, port, cidrs);
|
||||
}
|
||||
|
||||
/** A TCP permission on a port range, open to each CIDR given: an IPv6 one goes to {@code Ipv6Ranges}. */
|
||||
public static IpPermission tcp(int fromPort, int toPort, String... cidrs) {
|
||||
IpPermission permission = new IpPermission();
|
||||
permission.setIpProtocol("tcp");
|
||||
permission.setFromPort(fromPort);
|
||||
permission.setToPort(toPort);
|
||||
for (String cidr : cidrs) {
|
||||
if (cidr.indexOf(':') >= 0) {
|
||||
permission.getIpv6Ranges().add(new Ipv6Range(cidr));
|
||||
} else {
|
||||
permission.getIpRanges().add(new IpRange(cidr));
|
||||
}
|
||||
}
|
||||
return permission;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user