Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS EC2 : Safe way to get host public key

When I connect to the AWS EC2 instance using ssh for the first time, I got an error like below because the host key is not stored in ssh known_hosts file.

The authenticity of host 'x.x.x.x' can't be established. ECDSA key fingerprint is xx:yy:.... Are you sure you want to continue connecting (yes/no)?

Now, I'm automating ssh. I often just add StrictHostKeyChecking option to ssh command to avoid this message. But, I feel that is not very safe way and possibly cause Man in the middle attack. Is there any (or good) way to get host key safely on AWS EC2?

like image 434
Tsuneo Yoshioka Avatar asked Sep 18 '25 02:09

Tsuneo Yoshioka


1 Answers

I think the only way is to parse the console output.

#get the console output of the instance
aws ec2 get-console-output --instance-id <instance id> |\
#use jq to get the Output field
jq .Output -r |\
#use sed to find the interesting bits
sed -n -e '1,/-----BEGIN SSH HOST KEY KEYS-----/d; /-----END SSH HOST KEY KEYS-----/q; p'

Caveats, which might not matter depending on your application:

  • aws output is JSON, so we need to parse it
  • output requires some sed massage
  • output may not be the same depending on the AMI?
like image 185
nfirvine Avatar answered Sep 21 '25 07:09

nfirvine