Unable to SSH in EC2 instance - amazon-web-services

I am unable to ssh AWS ec2 instance. It shows error Permission denied (public Key).I have tried to generate new pem key
# ssh-keygen -y -f /path/to/keypair.pem
and added it in Instance Settings View/Change User Data
#cloud-config
#ssh_deletekeys: false
#ssh_authorized_keys:
# - ssh-rsa ENTER YOUR PUBLIC KEY HERE ...
#cloud_final_modules: - [ssh, always]
But it didn't work and I also tried this tutorial
https://aws.amazon.com/premiumsupport/knowledge-center/recover-access-lost-key-pair/
Still it is not working.

What you are trying to do wont work. Neither will the answer #Rajeev provided. If it was a file permission error you would see a message indicating the .pem file had unsecure read permissions. What I suspect you'll need to do is kill off that instance and relaunch with a new key. Will be easier than troubleshooting it, and you can make a snapshot to launch a new instance from if you have done a lot of config on it already.
AWS best practices state instances should be treated as ephemeral. Follow those guidelines and you'll save yourself a lot of hassle in the long run.

Related

Permission denied (publickey).while copying ssh key to server

I am getting Permission denied (publickey) error while copying a public key using this command over ec2 ubuntu instance
root#ip-172-31-5-68:~# ssh-copy-id docadmin#ip-172-31-13-212
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed:"/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
docadmin#ip-172-31-13-212: Permission denied (publickey).
Can anyone help me why I am getting this permission issue?
AWS doesn't allow SSH connections to an EC2 instance with private keys that are publicly exposed.
While you're trying to copy a .pub (public key) over to instance 2, you're using ssh-copy-id, which uses ssh under the hood to facilitate the transfer, so you'll first need to lock down your private key on instance 1.
Substituting the last term for your private key .pem filepath, you can accomplish this with:
chmod 400 /path/to/your-private-key.pem
The following post seems to be the canonical reference for this topic, but this is a slightly different scenario, so I'm not going to mark it as a duplicate:
Trying to SSH into an Amazon Ec2 instance - permission error

How can I create an AMI that uses password authentication?

My goal is to spin up an EC2 instance, make an AMI from that instance, use the custom AMI to spin up a new instance that uses password authentication instead of keys.
I changed /etc/ssh/sshd_config to have PasswordAuthentication yes before creating the AMI, but I still get "permission denied (publickey)" when trying to SSH to the new instance created from the custom AMI.
I followed these steps and they work on the first instance, but then I still get the error when logging into the instance created from the customn AMI.
AWS support fixed my problem, here is their answer:
Make changes to the following lines in /etc/cloud/cloud.cfg file on
the original instance launched in the above steps as follows:
Default
settings:
ssh_pwauth: 0
lock_passwd: true
Settings after modification:
ssh_pwauth: 1
lock_passwd: false
service sshd restart
REFERENCES
https://cloudinit.readthedocs.io/en/latest/topics/examples.html#including-users-and-groups
https://cloudinit.readthedocs.io/en/latest/topics/modules.html

Recovering lost AWS EC2 Key Pairs

AWS rookie here. I created a few EC2 instances under my AWS account and reused the same Key Pair for all of them. I believe (IIRC) that I had generated the Key Pair from inside AWS, but that could be wrong.
Over this past weekend I sold my old laptop (after completely wiping the hard disk) and got a new one. I'm just remembering now (:facepalm) that I forgot to copy all my SSH private keys to a flash drive and that I no longer have them.
All I want/need to do is to SSH into my EC2 instances, but to do that I need my SSH keys. I still have AWS console access, and I can log in and view all my EC2 Key Pairs. But I don't see any options for downloading them or updating my EC2 instances with new Key Pairs.
So I ask:
Is it possible for me to recover my existing Key Pairs somehow so that I can SSH into my EC2 instances? Again I can log into the AWS console. If not, then...
Is it possible to generate another Key Pair and "swap it out" for my existing Key Pair?
I really don't want to have to tear down my old EC2 instances and re-provision new ones, that will take about a week for me to do (although, arguably, it would serve me right!).
Rebuild shouldnt be nesserary. Id suggest option 2 as its quicker and easier.
1.> Its possible to change/append a new key?
Power off the ec2 instance you want to access ("target").
Create a new ("temporary") instance.
Detach the primary EBS volume from target instance (taking note of its current attachment!).
Attach/mount target volume on temporary instance.
edit appropriate authorized_keys file on the mounted volume.
unmount target volume, and reattach to target ec2 instance (using config you noted when detatching it)
start target instance and login with new key.
delete temporary instance
2.> Yes. Snapshot the instance. Provision a new instance from the snapshot selecting a different key (keypair popup appears when you click launch at end of launch wizard)
Step 1: Go to IAM.
Step 2: Create a policy with the permission
"AmazonSSMManagedInstanceCore".
Step 3: Create a new role and attach
the previously created policy to that role.
Step 4: Go to EC2, select
the instance in "Actions" ==> "Security" ==> "Modify IAM role" select
the created role and save.
Step 5: Wait for 1 hour. It will take some
time to resolve.
Step 6: Select the EC2, Click on "Connect" ==>
"Session Manager" ==> "Connect"
You will get a session with that session you can add a new key to authorized keys.
Change ec2 user data to a multipart mime.
Parts:
cloud config
cloud_final_modules:
- [scripts-user, always]
shell script
Overwrites /home/ec2-user/.ssh/authorized_keys
Refer to this blog article replace ec2 ssh key
You can replace the new key using user data or systems manager.
Using User Data:
Create a new key pair from the AWS EC2 Console
Generate the Public Key from the downloaded key pair using below cmd:
ssh-keygen -y -f .pem
Stop the EC2 instance and edit the user data of the instance and pass the below script and start the Instance
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [users-groups, once]
users:
- name:ec2-user
ssh-authorized-keys:
- <**Paste the Public key here**>
Now, You will be able to login to EC2 instance with the downloaded key pair.
Using Systems Manager:
If the instance is a managed instance in AWS Systems Manager, you can use the AWSSupport-ResetAccess document to recover the lost key pair.
Open the AWS Systems Manager console, select Automation in left navigation pane, click execute Automation. In automation document section select owned by Amazon. In the run book list, search for AWSSupport-ResetAccess
In Execute automation document page, choose Simple execution. In document details section, verify Document version is set to Default. In the input parameter section, specify the Instance ID, Subnet ID and Instance type in parameter and execute.
When Automation is finished, the new ssh private key is saved and encrypted in parameter store and the parameter store named as /ec2rl/openssh//key
You can refer the below link for more detailed steps:
https://cloudsolutionsonline.blogspot.com/2021/11/connect-to-linux-ec2-instance-if-ssh.html?m=1

CLI command "describe-instances" throw error "An error occurred (AuthFailure) when calling the

I was able to install CLI on windows 16 AWS instance. when I try "aws ec2 describe-instances" CLI command, I get the following error
CLI command "describe-instances" throw error "An error occurred (AuthFailure) when calling the DescribeInstances operation: AWS was not able to validate the provided access credentials"
In .aws\config file I have following content:
[default]
region = us-west-2
How can authorization fail when it took my access key id and secret access key without any issue.
Verify if your datetime is sync ok.
use: ntpdate ntp.server
bests
I deleted my two configuration files from .aws directory and re-ran "aws config"
That fixed the problem for me.
My Steps:
Go to your .aws directory under Users e.g. "c:\Users\Joe\.aws"
Two files: configure and credential. Delete both files
Rerun configure: "aws configure"
Note when you run aws configure you will need the AWS Access and Secret Key. If you don't have them you can just create another.
Steps:
Goto "My Security Credentials" Under you Account Name in AWS Console.
Expand Access Key panel.
Create New Access Key.
When you first ran aws configure, it just populated the local credentials in %UserProfile%\.aws\credentials; it didn't validate them with AWS.
(aws-cli doesn't know what rights your user has until it tries to do an operation -- all of the access control happens on AWS's end. It just tries to do what you ask, and tells you if it doesn't have access, like you saw.)
That said, if you're running the CLI from an AWS instance, you might want to consider applying a role to that instance, so you don't have to store your keys on the instance.
My Access and Security keys are correct. My server time was good. I got error while using Ap-south-1 region. After I changed my region to us-west-2, it worked without any problem.
I tried setting that too on my windows environment. didn't work and getting error above.
so I tried setting my environment
SET AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY
SET AWS_SECRET_ACCESS_KEY=***YOUR_SECRET_ACCESS_KEY*
and then tried running command like "aws ec2 describe-instance"
I tried many things. Finally, just uninstalling and installing again (not repairing) did the trick. Just make sure to save a copy of your credentials (key and key ID) to use later when calling aws configure.

Starting sshd: WARNING: UNPROTECTED PRIVATE KEY FILE

I am using BitVise to communicate with my AWS instance.
From the last two days, I am not able to login with the pem file. Got the log from aws as follows,
Starting sshd: ##########################################################
# WARNING: UNPROTECTED PRIVATE KEY FILE! #
###########################################################
Permissions 0777 for '/etc/ssh/ssh_host_rsa_key' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: /etc/ssh/ssh_host_rsa_key
Could not load host key: /etc/ssh/ssh_host_rsa_key
the mistake was happened by setting 777 to ssh unfortunately.
What is the solution for this now? Cant able to connect using SSHClient to make the permission 400.
This is not a problem with pem file permission, the directory ssh has permission of 777.
Assuming that you're using EBS for the root volume, you'd need to launch a new EC2 instance, and attach the root volume of your existing instance to the new one. Then you'd be able to mount the filesystem and change the permissions on the file.
Then re-attach the volume to your other instance and you should be able to get in.