mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 09:22:49 -05:00
feat(ec2): EC2 Instance Connect Endpoint tunnel (open-tunnel / eice SSH over WebSocket) (#7519)
This commit is contained in:
1 parent
c769ce055a
commit
475fb1822a
15 files changed
+1249
-15
No files matched your search
@@ -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:<key> 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",
|
||||
|
||||
+368
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user