Skip to content

Instantly share code, notes, and snippets.

@skorfmann
Last active October 20, 2023 01:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save skorfmann/24169f8e8d4a2aa036f959e8337d5747 to your computer and use it in GitHub Desktop.
Save skorfmann/24169f8e8d4a2aa036f959e8337d5747 to your computer and use it in GitHub Desktop.

Both things have been introduced recently, and let you access even private ec2 instances

  1. Without VPN
  2. No open SSH port
  3. Authentication / Authorization is fully delegated to IAM
# Assumes valid AWS Credentials in ENV
ssh -v ec2-user@i-002afb820244e392f

What this will do (through the aws-proxy script below):

  • Generate a single use ssh key
  • Push the generated publich key to AWS for the given user of the provided ec2 instance id
  • Adds the private key to the ssh agent
  • Create a tunnel through Session Manager
  • Establish an SSH session

The host has to be configured to run:

  • SSM Agent
  • ec2-instance-connect

Locally, you'll have to have a recent version of the AWS cli and the SSM plugin

#!/usr/bin/env bash
USER=$1
HOSTNAME=$2
PORT=$3
INSTANCE_AZ=$(aws ec2 describe-instances --instance-ids ${HOSTNAME} | jq -r '.Reservations | .[] | .Instances | .[] | .Placement.AvailabilityZone')
ONE_TIME_KEY_FILE_NAME="$(mktemp /tmp/${HOSTNAME}.${USER}.XXXXXX)"
yes | ssh-keygen -t rsa -b 2048 -f ${ONE_TIME_KEY_FILE_NAME} -N ''
aws ec2-instance-connect send-ssh-public-key \
--region eu-central-1 \
--availability-zone ${INSTANCE_AZ} \
--instance-id ${HOSTNAME} \
--instance-os-user ${USER} \
--ssh-public-key "file://${ONE_TIME_KEY_FILE_NAME}.pub"
ssh-add -t 60 ${ONE_TIME_KEY_FILE_NAME}
aws ssm start-session \
--target ${HOSTNAME} \
--document-name AWS-StartSSHSession \
--parameters "portNumber=${PORT}"
# SSH over Session Manager and EC2 Instance Connect
host i-* mi-*
ProxyCommand sh -c "aws-proxy %r %h %p"
@Maks3w
Copy link

Maks3w commented Feb 13, 2021

Nice post. I already have achieved this doing some changes in EC2 Instance Connect CLI but due the lack of AWS support I was looking for a pure ProxyCommand approach.

I have made a fork from your post with some changes for avoid the use of SSH Agent. Take a look I think you will find some nice improvements.

@skorfmann
Copy link
Author

I have made a fork from your post with some changes for avoid the use of SSH Agent. Take a look I think you will find some nice improvements.

Thanks for sharing :) For reference here's the link to the fork

@Maks3w
Copy link

Maks3w commented Feb 14, 2021

I've made a totally new refactor using the "Match exec" feature. By this way I have be able to generate the pair of keys earlier and outside from the ProxyCommand context.

This solves the SCP compatibility from my earliest version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment