feat(ec2): EC2 Instance Connect Endpoint tunnel (open-tunnel / eice SSH over WebSocket) (#7519)

This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-11-11 14:08:37 -04:00
1 parent c769ce055a
commit 475fb1822a
15 files changed
+1249 -15

No files matched your search

+39 -1
View File
@@ -58,4 +58,42 @@ must provide one (the instance ID is in the guest's `AWS_EC2_INSTANCE_ID` enviro
`ec2:osuser` condition key.
- The signing material lives in memory: a restart issues a new intermediate and signers under the
same local CA, so guests keep verifying.
- EC2 Instance Connect Endpoint tunnels.
## Instance Connect Endpoint tunnels
`aws ec2-instance-connect open-tunnel` and `aws ec2-instance-connect ssh --connection-type eice`
open a SigV4-presigned WebSocket to `wss://<endpoint DnsName>/openTunnel`, and binary frames carry
the TCP stream to the instance. Endpoint DNS names are `<endpoint id>.localhost.floci.io`, which
public DNS resolves to `127.0.0.1` and Floci's wildcard certificate covers.
Floci serves `/openTunnel` on every listener, plain HTTP included, but the AWS CLI only dials
`wss://` on port 443. So the CLI needs `FLOCI_TLS_ENABLED=true`, the client's loopback port 443
must reach Floci's port (publish `127.0.0.1:443:4566`, or forward it inside a client container),
and the operating system's trust store (not `AWS_CA_BUNDLE`, which the tunnel's TLS ignores) must
trust Floci's local CA (`GET /_floci/ca.pem`).
The route sits outside Floci's JAX-RS request filters, so it applies their rules itself. Before the
WebSocket upgrade, Floci checks what AWS checks and answers a refusal as an HTTP error the CLI
prints:
| Check | Refusal |
| --- | --- |
| The URL is presigned for `ec2-instance-connect`, `X-Amz-Expires` is 1 to 604800 seconds, the URL has not expired, and it was not signed more than five minutes ahead | 403 |
| With `floci.auth.validate-signatures`, the signature verifies against the access key's secret (the CLI signs `GET /openTunnel`, the query and `host`) | 403 |
| With IAM enforcement, the access key is known and is allowed `ec2-instance-connect:OpenTunnel` on the endpoint's ARN | 403 |
| `remotePort` is 22 or 3389, `maxTunnelDuration` is 1 to 3600 seconds | 400 |
| The endpoint exists, in a usable state, in the account the credential's access key belongs to | 404 |
| A running instance holds `privateIpAddress` in the endpoint's VPC | 404 |
| The endpoint's security groups allow the port out to the instance, and the instance's allow it in from the endpoint's address or groups | 403 |
| The instance accepts the TCP connection | 504 |
The account is resolved from the access key as for every other request: a 12-digit key is that
account, an IAM or session key is its owner's, and anything else is the default account. With
signature validation off (the default) the signature is not checked, as for every other service.
An unreachable instance takes up to about 20 seconds to answer 504: Floci tries the container's address
and then the published SSH port, each with a 10 second connect timeout.
The tunnel closes after `maxTunnelDuration` (3600 seconds by default), and either side closing
closes the other. `PreserveClientIp` is recorded but not modelled: the instance always sees, and
its security groups are evaluated against, the endpoint's own address and groups.
+1 -1
View File
@@ -838,7 +838,7 @@ back, and a new address that is already held fails the update and leaves the gat
| DescribeInstanceConnectEndpoints | Lists endpoints; filters `instance-connect-endpoint-id`, `state`, `vpc-id`, `subnet-id`, `tag:<key>`, `tag-key`, `tag-value`. |
| DeleteInstanceConnectEndpoint | Deletes an endpoint and answers with it in `delete-in-progress`. |
A repeated `ClientToken` returns the endpoint the first call created (`IdempotentParameterMismatch` when reused with another subnet, security group set, `IpAddressType`, `PreserveClientIp` or tag set; tags added later with `CreateTags` do not count). While an endpoint exists, `DeleteSubnet` on its subnet and `DeleteVpc` on its VPC fail with `DependencyViolation`, as on AWS. The interface ID in an endpoint's `networkInterfaceIdSet` resolves in `DescribeNetworkInterfaces` while the endpoint exists: a requester-managed `ec2_instance_connect_endpoint` interface carrying the endpoint's private address, subnet, VPC and security groups. An unknown filter name is `InvalidParameterValue` even when no endpoint exists. `DescribeInstanceConnectEndpoints` pages by `MaxResults`/`NextToken` in endpoint ID order (`MaxResults` outside 1-50 is `InvalidMaxResults`), and `publicDnsNames` carries only the `ipv4` names. The endpoint's tunnel (`openTunnel`) is not served yet.
A repeated `ClientToken` returns the endpoint the first call created (`IdempotentParameterMismatch` when reused with another subnet, security group set, `IpAddressType`, `PreserveClientIp` or tag set; tags added later with `CreateTags` do not count). While an endpoint exists, `DeleteSubnet` on its subnet and `DeleteVpc` on its VPC fail with `DependencyViolation`, as on AWS. The interface ID in an endpoint's `networkInterfaceIdSet` resolves in `DescribeNetworkInterfaces` while the endpoint exists: a requester-managed `ec2_instance_connect_endpoint` interface carrying the endpoint's private address, subnet, VPC and security groups. An unknown filter name is `InvalidParameterValue` even when no endpoint exists. `DescribeInstanceConnectEndpoints` pages by `MaxResults`/`NextToken` in endpoint ID order (`MaxResults` outside 1-50 is `InvalidMaxResults`), and `publicDnsNames` carries only the `ipv4` names. The endpoint's tunnel is real: see [EC2 Instance Connect](ec2-instance-connect.md#instance-connect-endpoint-tunnels).
### Capacity Reservations
@@ -158,7 +158,8 @@ public class IamConditionContextResolver {
case "iam" -> iamConditionContext(action, ctx);
case "logs" -> logsConditionContext(action, ctx);
case "lambda" -> lambdaConditionContext(action, ctx);
case "redshift" -> redshiftConditionContext(action, ctx);
case "redshift" -> RequestConditionKeys.requestKeys(action).isEmpty() ? null
: requestConditions(action, formParameters(ctx)::get);
default -> null;
};
}
@@ -308,17 +309,16 @@ public class IamConditionContextResolver {
};
}
/** The {@code redshift:} keys a Redshift request carries in its own members, such as its DbUser. */
private Map<String, List<String>> redshiftConditionContext(String action, ContainerRequestContext ctx) {
List<String> keys = RequestConditionKeys.requestKeys(action);
if (keys.isEmpty()) {
return null;
}
Map<String, String> form = formParameters(ctx);
/**
* The keys a request for {@code action} carries in its own members, such as a Redshift DbUser or an
* OpenTunnel remotePort, read through {@code parameter} from the table in
* {@code request-condition-keys.json}; null when it carries none.
*/
static Map<String, List<String>> requestConditions(String action, Function<String, String> parameter) {
Map<String, List<String>> conditions = new LinkedHashMap<>();
for (String key : keys) {
for (String key : RequestConditionKeys.requestKeys(action)) {
for (String member : RequestConditionKeys.members(action, key)) {
putIfPresent(conditions, key, form.get(member));
putIfPresent(conditions, key, parameter.apply(member));
}
}
return conditions.isEmpty() ? null : conditions;
@@ -1459,6 +1459,20 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
authorizeAdditionalResource(authorizationHeader, action, resource, null, null, null, requestConditions);
}
/**
* Authorizes a secondary resource for a request {@link #filter} never sees, such as a WebSocket upgrade,
* with the condition keys the request carries in the members {@code request-condition-keys.json} names
* for {@code action}, read through {@code parameter}.
*/
public void authorizeRequestParameters(
String authorizationHeader,
String action,
String resource,
Function<String, String> parameter) {
authorizeAdditionalResource(authorizationHeader, action, resource,
IamConditionContextResolver.requestConditions(action, parameter));
}
/**
* Authorizes a browser POST upload, a PostObject, as {@code s3:PutObject} on {@code resource}.
* Its credential is only in the form body, so {@link #filter} never sees it, and a denial is
@@ -12888,6 +12888,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
/** The public suffix every endpoint DNS name ends in; it resolves to 127.0.0.1 in public DNS. */
static final String INSTANCE_CONNECT_ENDPOINT_DNS_SUFFIX = "localhost.floci.io";
private static final Set<String> INSTANCE_CONNECT_ENDPOINT_IP_TYPES = Set.of("ipv4", "dualstack", "ipv6");
/** States the AWS CLI accepts as usable when it looks an endpoint up for a tunnel. */
private static final Set<String> USABLE_INSTANCE_CONNECT_ENDPOINT_STATES =
Set.of("create-complete", "update-in-progress", "update-complete", "update-failed");
/**
* The names matchesInstanceConnectEndpointFilter implements, exactly the DescribeInstanceConnectEndpoints
* reference's list; tag:&lt;key&gt; is admitted through tag-key.
@@ -13073,6 +13076,49 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return endpoint;
}
/** The usable endpoint a tunnel names, or empty: unknown, or not in a state the CLI would use. */
public Optional<InstanceConnectEndpoint> findUsableInstanceConnectEndpoint(String region, String id) {
return instanceConnectEndpoints.get(key(region, id))
.filter(endpoint -> USABLE_INSTANCE_CONNECT_ENDPOINT_STATES.contains(endpoint.getState()));
}
/** The running instance in {@code vpcId} holding {@code privateIp}: what a tunnel connects to. */
public Optional<Instance> findRunningInstanceByPrivateIp(String region, String vpcId, String privateIp) {
return instances.scan(k -> true).stream()
.filter(instance -> region.equals(instance.getRegion()))
.filter(instance -> vpcId.equals(instance.getVpcId()) && privateIp.equals(instance.getPrivateIpAddress()))
.filter(instance -> instance.getState() != null && "running".equals(instance.getState().getName()))
.findFirst();
}
/**
* Whether the endpoint may open {@code port} on {@code instance}: its own groups must allow the
* traffic out, and the instance's groups must allow it in from the endpoint, the way AWS
* evaluates a tunnel. The source is always the endpoint's own address and groups:
* {@code PreserveClientIp} is recorded but not modelled, so a rule that admits only the
* client's address does not admit the tunnel here.
*/
public boolean instanceConnectEndpointMayReach(InstanceConnectEndpoint endpoint, Instance instance, int port) {
String region = endpoint.getRegion();
List<SecurityGroup> endpointGroups = groupsById(region, endpoint.getSecurityGroupIds());
List<String> instanceGroupIds = instance.getSecurityGroups() == null ? List.of()
: instance.getSecurityGroups().stream().map(GroupIdentifier::getGroupId).toList();
List<SecurityGroup> instanceGroups = groupsById(region, instanceGroupIds);
SecurityGroupPolicy.Peer target = new SecurityGroupPolicy.Peer(instance.getPrivateIpAddress(),
instance.getOwnerId(), instance.getVpcId(), new HashSet<>(instanceGroupIds));
SecurityGroupPolicy.Peer source = new SecurityGroupPolicy.Peer(endpoint.getPrivateIpAddress(),
endpoint.getOwnerId(), endpoint.getVpcId(), new HashSet<>(endpoint.getSecurityGroupIds()));
return SecurityGroupPolicy.allows(endpointGroups, true, "tcp", port, -1, target,
policyPrefixLists(region, endpointGroups))
&& SecurityGroupPolicy.allows(instanceGroups, false, "tcp", port, -1, source,
policyPrefixLists(region, instanceGroups));
}
private List<SecurityGroup> groupsById(String region, List<String> ids) {
return ids.stream().map(id -> securityGroups.get(key(region, id)).orElse(null))
.filter(Objects::nonNull).toList();
}
private InstanceConnectEndpoint requireInstanceConnectEndpoint(String region, String id) {
return instanceConnectEndpoints.get(key(region, id)).orElseThrow(() -> new AwsException(
"InvalidInstanceConnectEndpointId.NotFound",
@@ -0,0 +1,368 @@
package io.floci.aws.services.ec2instanceconnect;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AccountResolver;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.IamEnforcementFilter;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.SessionAccountLookup;
import io.floci.aws.core.common.auth.CredentialScope;
import io.floci.aws.core.common.auth.SigV4Canonicalization;
import io.floci.aws.core.common.auth.SigV4RequestValidator;
import io.floci.aws.core.common.auth.SigV4SignedRequest;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.InstanceConnectEndpoint;
import io.floci.aws.services.iam.IamService;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetSocket;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.UnaryOperator;
/**
* The EC2 Instance Connect Endpoint data plane: {@code wss://<endpoint DnsName>/openTunnel}, the
* SigV4-presigned WebSocket the AWS CLI opens for {@code aws ec2-instance-connect open-tunnel} and
* {@code ssh --connection-type eice}. Each binary frame carries raw TCP bytes to and from the
* instance's port, the same contract as AWS's endpoint.
*
* <p>This is a plain Vert.x route, so none of the JAX-RS filters run for it; it applies their rules
* itself. Checked before the upgrade, each refusal answered as an HTTP error the CLI prints:
* <ul>
* <li>the presigned query: scoped to {@code ec2-instance-connect}, {@code X-Amz-Expires} from 1
* to 604800 seconds, not expired, not signed more than five minutes ahead;</li>
* <li>with {@code floci.auth.validate-signatures}, the signature itself, verified with
* {@link SigV4Canonicalization} as {@code SigV4HeaderSignatureFilter} verifies every other
* service's;</li>
* <li>the account: the credential's access key picks it, as {@code AccountContextFilter} does,
* and the endpoint and instance are looked up in that account only;</li>
* <li>with IAM enforcement, {@code ec2-instance-connect:OpenTunnel} on the endpoint's ARN;</li>
* <li>the endpoint (known, usable), the target (a running instance at that private address in
* the endpoint's VPC), the port (22 or 3389, as AWS allows), and the security groups (the
* endpoint's egress and the instance's ingress must both allow the port).</li>
* </ul>
*/
@ApplicationScoped
public class InstanceConnectTunnelHandler {
private static final Logger LOG = Logger.getLogger(InstanceConnectTunnelHandler.class);
public static final String PATH = "/openTunnel";
static final String SIGNING_SERVICE = "ec2-instance-connect";
static final String OPEN_TUNNEL_ACTION = "ec2-instance-connect:OpenTunnel";
/** The ports an EC2 Instance Connect Endpoint forwards: SSH and RDP. */
static final Set<Integer> ALLOWED_PORTS = Set.of(22, 3389);
/** AWS's limit, and the CLI's default, for {@code maxTunnelDuration}. */
static final int MAX_TUNNEL_SECONDS = 3600;
private static final int CONNECT_TIMEOUT_MILLIS = 10_000;
/** The well-known local-dev pair, honoured as every other SigV4 check in Floci honours it. */
private static final String LEGACY_ACCESS_KEY_ID = "test";
private static final String LEGACY_SECRET_KEY = "test";
private final Ec2Service ec2Service;
private final Vertx vertx;
private final EmulatorConfig config;
private final IamService iamService;
private final AccountResolver accountResolver;
private final SessionAccountLookup sessionAccountLookup;
private final IamEnforcementFilter iamEnforcement;
private final Clock clock;
private NetClient netClient;
@Inject
public InstanceConnectTunnelHandler(Ec2Service ec2Service, Vertx vertx, EmulatorConfig config,
IamService iamService, AccountResolver accountResolver,
SessionAccountLookup sessionAccountLookup,
IamEnforcementFilter iamEnforcement) {
this(ec2Service, vertx, config, iamService, accountResolver, sessionAccountLookup, iamEnforcement,
Clock.systemUTC());
}
InstanceConnectTunnelHandler(Ec2Service ec2Service, Vertx vertx, EmulatorConfig config, IamService iamService,
AccountResolver accountResolver, SessionAccountLookup sessionAccountLookup,
IamEnforcementFilter iamEnforcement, Clock clock) {
this.ec2Service = ec2Service;
this.vertx = vertx;
this.config = config;
this.iamService = iamService;
this.accountResolver = accountResolver;
this.sessionAccountLookup = sessionAccountLookup;
this.iamEnforcement = iamEnforcement;
this.clock = clock;
}
void init(@Observes Router router) {
netClient = vertx.createNetClient(new NetClientOptions().setConnectTimeout(CONNECT_TIMEOUT_MILLIS));
router.route(PATH).handler(this::open);
LOG.debugv("Registered the EC2 Instance Connect Endpoint tunnel on {0}", PATH);
}
/** What a valid request resolved to. */
record Target(InstanceConnectEndpoint endpoint, Instance instance, String host, int port, int maxSeconds,
String fallbackHost, int fallbackPort) { }
/** Thrown for a request the endpoint refuses; the status and message become the HTTP answer. */
static final class Refusal extends RuntimeException {
final int status;
Refusal(int status, String message) {
super(message);
this.status = status;
}
}
void open(RoutingContext ctx) {
String upgrade = ctx.request().getHeader("Upgrade");
if (upgrade == null || !"websocket".equalsIgnoreCase(upgrade)) {
ctx.next();
return;
}
Target target;
try {
target = resolve(ctx.request().path(), ctx.request().query(), ctx.request()::getHeader);
} catch (Refusal refusal) {
ctx.response().setStatusCode(refusal.status).end(refusal.getMessage());
return;
}
// Connect first, so an unreachable instance is a clean HTTP error rather than a socket
// that opens and immediately closes.
ctx.request().pause();
// The container's own address is tried first: it is the one that works when Floci shares a
// Docker network with the instance, whichever host it runs on. Where the host cannot route to
// containers (Docker Desktop on macOS or Windows) the published SSH port is the way in.
boolean[] usedFallback = {false};
netClient.connect(target.port(), target.host()).recover(primary -> target.fallbackPort() <= 0
? Future.<NetSocket>failedFuture(primary)
: netClient.connect(target.fallbackPort(), target.fallbackHost())
.onSuccess(ignored -> usedFallback[0] = true)
.recover(ignored -> Future.<NetSocket>failedFuture(primary))).onComplete(connected -> {
if (connected.failed()) {
ctx.request().resume();
ctx.response().setStatusCode(504).end("Unable to reach " + target.instance().getPrivateIpAddress()
+ ":" + target.port() + ": " + connected.cause().getMessage());
return;
}
// An instance that speaks first (sshd's banner) can write before the upgrade completes;
// hold its bytes until the pipe below exists; pipeTo resumes it.
NetSocket socket = connected.result().pause();
ctx.request().resume();
ctx.request().toWebSocket().onSuccess(webSocket -> {
String dialed = usedFallback[0]
? target.fallbackHost() + ":" + target.fallbackPort()
: target.host() + ":" + target.port();
LOG.infov("EC2 Instance Connect Endpoint {0}: tunnel to {1} opened via {2} (published-port fallback: {3})",
target.endpoint().getInstanceConnectEndpointId(), target.instance().getInstanceId(),
dialed, usedFallback[0]);
webSocket.pipeTo(socket);
socket.pipeTo(webSocket);
long timer = vertx.setTimer(target.maxSeconds() * 1000L, ignored -> webSocket.close());
webSocket.closeHandler(ignored -> {
vertx.cancelTimer(timer);
socket.close();
});
socket.closeHandler(ignored -> {
if (!webSocket.isClosed()) {
webSocket.close();
}
});
}).onFailure(cause -> {
socket.close();
LOG.warnv("EC2 Instance Connect Endpoint tunnel upgrade failed: {0}", cause.getMessage());
});
});
}
/** Validates a tunnel request into its target, or throws {@link Refusal}. */
Target resolve(String rawPath, String rawQuery, UnaryOperator<String> header) {
if (!config.services().ec2instanceconnect().enabled()) {
throw new Refusal(404, "EC2 Instance Connect is not enabled");
}
Map<String, List<String>> params = new QueryStringDecoder(rawQuery == null ? "" : rawQuery, false)
.parameters();
UnaryOperator<String> query = name -> {
List<String> values = params.get(name);
return values == null || values.isEmpty() ? null : values.getFirst();
};
SigV4SignedRequest signed = SigV4SignedRequest.ALGORITHM.equals(query.apply("X-Amz-Algorithm"))
? SigV4SignedRequest.fromQuery(query) : null;
CredentialScope scope = signed == null ? null : CredentialScope.parse(signed.credential());
if (scope == null || !SIGNING_SERVICE.equals(scope.service())) {
throw new Refusal(403, "The request is not presigned for " + SIGNING_SERVICE);
}
switch (signed.freshness(clock.instant())) {
case FRESH -> { }
case EXPIRED -> throw new Refusal(403, "Request has expired");
case NOT_YET_VALID -> throw new Refusal(403, "Request is signed in the future");
case BAD_EXPIRES -> throw new Refusal(403, "X-Amz-Expires must be from 1 to "
+ SigV4SignedRequest.MAX_PRESIGNED_EXPIRY_SECONDS + " seconds");
case MALFORMED_DATE -> throw new Refusal(403, "The request has no valid X-Amz-Date");
}
String akid = scope.accessKeyId();
String accountId = accountResolver.resolveFromPresignedCredential(signed.credential());
if (!AccountResolver.isAccountId(akid)) {
accountId = sessionAccountLookup.resolveAccountId(akid).orElse(accountId);
}
String account = accountId;
// The signing secret is read from the credential's account, so the signature is verified
// inside its scope: outside one the store is the default account's and another account's
// key is unknown.
return RequestScopes.callAs(account, scope.region(), () -> {
if (config.auth().validateSignatures()) {
verifySignature(signed, scope, rawPath, rawQuery, header, query.apply("X-Amz-Security-Token"));
}
return resolveTarget(scope, account, signed.credential(), query);
});
}
/** Runs as the credential's account, so every store read below is that account's. */
private Target resolveTarget(CredentialScope scope, String accountId, String credential,
UnaryOperator<String> query) {
String region = scope.region();
String endpointId = required(query, "instanceConnectEndpointId");
String privateIp = required(query, "privateIpAddress");
if (!isIpv4Literal(privateIp)) {
throw new Refusal(400, "privateIpAddress must be an IPv4 address");
}
int port = integer(query, "remotePort", null);
if (!ALLOWED_PORTS.contains(port)) {
throw new Refusal(400, "remotePort " + port + " is not supported; an EC2 Instance Connect Endpoint "
+ "forwards ports 22 and 3389");
}
int maxSeconds = integer(query, "maxTunnelDuration", MAX_TUNNEL_SECONDS);
if (maxSeconds < 1 || maxSeconds > MAX_TUNNEL_SECONDS) {
throw new Refusal(400, "maxTunnelDuration must be from 1 to " + MAX_TUNNEL_SECONDS + " seconds");
}
InstanceConnectEndpoint endpoint = ec2Service.findUsableInstanceConnectEndpoint(region, endpointId)
.orElseThrow(() -> new Refusal(404, "No available EC2 Instance Connect Endpoint " + endpointId
+ " in " + region));
authorize(scope.accessKeyId(), accountId, credential, endpoint.getInstanceConnectEndpointArn(),
name -> switch (name) {
case "remotePort" -> String.valueOf(port);
case "privateIpAddress" -> privateIp;
case "maxTunnelDuration" -> String.valueOf(maxSeconds);
default -> null;
});
Instance instance = ec2Service.findRunningInstanceByPrivateIp(region, endpoint.getVpcId(), privateIp)
.orElseThrow(() -> new Refusal(404, "No running instance at " + privateIp + " in "
+ endpoint.getVpcId()));
if (!ec2Service.instanceConnectEndpointMayReach(endpoint, instance, port)) {
throw new Refusal(403, "The security groups of " + endpointId + " and " + instance.getInstanceId()
+ " do not allow TCP " + port + " from the endpoint to the instance");
}
String host = Optional.ofNullable(instance.getContainerBridgeIp()).filter(ip -> !ip.isBlank())
.orElse(privateIp);
// Only SSH is published on the host (Ec2ContainerManager maps 22 to sshHostPort).
boolean published = port == 22 && instance.getSshHostPort() > 0;
return new Target(endpoint, instance, host, port, maxSeconds,
published ? "127.0.0.1" : null, published ? instance.getSshHostPort() : 0);
}
/**
* IAM enforcement for {@code ec2-instance-connect:OpenTunnel}, by the rules
* {@code IamEnforcementFilter} applies to every JAX-RS request: an access key IAM does not know
* is refused, and a known one must be allowed the action on the endpoint, with the condition keys
* the shared table gives the action filled from the request's parameters, read as this handler resolved
* them (an omitted maxTunnelDuration is the default it opens the tunnel with).
*/
private void authorize(String akid, String accountId, String credential, String endpointArn,
Function<String, String> parameter) {
if (!config.services().iam().enforcementEnabled() || LEGACY_ACCESS_KEY_ID.equals(akid)) {
return;
}
if (!akid.equals(accountId) && !iamService.isKnownAccessKey(akid)
&& iamService.resolveCallerContext(akid, clock.instant()) == null) {
throw new Refusal(403, "The security token included in the request is invalid.");
}
try {
iamEnforcement.authorizeRequestParameters(AccountResolver.SIGV4_SCHEME + " Credential=" + credential,
OPEN_TUNNEL_ACTION, endpointArn, parameter);
} catch (AwsException e) {
throw new Refusal(e.getHttpStatus(), e.getMessage());
}
}
/**
* The presigned signature, verified as the AWS CLI signs it: method {@code GET}, the wire path,
* the query without {@code X-Amz-Signature}, the signed headers ({@code host}), and the SHA-256
* of an empty body.
*/
private void verifySignature(SigV4SignedRequest signed, CredentialScope scope, String rawPath, String rawQuery,
UnaryOperator<String> header, String sessionToken) {
if (!SigV4RequestValidator.containsHeader(signed.signedHeaders(), "host")) {
throw new Refusal(403, "X-Amz-SignedHeaders must include host");
}
String secret = LEGACY_ACCESS_KEY_ID.equals(scope.accessKeyId()) ? LEGACY_SECRET_KEY
: iamService.findSecretKey(scope.accessKeyId(), sessionToken).orElse(null);
if (secret == null) {
throw new Refusal(403, "The security token included in the request is invalid.");
}
boolean matches;
try {
matches = SigV4Canonicalization.signatureMatches("GET", rawPath,
SigV4Canonicalization.canonicalQueryString(rawQuery, true),
SigV4Canonicalization.canonicalHeaders(signed.signedHeaders(), name -> {
String value = header.apply(name);
return value == null ? "" : value;
}),
signed.signedHeaders(),
SigV4Canonicalization.payloadHash(null, signed.signedHeaders(), new byte[0], false),
signed.amzDate(), scope, secret, signed.signature());
} catch (Exception e) {
LOG.debugv(e, "EC2 Instance Connect tunnel signature could not be verified");
matches = false;
}
if (!matches) {
throw new Refusal(403, "The request signature we calculated does not match the signature you provided.");
}
}
/** ofLiteral never resolves a name; a non-literal throws instead of reaching DNS. */
private static boolean isIpv4Literal(String value) {
try {
// The round trip refuses the shorthand ofLiteral accepts ("10.0.1", hex, octal).
return InetAddress.ofLiteral(value) instanceof Inet4Address a && a.getHostAddress().equals(value);
} catch (IllegalArgumentException e) {
return false;
}
}
private static String required(UnaryOperator<String> query, String name) {
String value = query.apply(name);
if (value == null || value.isBlank()) {
throw new Refusal(400, name + " is required");
}
return value;
}
private static int integer(UnaryOperator<String> query, String name, Integer fallback) {
String value = query.apply(name);
if (value == null || value.isBlank()) {
if (fallback == null) {
throw new Refusal(400, name + " is required");
}
return fallback;
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new Refusal(400, name + " must be an integer");
}
}
}
@@ -6,6 +6,11 @@
"note": "make request-condition-keys-check re-derives members from botocore; make request-condition-keys-verify checks actions against AWS."
},
"actions": {
"ec2-instance-connect:OpenTunnel": [
"ec2-instance-connect:MaxTunnelDuration",
"ec2-instance-connect:privateIpAddress",
"ec2-instance-connect:remotePort"
],
"lambda:CreateWebFunction": [
"lambda:Request/WebFunctionAuthType"
],
@@ -33,6 +38,17 @@
]
},
"members": {
"ec2-instance-connect:OpenTunnel": {
"ec2-instance-connect:MaxTunnelDuration": [
"maxTunnelDuration"
],
"ec2-instance-connect:privateIpAddress": [
"privateIpAddress"
],
"ec2-instance-connect:remotePort": [
"remotePort"
]
},
"lambda:CreateWebFunction": {
"lambda:Request/WebFunctionAuthType": [
"endpointConfig.authType"
@@ -4,9 +4,16 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.services.ec2.model.GroupIdentifier;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.InstanceConnectEndpoint;
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.NetworkInterface;
import io.floci.aws.services.ec2.model.PrefixListEntry;
import io.floci.aws.services.ec2.model.PrefixListId;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.ec2.model.UserIdGroupPair;
import io.floci.aws.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
@@ -387,4 +394,81 @@ class Ec2InstanceConnectEndpointServiceTest {
assertEquals("InvalidNetworkInterfaceID.NotFound", assertThrows(AwsException.class, () -> service
.describeNetworkInterfaces(REGION, List.of(eniId), Map.of())).getErrorCode());
}
@Test
void tunnelReachNeedsTheEndpointsEgressAndTheInstancesIngress() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.73.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.73.1.0/24", "us-east-1a").getSubnetId();
String eiceGroup = service.createSecurityGroup(REGION, "eice", "x", vpcId).getGroupId();
String hostGroup = service.createSecurityGroup(REGION, "host", "x", vpcId).getGroupId();
service.revokeSecurityGroupEgress(REGION, eiceGroup, List.of(permission("-1", null, null, null, "0.0.0.0/0")));
service.authorizeSecurityGroupEgress(REGION, eiceGroup, List.of(permission("tcp", 22, 22, hostGroup, null)));
Instance instance = service.runInstances(REGION, "ami-1234567890abcdef0", "t3.micro", 1, 1, null,
List.of(hostGroup), subnetId, null, List.of(), null, null).getInstances().getFirst();
InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnetId,
List.of(eiceGroup), null, null, List.of(), null);
assertFalse(service.instanceConnectEndpointMayReach(endpoint, instance, 22), "no ingress on the host yet");
service.authorizeSecurityGroupIngress(REGION, hostGroup, List.of(permission("tcp", 22, 22, eiceGroup, null)));
assertTrue(service.instanceConnectEndpointMayReach(endpoint, instance, 22));
assertFalse(service.instanceConnectEndpointMayReach(endpoint, instance, 3389), "the endpoint may only send 22");
assertTrue(service.findRunningInstanceByPrivateIp(REGION, vpcId, instance.getPrivateIpAddress()).isEmpty(),
"a pending instance is not a tunnel target");
// Mock mode has no container to report the launch; mark it running as the launch would.
service.getInstance(REGION, instance.getInstanceId()).orElseThrow().setState(InstanceState.running());
assertEquals(instance.getInstanceId(), service.findRunningInstanceByPrivateIp(REGION, vpcId,
instance.getPrivateIpAddress()).orElseThrow().getInstanceId());
service.deleteInstanceConnectEndpoint(REGION, endpoint.getInstanceConnectEndpointId());
assertTrue(service.findUsableInstanceConnectEndpoint(REGION, endpoint.getInstanceConnectEndpointId())
.isEmpty());
}
@Test
void tunnelReachHonoursPrefixListRules() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.74.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.74.1.0/24", "us-east-1a").getSubnetId();
String eiceGroup = service.createSecurityGroup(REGION, "eice", "x", vpcId).getGroupId();
String hostGroup = service.createSecurityGroup(REGION, "host", "x", vpcId).getGroupId();
String subnetList = service.createManagedPrefixList(REGION, "subnet", "IPv4", 2,
List.of(new PrefixListEntry("10.74.1.0/24", null)), List.of()).getPrefixListId();
service.revokeSecurityGroupEgress(REGION, eiceGroup, List.of(permission("-1", null, null, null, "0.0.0.0/0")));
service.authorizeSecurityGroupEgress(REGION, eiceGroup, List.of(prefixListPermission(subnetList)));
Instance instance = service.runInstances(REGION, "ami-1234567890abcdef0", "t3.micro", 1, 1, null,
List.of(hostGroup), subnetId, null, List.of(), null, null).getInstances().getFirst();
InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnetId,
List.of(eiceGroup), null, null, List.of(), null);
assertFalse(service.instanceConnectEndpointMayReach(endpoint, instance, 22), "no ingress on the host yet");
service.authorizeSecurityGroupIngress(REGION, hostGroup, List.of(prefixListPermission(subnetList)));
assertTrue(service.instanceConnectEndpointMayReach(endpoint, instance, 22),
"both sides name the subnet through a prefix list");
}
private static IpPermission prefixListPermission(String prefixListId) {
IpPermission permission = permission("tcp", 22, 22, null, null);
permission.setPrefixListIds(new ArrayList<>(List.of(new PrefixListId(prefixListId, null))));
return permission;
}
private static IpPermission permission(String protocol, Integer from, Integer to, String groupId, String cidr) {
IpPermission permission = new IpPermission();
permission.setIpProtocol(protocol);
permission.setFromPort(from);
permission.setToPort(to);
if (groupId != null) {
UserIdGroupPair pair = new UserIdGroupPair();
pair.setGroupId(groupId);
permission.setUserIdGroupPairs(new ArrayList<>(List.of(pair)));
}
if (cidr != null) {
IpRange range = new IpRange();
range.setCidrIp(cidr);
permission.setIpRanges(new ArrayList<>(List.of(range)));
}
return permission;
}
}
@@ -0,0 +1,64 @@
package io.floci.aws.services.ec2instanceconnect;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.testing.EnforcementFixtures;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The tunnel is a Vert.x route, outside the JAX-RS filters that set the request's account. It must
* still read the endpoint from the account the presigned credential names: before, every lookup
* fell back to the default account, so another account's endpoint was never found and a caller
* from any account reached the default account's instances.
*/
@QuarkusTest
class InstanceConnectTunnelAccountIntegrationTest {
private static final String ACCOUNT = "111122223333";
@Inject
InstanceConnectTunnelHandler handler;
@Test
void theEndpointIsLookedUpInTheCredentialsAccountOnly() {
String vpcId = XmlParser.extractFirst(ec2("CreateVpc", "CidrBlock", "10.91.0.0/16"), "vpcId", null);
String subnetId = XmlParser.extractFirst(
ec2("CreateSubnet", "VpcId", vpcId, "CidrBlock", "10.91.1.0/24"), "subnetId", null);
String endpointId = XmlParser.extractFirst(
ec2("CreateInstanceConnectEndpoint", "SubnetId", subnetId), "instanceConnectEndpointId", null);
assertTrue(endpointId.startsWith("eice-"), endpointId);
InstanceConnectTunnelHandler.Refusal asOwner = refusal(ACCOUNT, endpointId);
assertEquals(404, asOwner.status);
assertTrue(asOwner.getMessage().startsWith("No running instance"),
"the owner's credential finds the endpoint: " + asOwner.getMessage());
InstanceConnectTunnelHandler.Refusal asDefault = refusal("000000000000", endpointId);
assertEquals(404, asDefault.status);
assertTrue(asDefault.getMessage().startsWith("No available EC2 Instance Connect Endpoint"),
"another account's credential does not: " + asDefault.getMessage());
}
private InstanceConnectTunnelHandler.Refusal refusal(String accessKey, String endpointId) {
String query = "instanceConnectEndpointId=" + endpointId + "&remotePort=22&privateIpAddress=10.91.1.200&"
+ EnforcementFixtures.presignedQuery(accessKey, "ec2-instance-connect");
return assertThrows(InstanceConnectTunnelHandler.Refusal.class,
() -> handler.resolve("/openTunnel", query, name -> null));
}
private static String ec2(String action, String... params) {
RequestSpecification request = given().formParam("Action", action)
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261019/us-east-1/ec2/aws4_request");
for (int i = 0; i < params.length; i += 2) {
request = request.formParam(params[i], params[i + 1]);
}
return request.when().post("/").then().statusCode(200).extract().asString();
}
}
@@ -0,0 +1,81 @@
package io.floci.aws.services.ec2instanceconnect;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.IamEnforcementFilter;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.model.AccessKey;
import io.floci.aws.testing.IamEnforcementProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The EC2 User Guide's OpenTunnel policies, through the path the tunnel handler takes: the shared
* filter fills {@code ec2-instance-connect:remotePort}, {@code privateIpAddress} and
* {@code maxTunnelDuration} from the query parameters, by the table in request-condition-keys.json.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class InstanceConnectTunnelConditionKeysIntegrationTest {
private static final String ACTION = "ec2-instance-connect:OpenTunnel";
private static final String ENDPOINT = "arn:aws:ec2:us-east-1:000000000000:instance-connect-endpoint/eice-0123456789abcdef0";
@Inject
IamService iam;
@Inject
IamEnforcementFilter enforcement;
@Test
void anAllowScopedToPortAddressAndDurationAppliesToTheTunnelsQuery() {
String key = userWith("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"ec2-instance-connect:OpenTunnel",
"Resource":"*","Condition":{
"NumericEquals":{"ec2-instance-connect:remotePort":22},
"IpAddress":{"ec2-instance-connect:privateIpAddress":"10.0.0.0/24"},
"NumericLessThanEquals":{"ec2-instance-connect:maxTunnelDuration":600}}}]}""");
assertDoesNotThrow(() -> open(key, "22", "10.0.0.5", "300"));
assertDenied(key, "3389", "10.0.0.5", "300");
assertDenied(key, "22", "10.0.1.5", "300");
assertDenied(key, "22", "10.0.0.5", "900");
}
@Test
void aDenyScopedToAPortRefusesThatPortOnly() {
String key = userWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"ec2-instance-connect:OpenTunnel","Resource":"*"},
{"Effect":"Deny","Action":"ec2-instance-connect:OpenTunnel","Resource":"*",
"Condition":{"NumericEquals":{"ec2-instance-connect:remotePort":3389}}}]}""");
assertDoesNotThrow(() -> open(key, "22", "10.0.0.5", "300"));
assertDenied(key, "3389", "10.0.0.5", "300");
}
private String userWith(String policy) {
String user = "eice-" + UUID.randomUUID().toString().substring(0, 8);
iam.createUser(user, "/");
iam.putUserPolicy(user, "tunnel", policy);
AccessKey key = iam.createAccessKey(user);
return key.getAccessKeyId();
}
private void open(String accessKeyId, String port, String ip, String max) {
Map<String, String> query = Map.of("remotePort", port, "privateIpAddress", ip, "maxTunnelDuration", max);
enforcement.authorizeRequestParameters(auth(accessKeyId, "ec2-instance-connect"), ACTION, ENDPOINT,
query::get);
}
private void assertDenied(String accessKeyId, String port, String ip, String max) {
assertThrows(AwsException.class, () -> open(accessKeyId, port, ip, max), port + " " + ip + " " + max);
}
}
@@ -0,0 +1,201 @@
package io.floci.aws.services.ec2instanceconnect;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AccountResolver;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.IamEnforcementFilter;
import io.floci.aws.core.common.SessionAccountLookup;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.InstanceConnectEndpoint;
import io.floci.aws.services.iam.IamService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import org.mockito.ArgumentCaptor;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class InstanceConnectTunnelHandlerTest {
private static final String EICE = "eice-0123456789abcdef0";
private static final String HOST = EICE + ".localhost.floci.io";
private static final String ARN = "arn:aws:ec2:us-east-1:000000000000:instance-connect-endpoint/" + EICE;
/**
* Produced by AWS CLI 2.38.1's own signer ({@code InstanceConnectEndpointRequestSigner}) with access
* key AKIAFLOCITUNNELTEST1 and secret {@code tunnelsecret}: the exact URL {@code open-tunnel} dials.
*/
private static final String CLI_QUERY = "instanceConnectEndpointId=" + EICE
+ "&remotePort=22&privateIpAddress=10.0.1.10&maxTunnelDuration=3600&X-Amz-Algorithm=AWS4-HMAC-SHA256"
+ "&X-Amz-Credential=AKIAFLOCITUNNELTEST1%2F20261019%2Fus-east-1%2Fec2-instance-connect%2Faws4_request"
+ "&X-Amz-Date=20261019T183743Z&X-Amz-Expires=60&X-Amz-SignedHeaders=host"
+ "&X-Amz-Signature=52d3a1720534fa6940d19223dba7516507774db4c7f24e50c92116cd63fee0b2";
private static final Instant NOW = Instant.parse("2026-10-19T18:38:13Z");
private Ec2Service ec2;
private EmulatorConfig config;
private IamService iam;
private SessionAccountLookup sessions;
private IamEnforcementFilter enforcement;
private InstanceConnectTunnelHandler handler;
private Instance instance;
private InstanceConnectEndpoint endpoint;
@BeforeEach
void setUp() {
ec2 = mock(Ec2Service.class);
config = mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
when(config.services().ec2instanceconnect().enabled()).thenReturn(true);
iam = mock(IamService.class);
sessions = mock(SessionAccountLookup.class);
enforcement = mock(IamEnforcementFilter.class);
when(sessions.resolveAccountId(anyString())).thenReturn(Optional.empty());
when(iam.findSecretKey(eq("AKIAFLOCITUNNELTEST1"), nullable(String.class)))
.thenReturn(Optional.of("tunnelsecret"));
handler = new InstanceConnectTunnelHandler(ec2, null, config, iam, new AccountResolver("000000000000"),
sessions, enforcement, Clock.fixed(NOW, ZoneOffset.UTC));
endpoint = new InstanceConnectEndpoint();
endpoint.setInstanceConnectEndpointId(EICE);
endpoint.setInstanceConnectEndpointArn(ARN);
endpoint.setVpcId("vpc-1");
instance = new Instance();
instance.setInstanceId("i-0123456789abcdef0");
instance.setPrivateIpAddress("10.0.1.10");
instance.setContainerBridgeIp("192.168.97.5");
when(ec2.findUsableInstanceConnectEndpoint(anyString(), anyString())).thenReturn(Optional.empty());
when(ec2.findUsableInstanceConnectEndpoint("us-east-1", EICE)).thenReturn(Optional.of(endpoint));
when(ec2.findRunningInstanceByPrivateIp(anyString(), anyString(), anyString())).thenReturn(Optional.empty());
when(ec2.findRunningInstanceByPrivateIp("us-east-1", "vpc-1", "10.0.1.10")).thenReturn(Optional.of(instance));
when(ec2.instanceConnectEndpointMayReach(eq(endpoint), eq(instance), anyInt())).thenReturn(true);
}
@Test
void resolvesTheCliUrlToTheInstancesReachableAddress() {
InstanceConnectTunnelHandler.Target target = resolve(CLI_QUERY);
assertEquals("192.168.97.5", target.host());
assertEquals(22, target.port());
assertEquals(3600, target.maxSeconds());
}
@Test
void sshIsAlsoOfferedOnThePublishedHostPort() {
assertEquals(0, resolve(CLI_QUERY).fallbackPort(), "nothing published, nothing to fall back to");
instance.setSshHostPort(32022);
InstanceConnectTunnelHandler.Target target = resolve(CLI_QUERY);
assertEquals("127.0.0.1", target.fallbackHost());
assertEquals(32022, target.fallbackPort());
assertEquals("192.168.97.5", target.host(), "the container address is still tried first");
assertEquals(0, resolve(CLI_QUERY.replace("remotePort=22", "remotePort=3389")).fallbackPort(),
"only SSH is published");
}
@Test
void refusesEveryTunnelWhenTheServiceIsDisabled() {
when(config.services().ec2instanceconnect().enabled()).thenReturn(false);
assertEquals(404, refusal(CLI_QUERY));
}
@Test
void refusesWhatAwsRefuses() {
assertEquals(403, refusal(CLI_QUERY.replace("ec2-instance-connect%2Faws4", "ec2%2Faws4")));
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Algorithm=AWS4-HMAC-SHA256&", "")));
assertEquals(400, refusal(CLI_QUERY.replace("remotePort=22", "remotePort=6443")));
assertEquals(400, refusal(CLI_QUERY.replace("maxTunnelDuration=3600", "maxTunnelDuration=3601")));
assertEquals(404, refusal(CLI_QUERY.replace("instanceConnectEndpointId=" + EICE,
"instanceConnectEndpointId=eice-0000000000000000f")));
assertEquals(404, refusal(CLI_QUERY.replace("10.0.1.10", "10.0.1.99")));
for (String bad : List.of("not-an-ip", "10.0.0.256", "::1", "10.0.1")) {
assertEquals(400, refusal(CLI_QUERY.replace("10.0.1.10", bad)), bad);
}
when(ec2.instanceConnectEndpointMayReach(eq(endpoint), eq(instance), anyInt())).thenReturn(false);
assertEquals(403, refusal(CLI_QUERY), "security groups deny");
}
@Test
void expiryIsBoundedAndAFutureSigningTimeIsRefused() {
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Date=20261019T183743Z", "X-Amz-Date=20261019T183600Z")),
"signed 133 s ago, valid 60 s");
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Expires=60", "X-Amz-Expires=0")));
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Expires=60", "X-Amz-Expires=604801")));
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Expires=60", "X-Amz-Expires=9223372036854775807")),
"used to overflow Instant.plusSeconds into a 500");
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Date=20261019T183743Z", "X-Amz-Date=20261019T185000Z")),
"signed twelve minutes ahead");
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Date=20261019T183743Z", "X-Amz-Date=yesterday")));
}
@Test
void withSignatureValidationTheCliSignatureVerifiesAndATamperedOneDoesNot() {
when(config.auth().validateSignatures()).thenReturn(true);
assertEquals(22, resolve(CLI_QUERY).port());
assertEquals(403, refusal(CLI_QUERY.replace("privateIpAddress=10.0.1.10", "privateIpAddress=10.0.1.11")),
"the target is covered by the signature");
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Signature=52", "X-Amz-Signature=53")));
when(iam.findSecretKey(eq("AKIAFLOCITUNNELTEST1"), nullable(String.class))).thenReturn(Optional.empty());
assertEquals(403, refusal(CLI_QUERY), "an access key Floci never issued");
}
@Test
void withoutSignatureValidationTheSignatureIsNotChecked() {
assertEquals(22, resolve(CLI_QUERY.replace("X-Amz-Signature=52", "X-Amz-Signature=53")).port());
}
@Test
void withIamEnforcementOpenTunnelIsAuthorizedOnTheEndpoint() {
when(config.services().iam().enforcementEnabled()).thenReturn(true);
when(iam.isKnownAccessKey("AKIAFLOCITUNNELTEST1")).thenReturn(true);
resolve(CLI_QUERY);
ArgumentCaptor<Function<String, String>> parameter = ArgumentCaptor.forClass(Function.class);
verify(enforcement).authorizeRequestParameters(
eq("AWS4-HMAC-SHA256 Credential=AKIAFLOCITUNNELTEST1/20261019/us-east-1/ec2-instance-connect/aws4_request"),
eq("ec2-instance-connect:OpenTunnel"), eq(ARN), parameter.capture());
assertEquals("22", parameter.getValue().apply("remotePort"));
assertEquals("10.0.1.10", parameter.getValue().apply("privateIpAddress"));
assertEquals("3600", parameter.getValue().apply("maxTunnelDuration"));
// Omitted, it is the 3600 the tunnel opens with, so a policy on it still applies.
clearInvocations(enforcement);
resolve(CLI_QUERY.replace("&maxTunnelDuration=3600", ""));
verify(enforcement).authorizeRequestParameters(anyString(), anyString(), anyString(), parameter.capture());
assertEquals("3600", parameter.getValue().apply("maxTunnelDuration"));
doThrow(new AwsException("AccessDenied", "denied", 403)).when(enforcement)
.authorizeRequestParameters(anyString(), anyString(), anyString(), any());
assertEquals(403, refusal(CLI_QUERY));
when(iam.isKnownAccessKey("AKIAFLOCITUNNELTEST1")).thenReturn(false);
assertEquals(403, refusal(CLI_QUERY), "an unknown key is refused under enforcement");
}
private InstanceConnectTunnelHandler.Target resolve(String query) {
return handler.resolve("/openTunnel", query, name -> "host".equals(name) ? HOST : null);
}
private int refusal(String query) {
return assertThrows(InstanceConnectTunnelHandler.Refusal.class, () -> resolve(query)).status;
}
}
@@ -0,0 +1,204 @@
package io.floci.aws.services.ec2instanceconnect;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.InstanceConnectEndpoint;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.UpgradeRejectedException;
import io.vertx.core.http.WebSocket;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetSocket;
import io.vertx.ext.web.Router;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.UnaryOperator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@code open()} against real sockets: a WebSocket client, the handler on a Vert.x router, and a local
* TCP server standing in for the instance's port. {@code resolve()} (covered by
* {@link InstanceConnectTunnelHandlerTest}) is replaced so the tunnel dials that server.
*/
class InstanceConnectTunnelOpenTest {
private Vertx vertx;
private NetServer instancePort;
private HttpServer floci;
private HttpClient client;
private final CompletableFuture<NetSocket> instanceSide = new CompletableFuture<>();
private final CompletableFuture<Void> instanceSideClosed = new CompletableFuture<>();
private int targetPort;
private int maxSeconds = 60;
/** Written by the instance as soon as the tunnel connects, before it reads anything, as sshd does. */
private String banner;
/** When set, the instance accepts the connection and closes it at once. */
private boolean closeOnConnect;
/** When set, the address the instance reports is dead and only the published port reaches it. */
private boolean publishedPortOnly;
@BeforeEach
void setUp() throws Exception {
vertx = Vertx.vertx();
instancePort = vertx.createNetServer().connectHandler(socket -> {
instanceSide.complete(socket);
if (closeOnConnect) {
socket.close();
return;
}
if (banner != null) {
socket.write(banner);
}
socket.handler(socket::write);
socket.closeHandler(ignored -> instanceSideClosed.complete(null));
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
targetPort = instancePort.actualPort();
InstanceConnectTunnelHandler handler = new InstanceConnectTunnelHandler(null, vertx, null, null, null,
null, null) {
@Override
Target resolve(String rawPath, String rawQuery, UnaryOperator<String> header) {
Instance instance = new Instance();
instance.setInstanceId("i-0123456789abcdef0");
instance.setPrivateIpAddress("10.0.1.10");
if (publishedPortOnly) {
return new Target(new InstanceConnectEndpoint(), instance, "127.0.0.1", closedPort(), maxSeconds,
"127.0.0.1", targetPort);
}
return new Target(new InstanceConnectEndpoint(), instance, "127.0.0.1", targetPort, maxSeconds, null, 0);
}
};
Router router = Router.router(vertx);
handler.init(router);
floci = vertx.createHttpServer().requestHandler(router).listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
client = vertx.createHttpClient();
}
@AfterEach
void tearDown() throws Exception {
vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
}
@Test
void bytesCrossTheTunnelBothWays() throws Exception {
WebSocket webSocket = connect();
CompletableFuture<Buffer> echoed = new CompletableFuture<>();
webSocket.binaryMessageHandler(echoed::complete);
webSocket.writeBinaryMessage(Buffer.buffer("SSH-2.0-test\r\n"));
assertEquals("SSH-2.0-test\r\n", echoed.get(5, TimeUnit.SECONDS).toString());
}
@Test
void aBannerTheInstanceWritesOnConnectReachesTheClient() throws Exception {
banner = "SSH-2.0-OpenSSH_9.6\r\n";
CompletableFuture<Buffer> received = new CompletableFuture<>();
// The handler is set inside the completion callback, so the client cannot itself lose the frame.
client.webSocket(floci.actualPort(), "127.0.0.1", InstanceConnectTunnelHandler.PATH)
.onSuccess(ws -> ws.binaryMessageHandler(received::complete))
.onFailure(received::completeExceptionally);
assertEquals(banner, received.get(5, TimeUnit.SECONDS).toString());
}
@Test
void closingTheWebSocketClosesTheInstanceConnection() throws Exception {
WebSocket webSocket = connect();
instanceSide.get(5, TimeUnit.SECONDS);
webSocket.close();
instanceSideClosed.get(5, TimeUnit.SECONDS);
}
@Test
void theInstanceClosingClosesTheWebSocket() throws Exception {
WebSocket webSocket = connect();
CompletableFuture<Void> closed = new CompletableFuture<>();
webSocket.closeHandler(ignored -> closed.complete(null));
instanceSide.get(5, TimeUnit.SECONDS).close();
closed.get(5, TimeUnit.SECONDS);
}
@Test
void anInstanceThatClosesBeforeTheUpgradeCompletesStillClosesTheWebSocket() throws Exception {
closeOnConnect = true;
CompletableFuture<Void> closed = new CompletableFuture<>();
client.webSocket(floci.actualPort(), "127.0.0.1", InstanceConnectTunnelHandler.PATH).onSuccess(ws -> {
if (ws.isClosed()) {
closed.complete(null);
} else {
ws.closeHandler(ignored -> closed.complete(null));
}
}).onFailure(closed::completeExceptionally);
closed.get(5, TimeUnit.SECONDS);
}
@Test
void maxTunnelDurationClosesBothSides() throws Exception {
maxSeconds = 1;
WebSocket webSocket = connect();
CompletableFuture<Void> closed = new CompletableFuture<>();
webSocket.closeHandler(ignored -> closed.complete(null));
closed.get(5, TimeUnit.SECONDS);
instanceSideClosed.get(5, TimeUnit.SECONDS);
}
@Test
void anUnreachableInstanceIsA504BeforeTheUpgrade() throws Exception {
instancePort.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
ExecutionException failed = assertThrows(ExecutionException.class, this::connect);
UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failed.getCause());
assertEquals(504, rejected.getStatus());
assertTrue(rejected.getBody() == null || rejected.getBody().toString().contains("Unable to reach"));
}
@Test
void anAddressFlociCannotRouteToFallsBackToThePublishedPort() throws Exception {
publishedPortOnly = true;
WebSocket webSocket = connect();
CompletableFuture<Buffer> echoed = new CompletableFuture<>();
webSocket.binaryMessageHandler(echoed::complete);
webSocket.writeBinaryMessage(Buffer.buffer("SSH-2.0-test\r\n"));
assertEquals("SSH-2.0-test\r\n", echoed.get(5, TimeUnit.SECONDS).toString());
}
@Test
void whenBothAddressesRefuseTheAnswerIsA504() throws Exception {
publishedPortOnly = true;
instancePort.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
ExecutionException failed = assertThrows(ExecutionException.class, this::connect);
assertEquals(504, assertInstanceOf(UpgradeRejectedException.class, failed.getCause()).getStatus());
}
private static int closedPort() {
try (ServerSocket probe = new ServerSocket(0)) {
return probe.getLocalPort();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private WebSocket connect() throws Exception {
return client.webSocket(floci.actualPort(), "127.0.0.1", InstanceConnectTunnelHandler.PATH)
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
}
}
@@ -0,0 +1,74 @@
package io.floci.aws.services.ec2instanceconnect;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.model.AccessKey;
import io.floci.aws.testing.TestAccounts;
import io.floci.aws.testing.ValidateSignaturesProfile;
import io.floci.aws.testutil.AwsRequestSigner;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* With signature validation on, a tunnel signed by an IAM access key that belongs to another
* account has to get past the signature check: the secret is stored in that account, so it is only
* found once the request runs as that account.
*/
@QuarkusTest
@TestProfile(ValidateSignaturesProfile.class)
class InstanceConnectTunnelSignedAccountIntegrationTest {
private static final String REGION = "us-east-1";
@Inject
InstanceConnectTunnelHandler handler;
@Inject
IamService iam;
@Inject
Ec2Service ec2;
@Test
void anAccessKeyOfAnotherAccountPassesTheSignatureCheck() throws Exception {
String account = TestAccounts.randomId();
AccessKey key = RequestScopes.callAs(account, () -> {
iam.createUser("eice-user", "/");
return iam.createAccessKey("eice-user");
});
String endpointId = RequestScopes.callAs(account, REGION, () -> {
String vpcId = ec2.createVpc(REGION, "10.92.0.0/16", false).getVpcId();
String subnetId = ec2.createSubnet(REGION, vpcId, "10.92.1.0/24", "us-east-1a").getSubnetId();
return ec2.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), null)
.getInstanceConnectEndpointId();
});
String query = signedQuery(key, endpointId);
InstanceConnectTunnelHandler.Refusal refusal = assertThrows(InstanceConnectTunnelHandler.Refusal.class,
() -> handler.resolve("/openTunnel", query, name -> "host".equals(name) ? "localhost" : null));
// Past the signature and the endpoint lookup, refused only for want of an instance.
assertEquals(404, refusal.status, refusal.getMessage());
assertTrue(refusal.getMessage().startsWith("No running instance"), refusal.getMessage());
String tampered = query.replace("remotePort=22", "remotePort=3389");
assertEquals(403, assertThrows(InstanceConnectTunnelHandler.Refusal.class,
() -> handler.resolve("/openTunnel", tampered, name -> "host".equals(name) ? "localhost" : null)).status);
}
/** A presigned tunnel URL as the AWS CLI signs it: GET, the query, the host header, an empty body. */
private static String signedQuery(AccessKey key, String endpointId) throws Exception {
return AwsRequestSigner.signedAs(key.getAccessKeyId(), key.getSecretAccessKey(), "ec2-instance-connect")
.presignedUri("GET", URI.create("http://localhost/openTunnel"), Map.of(
"instanceConnectEndpointId", endpointId, "remotePort", "22",
"privateIpAddress", "10.92.1.200"), new byte[0]).getRawQuery();
}
}
@@ -83,6 +83,31 @@ class IamPolicyEvaluatorTest {
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), "s3:ListBucket", "*", over));
}
@Test
void openTunnelConditionKeysScopeAnAllowToPortAddressAndDuration() {
String policy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"ec2-instance-connect:OpenTunnel","Resource":"*","Condition":{
"NumericEquals":{"ec2-instance-connect:remotePort":22},
"IpAddress":{"ec2-instance-connect:privateIpAddress":"10.0.0.0/24"},
"NumericLessThanEquals":{"ec2-instance-connect:maxTunnelDuration":600}}}]}""";
String action = "ec2-instance-connect:OpenTunnel";
String port = "ec2-instance-connect:remotePort";
String ip = "ec2-instance-connect:privateIpAddress";
String max = "ec2-instance-connect:maxTunnelDuration";
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy), action, "*",
Map.of(port, List.of("22"), ip, List.of("10.0.0.5"), max, List.of("300"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), action, "*",
Map.of(port, List.of("3389"), ip, List.of("10.0.0.5"), max, List.of("300"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), action, "*",
Map.of(port, List.of("22"), ip, List.of("10.0.1.5"), max, List.of("300"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), action, "*",
Map.of(port, List.of("22"), ip, List.of("10.0.0.5"), max, List.of("900"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), action, "*",
Map.of(port, List.of("22"), ip, List.of("10.0.0.5"))), "a key the caller never supplies");
}
@Test
void nullConditionReadsUnquotedBooleanValues() {
String requireAbsent = """
+22 -3
View File
@@ -10,6 +10,11 @@ it. `SERVICES` names, for each namespace, the keys read and where:
- `redshift`: a Redshift request is checked with the database user it names as `redshift:DbUser`, so a policy
can scope GetClusterCredentials and CreateClusterUser to `dbuser:<cluster>/${redshift:DbUser}`.
`redshift:DbName` and `redshift:DurationSeconds` are not read yet.
- `ec2-instance-connect`: an OpenTunnel request is checked with the `remotePort`, `privateIpAddress` and
`maxTunnelDuration` query parameters of its presigned WebSocket URL as the keys of the same names (the
Service Reference spells the action's third key `MaxTunnelDuration`; IAM keys are case-insensitive).
botocore does not model OpenTunnel (it is a WebSocket upgrade, not an API operation), so `SERVICES` gives
its members itself (`"model": None`) and `--check` has no botocore model to compare them to.
The table comes from two sources:
@@ -65,6 +70,14 @@ SERVICES = {
"stored": ("lambda:Resource/WebFunctionAuthType",),
"not_in_request": {},
},
"ec2-instance-connect": {
"model": None,
"request": {"ec2-instance-connect:remotePort": "remotePort",
"ec2-instance-connect:privateIpAddress": "privateIpAddress",
"ec2-instance-connect:MaxTunnelDuration": "maxTunnelDuration"},
"stored": (),
"not_in_request": {},
},
"redshift": {
"model": "redshift",
"request": {"redshift:DbUser": "DbUser"},
@@ -95,11 +108,11 @@ def action_keys(namespace: str, reference: dict) -> dict[str, list[str]]:
return found
def request_members(namespace: str, model: dict,
def request_members(namespace: str, model: dict | None,
actions: dict[str, list[str]]) -> dict[str, dict[str, list[str]]]:
"""For every action of the namespace and key read from its request, where the request carries the value."""
service = SERVICES[namespace]
flat = model.get("metadata", {}).get("protocol") in FLAT_PROTOCOLS
flat = model is not None and model.get("metadata", {}).get("protocol") in FLAT_PROTOCOLS
found = {}
for action, keys in sorted(actions.items()):
if not action.startswith(f"{namespace}:"):
@@ -108,6 +121,9 @@ def request_members(namespace: str, model: dict,
if key not in service["request"] or (action, key) in service["not_in_request"]:
continue
name = service["request"][key]
if model is None: # not modelled by botocore: the member is the name SERVICES gives
found.setdefault(action, {})[key] = [name]
continue
operation = model["operations"].get(action.split(":", 1)[1])
if operation is None or "input" not in operation:
raise ValueError(f"{action} takes {key} but botocore has no request for it")
@@ -140,6 +156,8 @@ def validate(document: dict) -> list[str]:
problems.append("lambda:GetWebFunctionEndpoint takes no lambda:Resource/WebFunctionAuthType")
if members.get("redshift:GetClusterCredentials", {}).get("redshift:DbUser") != ["DbUser"]:
problems.append("redshift:GetClusterCredentials does not read redshift:DbUser from DbUser")
if members.get("ec2-instance-connect:OpenTunnel", {}).get("ec2-instance-connect:remotePort") != ["remotePort"]:
problems.append("ec2-instance-connect:OpenTunnel does not read ec2-instance-connect:remotePort from remotePort")
return problems
@@ -162,7 +180,8 @@ def _members(actions: dict[str, list[str]], botocore_data: Path | None) -> tuple
data, provenance = resolve_botocore_data(botocore_data)
members = {}
for namespace, service in SERVICES.items():
members.update(request_members(namespace, load_model(latest_model_dir(data, service["model"])), actions))
model = service["model"] and load_model(latest_model_dir(data, service["model"]))
members.update(request_members(namespace, model, actions))
return dict(sorted(members.items())), provenance