Can't push to bitbucket, Permission denied (publickey) - ssh

I am trying to push my project onto my bitbucket, been messing with this for about 4 days pouring through countless problem solving/pages/troubleshooting/tutorials. Im at a loss and very frustrated. I have done this before but on different computers...anyway here is the code/response that I'm getting
~/dev/sample_app git push -u origin --all
The authenticity of host 'bitbucket.org (131.103.20.168)' can't be established.
RSA key fingerprint is 81:7b:2c:f5:6f:18:2b:7c:4b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)?
Host key verification failed.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
~/dev/sample_app
I am on a mac running 10.8.4.
So a little progress has been made, initially there was no .ssh folder so I created that way back in the beginning, there was no known_hosts file so I ran
ssh -T git#bitbucket.org
I chose yes and this created a known_hosts file and when I tried to push again I got:
~/dev/sample_app git push -u origin --all
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
My .ssh folder is 700 and the keys inside are all 600.

You can set IdentityFile flag file in ~/.ssh/config file as follows:
Host bitbucket.org
IdentityFile ~/.ssh/id_rsa
When you run
ssh git#bitbucket.org
the ssh client allows you to selects a file from which the identity (private key) for RSA or DSA authentication is read.
SSH Client To Use Given Private Key ( identity file )

You might be using ssh as the git origin url. Try removing the ssh origin like so
git remote rm origin
Then add new origin with HTTPS url and try pushing again.
git remote add origin https://git#bitbucket.org/SOMETHING/SOMETHING.git
git push -u origin master
Make sure you paste your url from bitbucket as origin.

In my case on fresh Ubuntu 16 machine I was missing files in ~/.ssh folder so what worked:
Go to folder ~/.ssh
Run ssh-keygen and name your file i.e. id_rsa
Run cat ~/.ssh/id_rsa.pub | xclip -sel clip
If you miss xclip just apt-get install xclip :)
Go to (in url change USERNAME to your bitbucket username:) ) https://bitbucket.org/account/user/USERNAME/ssh-keys/
Click Add key and paste the key from the clipboard
Magic - it works now :)

Edit: As Dan Swain points out in the comments, from 1 March 2022 this answer will have been superseded by authentication policy changes: https://bitbucket.org/blog/deprecating-atlassian-account-password-for-bitbucket-api-and-git-activity
The same applies to Github repositories as well, FWIW.
Thanks for the heads-up, Dan.
It might make sysadmins recoil in horror, but after suffering this problem (Windows) I gave up on SSH and went back to HTTPS.
When first adding the remote repository to Git, replace the SSH reference 'git#bitbucket.org...' with the HTTPS URL 'https://<username>#bitbucket.org'.
You have to type your password in every time but, particularly under Windows where SSH is not as commonly available as with the *nix family, I see this as a minor inconvenience compared with the headaches of SSH.

After setting up git with git config --global user.name "My Name" and
git config --global user.email myemail#x.com, I was still having trouble with the Permission Denied, (publickey) error. To solve this, I first generated a new ssh token with
ssh-keygen
and copied it with
pbcopy < ~/.ssh/YOUR_KEY
After that, I went to bitbucket.com to add it as a new SSH key in my settings. Then, I returned to my terminal to add the new key with
ssh-add ~/.ssh/YOUR_KEY.
The big problem that I was having was that I missed the critical ssh-add [key] command.

I had similar problem with BitBucket. in my case, it only fixed after I found out I should remove sudo from git clone command!
According to Attlassian:
You shouldn't use sudo when cloning, pushing, or pulling because the
ssh-agent runs on the user level, not the root level.

A more sustainable solution is to edit .bashrc (e.g. vi ~/.bashrc) and then add the following line to it (replace the key name):
KEY="$HOME/.ssh/YOUR_KEY"
if [ -e "${KEY}" ]; then
ssh-add -q "${KEY}"
fi
This will load the key automatically when you start the shell

If you're using Fedora 33+ and using the RSA algorithm. Use more secure alogrithm like ECDSA or ED25519 instead:
ssh-keygen -t ed25519 -C "your_email#example.com"
Check out the bitbucket support for more details
Cause
The RSA algorithm is being quickly deprecated across operating systems and SSH clients because of various security vulnerabilities, with many of these technologies now outright denying the use of this algorithm.
(info) For example - here is the announcement from OpenSSH regarding
their upcoming deprecation of the ssh-rsa algorithm. In the event that
you are using an operating system or SSH client whose version has this
algorithm disabled, it's possible that any SSH keys previously
generated using this algorithm will no longer be accepted by these
technologies.
Resolution
To fully resolve this issue, our team recommends that these deprecated
keys be re-generated using a supported and more secure algorithm such
as ECDSA and ED25519

I faced same issues in Linux (Ubuntu).
I solved it using setup in git:
git config --global user.name "Your Name"
git config --global user.email your.email#example.com
Printing the public key using cat and SSH key to bitbucket.org:
$ cat ~/.ssh/id_rsa.pub
Adding Bitbucket and pushing up the repository:
git remote add origin git#bitbucket.org:<username>/your repository name.git
git push -u origin --all
That's all!

In my case, this issue happened because I had a number of ssh keys in the ~/.ssh. I had to create a bitbucket.org specific entry in ~/.ssh/config as follows:
Host bitbucket.org
Hostname bitbucket.org
IdentityFile <location-of-.ssh-directory>/bb-rsa
IdentitiesOnly=yes
My guess is that since we don't specify a key while cloning, ssh tries all the keys in ~/.ssh which bitbucket thinks as a hacking attempt and rejects our repo clone attempt.

In my case it solved the problem to add the ssh key from the directory
~/.ssh/id_rsa.pub
on bitbucket.org. I named it also id_rsa.pub on the website.
At the beginning I added another key I created just for bitbucket and named it like that. The first remote actions worked but after some days the request have been denied.

Check for exisiting SSH Key
ls -al ~/.ssh
Copy the SSH Key
cat ~/.ssh/id_rsa.pub | pbcopy
Add the copied SSH Key to 'Bitbucket Settings', 'Security', 'SSH Keys'.

If you have multiple keys in your computer make sure you add bitbucket to the list such as below in
.ssh/config
# Company account
Host company
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_accelya
# Personal account
Host personal
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_personal
# Personal account bitbucket
Host bitbucket
HostName bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_personal_bitbucket

This may be obvious, but I spent quite a bit of time on it.
Check the destination when running git remote -v
In my case I had the ssh keys perfectly set up but the output from this command was:
origin get#github.com:USERNAME/REPOSITORY.git
(notice the get not git)
and not
origin git#github.com:USERNAME/REPOSITORY.git
Again, this was a very particular case, but be sure to check the strings carefully of this system if you're having trouble.
You can fix this with the following commands:
git remote set-url origin git#github.com:USERNAME/REPOSITORY.git

Make sure your have switched to the correct user on terminal.
In my case root user was not the one which has ssh keys added at the bitbucket settings panel. Running git with sudo makes it run from root user and my own user was the one who has keys added.

In my case my issue was that I tried using the .ppk file the putty generated and no matter what I tried nothing worked.
In the end I figured that the it was the wrong file and I had to export it, save it as the id_rsa file and load it, then everything worked.

If any.ssh fix didn't work or you cloned as https there can be a validation issue. in my case, I fixed this error by providing my username and password when cloning the repo. This issue can occur when you are using multiple accounts in a same machine.
use "git clone https://username:password#github.com/username/repository.git" command with your user name and password and repo URL.

I like the Answers here, but they all kind of miss a possible root cause.
with the command:
ssh -T git#bitbucket.org
replace bitbucket.org with your own bitbucket host.
If you get an answer like:
This deploy key has read access to the following repositories:
team-name/repository-name
that is why pushing to the repository is not working.
This you can also double check in the Bitbucket Web UI, notice the read-only access in the description:
Hope this gives a different perspective to the same problem.

I update config file with the top line to get it working
PubkeyAcceptedKeyTypes +ssh-rsa
Host <yourhost>
IdentityFile ~/.ssh/id_rsa

My Solution:
git remote rm origin
Add you user name before #bitbucket.org to the repo URL
git remote add origin https://{USER_NAME}#bitbucket.org/{NAME}/{REPO_NAME}.git
git push -u origin master

In Windows, #efesaid answer worked for solving issues with the ssh connection test. By the way, you can add a -v to see what keys (by name) are being attempted and why the connection fails.
However, when pushing to bitbucket, using git#bitbucket.org:user/repo.git, it seems that the host is not precisely bitbucket.org so I still was getting permission denied problems. I solved them by (re)naming my key to id_rsa (this is the key name that was being attempted in the ssh test).
This works if you have a single rsa key. For multiple keys, perhaps the host in the config file must be
bitbucket.org:username
but I am no sure this is unde

I think that the bitbucket instructions are best. Check if ssh is installed and if not install it
krasen#krasen-Lenovo-Y50-70:~$ ssh -v
usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
[-D [bind_address:]port] [-E log_file] [-e escape_char]
[-F configfile] [-I xxxxx] [-i identity_file]
[-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]
[-O ctl_cmd] [-o option] [-p port]
[-Q cipher | cipher-auth | mac | kex | key]
[-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]
[-w local_tun[:remote_tun]] [user#]hostname [command]
krasen#krasen-Lenovo-Y50-70:~$ ls -a ~/.ssh
. .. google_compute_engine google_compute_engine.pub identity identity.pub known_hosts
krasen#krasen-Lenovo-Y50-70:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/krasen/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/krasen/.ssh/id_rsa.
Your public key has been saved in /home/krasen/.ssh/id_rsa.pub.
The key fingerprint is:
xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx krasen#krasen-Lenovo-Y50-70
The key's randomart image is:
+--[ RSA 2048]----+
| . |
| xx x |
| xxxxx |
| xxxxxxxxx |
| .xxxxxxxx |
| xxxxx |
| xxxxxxxxxxxx|
| xxxxxxxxxxxxx|
| xxxxxxxxxxx |
+-----------------+
krasen#krasen-Lenovo-Y50-70:~$ ls -la ~/.ssh
total 40
drwx------ 2 krasen krasen 4096 Jun 29 14:30 .
drwxr-xr-x 110 krasen krasen 4096 Jun 29 13:00 ..
-rw------- 1 krasen krasen 1675 Mar 18 2015 google_compute_engine
-rw-r--r-- 1 krasen krasen 409 Mar 18 2015 google_compute_engine.pub
-rw------- 1 krasen krasen 1679 Jun 29 13:15 identity
-rw-r--r-- 1 krasen krasen 409 Jun 29 13:15 identity.pub
-rw------- 1 krasen krasen 1679 Jun 29 14:30 id_rsa
-rw-r--r-- 1 krasen krasen 409 Jun 29 14:30 id_rsa.pub
-rw-r--r-- 1 krasen krasen 4698 Jun 29 13:16 known_hosts
krasen#krasen-Lenovo-Y50-70:~$ ssh-agent /bin/bash
to check if the agent is started
krasen#krasen-Lenovo-Y50-70:~$ ps -e | grep [s]sh-agent
26503 ? 00:00:00 ssh-agent
krasen#krasen-Lenovo-Y50-70:~$ ssh-add ~/.ssh/id_rsa
Identity added: /home/krasen/.ssh/id_rsa (/home/krasen/.ssh/id_rsa)
krasen#krasen-Lenovo-Y50-70:~$ ssh-add -l
2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx /home/krasen/.ssh/id_rsa (RSA)
krasen#krasen-Lenovo-Y50-70:~$ cat ~/.ssh/id_rsa.pub
ssh-rsa xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
get this key and add it as key in the bitbucket settings

I got round a similar issue where I had previously used HTTPS to access the repository and had to switch to SSH by setting the url like so;
git remote set-url origin ssh://git#bitbucket.org/...

My problem was to do with permissions.
My project directory was owned by root, but I was logged in as ubuntu. I would get PERMISSION DENIED if I typed in a git command, e.g. git pull origin master, so I used sudo git pull origin master.
I had registered ubuntu's SSH key from /home/ubuntu/.ssh/id_rsa.pub with BitBucket.
However, I was using sudo. So the SSH key used was actually /home/root/.ssh/id_rsa.pub which was different to what BitBucket had.
Solution for my case
chown -R username_here:username_here project/folder/here
Now it should work if you don't prepend sudo
OR give BitBucket root's key

In source tree select your project right click then you find an option "Convert to SSH"-> Repair -> login this solved for me

If you are using SourceTree with Bitbucket, the solution is the next:
Go to your personal Bitbucket settings
Got to App passwords and create an app password
Give the next permissions to the app password:
Repositories (R-W-A-D)
Projects (R-W)
Pull request (R-W)
After that, keep the password generated
Try to clone again your repo
A password popup will be displayed, input the generated password.
That's all.

Related

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

Configuring a new Digital Ocean droplet with SSH keys. When I run ssh-copy-id this is what I get:
ssh-copy-id user#012.345.67.89
/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
sign_and_send_pubkey: signing failed: agent refused operation
user#012.345.67.89's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'user#012.345.67.89'"
and check to make sure that only the key(s) you wanted were added.
However, when I then attempt to ssh in, this happens:
ssh user#012.345.67.89
sign_and_send_pubkey: signing failed: agent refused operation
user#012.345.67.89's password:
Upon entering the password, I am logged in just fine, but this of course defeats the purpose of creating the SSH key in the first place. I decided to take a look at the ssh-agent server-side and here's what I get:
user#012.345.67.89:~# eval `ssh-agent -s`
Agent pid 5715
user#012.345.67.89:~# ssh-add -l
The agent has no identities.
user/.ssh/authorized_keys does contain an ssh-rsa key entry, as well, but find -name "keynamehere" returns nothing.
Run ssh-add on the client machine, that will add the SSH key to the agent.
Confirm with ssh-add -l (again on the client) that it was indeed added.
After upgrading Fedora 26 to 28 I faced same issue.
And following logs were missing
/var/log/secure
/var/log/messages
ISSUE:
antop#localmachine  ~  ssh root#ocp1.example.com
sign_and_send_pubkey: signing failed: agent refused operation
root#ocp1.example.com's password:
error message is not pointing actual issue. Issue resolved by
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*
I was having the same problem in Linux Ubuntu 18. After the update from Ubuntu 17.10, every git command would show that message.
The way to solve it is to make sure that you have the correct permission on the id_rsa and id_rsa.pub.
Check the current chmod number by using stat --format '%a' <file>.
It should be 600 for id_rsa and 644 for id_rsa.pub.
To change the permission on the files use
chmod 600 id_rsa
chmod 644 id_rsa.pub
That solved my issue with the update.
Run the below command to resolve this issue.
It worked for me.
chmod 600 ~/.ssh/id_rsa
I once had a problem just like yours, and this is how I solved it through the following steps.
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*
ssh-copy-id user#ip
ssh-agent -s
ssh-add
I had the error when using gpg-agent as my ssh-agent and using a gpg subkey as my ssh key https://wiki.archlinux.org/index.php/GnuPG#gpg-agent.
I suspect that the problem was caused by having an invalid pin entry tty for gpg caused by my sleep+lock command used in my sway config
bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock'"
or just the sleep/suspend
Reset the pin entry tty to fix the problem
gpg-connect-agent updatestartuptty /bye > /dev/null
and the fix for my sway sleep+lock command:
bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock; gpg-connect-agent updatestartuptty /bye > /dev/null'"
eval "$(ssh-agent -s)"
To first start the ssh agent
ssh-add
To then add the ssh key
To this error:
# git pull
sign_and_send_pubkey: signing failed: agent refused operation
git#github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.
Verify or add again the public key in Github account > profile > ssh.
I solved like this:
# chmod 400 ~/.ssh/id_rsa
# ls ~/.ssh/id_rsa -ls
4 -r--------. 1 reinaldo reinaldo 1679 Jul 26 2017 /home/reinaldo/.ssh/id_rsa
# git pull
remote: Counting objects: 35, done.
remote: Compressing objects: 100% (19/19), done.
remote: Total 35 (delta 9), reused 34 (delta 9), pack-reused 0
Unpacking objects: 100% (35/35), done.
Thank you.
There could be various reason for getting the SSH error:
sign_and_send_pubkey: signing failed: agent refused operation
Some of them could be related to the issues highlighted by the other answers (see this thread answers), some of them could be hidden and thus would require a closer investigation.
In my case I've got the following error message:
sign_and_send_pubkey: signing failed: agent refused operation
user#website.domain.com: Permission denied (publickey,gssapi-keyex,gssapi-with-mic)
The only way to find the real problem was to invoke the -v verbose option which resulted in printing a lot of debugging info:
debug1: Connecting to website.domain.com [xxx.xxx.xxx.xxx] port 22.
debug1: Connection established.
debug1: identity file /home/user/.ssh/id_rsa.website.domain.com type 0
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_rsa.website.domain.com-cert type -1
Please note that the line saying key_load_public: No such file or directory is referring the next line and not the previous line.
So what SSH really says is that it could not find the public key file named id_rsa.website.domain.com-cert and that seemed to be the problem in my case since my public key file did not contain the -cert suffix.
Long story short: the fix in my case was just to make sure that the public key file was named as expected. I could never suspected that without debugging the connection.
The bottom line is USE THE SSH VERBOSE MODE (-v option) to figure out what is wrong, there could be various reasons, none that could be found on this/another thread.
First
ssh-add
then
ssh user#ip
this worked for me
Beware of how you name your ssh key files
If you have more than one key pair, you may be using ssh-keygen with the -f <key name> to name the output files. In my case, I was naming my keys like username#organization and username#organization.pub, which helps to keep multiple key pairs organized.
The problem is that the ssh agent doesn't like the # character.
In my case this was causing the sign_and_send_pubkey: signing failed: agent refused operation error, and was preventing the session keyring to interact with the ssh agent.
Renaming my key files to username_at_organization fixed the problem.
Yes. Run ssh-add on the client machine.
Then repeat command ssh-copy-id userserver#012.345.67.89
I got a sign_and_send_pubkey: signing failed: agent refused operation error as well. But in my case the problem was a wrong pinentry path.
In my ${HOME}/.gnupg/gpg-agent.conf the pinentry-program property was pointing to an old pinentry path. Correcting the path there and restarting the gpg-agent fixed it for me.
I discovered it by following the logs with journalctl -f. There where log lines like the following containing the wrong path:
Jul 02 08:37:50 my-host gpg-agent[12677]: ssh sign request failed: No pinentry <GPG Agent>
Jul 02 08:37:57 my-host gpg-agent[12677]: can't connect to the PIN entry module '/usr/local/bin/pinentry': IPC connect call failed
In my case the problem was that GNOME keyring was holding an invalid passphrase for the ssh key to be used. After spending indecent amount of time troubleshooting this issue I ran seahorse and found the entry to hold empty string. I can only guess that it was caused by mistyping the passphrase at first use some time earlier, and then probably cancelling the requester or so in order to fall back to command line. Updating the entry with correct passphrase immediately solved the problem. Deleting that entry (from "login" keyring) and reentering passphrase at that first prompt (and checking the appropriate checkbox) solves this too. Now agent gets the correct passphrase from the unlocked at login keyring named "login" and neither asks for passphrase nor "refuses operation" anymore. Of course YMMV.
This should be rather a SuperUser question.
Right I have the exact same error inside MacOSX SourceTree, however, inside a iTerm2 terminal, things work just dandy.
However, the problem seemed to be that I've got two ssh-agents running ;(
The first being /usr/bin/ssh-agent (aka MacOSX's) and then also the HomeBrew installed /usr/local/bin/ssh-agent running.
Firing up a terminal from SourceTree, allowed me to see the differences in SSH_AUTH_SOCK, using lsof I found the two different ssh-agents and then I was able to load the keys (using ssh-add) into the system's default ssh-agent (ie. /usr/bin/ssh-agent), SourceTree was working again.
For me the problem was a wrong copy/paste of the public key into Gitlab. The copy generated an extra return. Make sure what you paste is a one-line key.
I need to share, as I spent too much time looking for a solution
Here was the solution : https://unix.stackexchange.com/a/351742/215375
I was using this command :
ssh-keygen -o -t rsa -b 4096 -C "email#example.com"
gnome-keyring does not support the generated key.
Removing the -o argument solved the problem.
What worked here : on the client
1) ssh-add
2) ssh-copy-id user#server
The keys has been created some time ago with plain "ssh-keygen -t rsa"
I sw the error message because I copied across my ssh public key from client to server (with ssh-id-copy) without running ssh-add first, since I erroneously assumed I'd added them some time earlier.
quick note for those recently upgrading to "modern" ssh version [OpenSSH_8.1p1, OpenSSL 1.1.1d FIPS 10 Sep 2019] - supplied with fedora 31, seems not to be anymore accepting old DSA SHA256 keys (mine are dated 2006!) - created a new rsa key, public added to authorized, private on client, and everything works perfectly.
thanks for previous suggestions, especially the ssh -v has been very useful
As others have mentioned, there can be multiple reasons for this error.
If you are using SSH with Smart Card (PIV), and adding the card to ssh-agent with
ssh-add -s /usr/lib64/pkcs11/opensc-pkcs11.so
you may get the error
sign_and_send_pubkey: signing failed: agent refused operation
from ssh if the PIV authentication has expired, or if you have removed and reinserted the PIV card.
In that case, if you try to do another ssh-add -s you will still get an error:
Could not add card "/usr/lib64/opensc-pkcs11.so": agent refused operation
According to RedHat Bug 1609055 - pkcs11 support in agent is clunky, you instead need to do
ssh-add -e /usr/lib64/opensc-pkcs11.so
ssh-add -s /usr/lib64/opensc-pkcs11.so
Another reason for this is OpenSSH v9.0's new default of NTRU primes + x25519 key exchange, in combination with gpg-agent (at least, as at v2.2.32).
To work-around, disable the new key exchange algortihm (and thus it's security benefit) thus:
ssh -o 'KexAlgorithm -sntrup761x25519-sha512#openssh.com' [...]
(or the same in SSH config.)
cf. https://unix.stackexchange.com/questions/701131/use-ntrux25519-key-exchange-with-gpg-agent
According to Github security blog RSA keys with SHA-1 are no longer accepted.
Use the following command to create new SSH key with ECDSAencryption and add it to Github.
ssh-keygen -t ecdsa -b 521 -C "your_email#example.com"
original answer with details can be found here
This could cause by 1Passsword not support ssh-rsa key exchange. They support newer rsa-sha-512 and rsa-sha-256 with security considerations.
https://1password.community/discussion/comment/632712/#Comment_632712
Just to toss another cause into the ring...
My env was configured to use a Gemalto card...but I had an old keypair named id_rsa_gemalto_old(.pub) in my ~/.ssh/ and that -- having gemalto in the name -- was enough for git fetch to result in sign_and_send_pubkey: signing failed: agent refused operation.
(Ubuntu 18.04.6)

ssh not expanding ~ correctly?

So for permission reasons, I have had to change my default home directory to a non-standard location.
I did export HOME=/non/standard/home and then confirmed this was working with
$ cd ~
$ pwd
/non/standard/home
Even though man ssh says that it looks in ~/.ssh for keys and identity files, it doesn't seem to:
$ ls ~/.ssh
cluster_key cluster_key.pub config
$ ssh host
Could not create directory '/home/myname/.ssh'.
The authenticity of host 'host (<ip address deleted>)' can't be established.
RSA key fingerprint is <finerprint deleted>.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/myname/.ssh/known_hosts).
Permission denied (publickey,gssapi-with-mic).
What does it insist on looking in /home/myname? The man page state that is consults the HOME environment variable. Using the -F option also fails to work.
$ ssh -version
OpenSSH_4.3p2, OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008
Bad escape character 'rsion'.
When you run "export" command you actually affect only your process of BASH/SH. When .ssh looks for it it has it's own instance and thus looks in the default directory. You need to run the command usermod -m -d /path/to/new/home/dir userNameHere (change the user that .ssh uses, probably admin)

gerrit ssh login issue

I am having an issue with my ssh login to gerrit. When I use one key file it works, but with the other it does not.
ssh gerrit_admin#<host> -p 29418 -i ~/.ssh/project/prod_rsa
**** Welcome to Gerrit Code Review ****
.....
ssh gerrit_admin#<host> -p 29418 -i ~/.ssh/id_rsa
Permission denied (publickey).
Now the issue seems obvious that one key is on the server and one is not. However both of these key files are identical. Not just copies, but a hard link meaning they both point to the exact same blocks on disk.
ls -il ~/.ssh/id_rsa ~/.ssh/project/prod_rsa
7603695 -rw------- 2 nellis nellis 1693 Jun 23 13:22 /home/nellis/.ssh/id_rsa
7603695 -rw------- 2 nellis nellis 1693 Jun 23 13:22 /home/nellis/.ssh/project/prod_rsa
Why do these "two" keys which are very much the same produce different reseults?
Not sure exactly what the problem here was, but I ended up just ditching the keys and importing new ones via the web interface.

oneadmin opennebula ssh localhost

We've been trying to use opennebula to simulate a cluster but ssh is driving us crazy.
For some, still unknown reasons, it is necessary that user oneadmin (created by opennebula) is able to ssh to local host. The "home" directory of opennebula (created by it) is /var/lib/one and inside "one" we can find .ssh directory. So here's what I've done up to now:
sudo -su oneadmin
oneadmin#pc:$ cd /var/lib/one/.ssh
oneadmin#pc:/var/lib/one/.ssh$ ssh-keygen -t rsa
oneadmin#pc:/var/lib/one/.ssh$ cat id_rsa.pub >> authorized_keys
Moreover, I've changed all permissions: all files and directory have oneadmin as owner and 600 (as I can read from the opennebula guide)
and finally, by root, I do
service ssh restart
Then I login from one terminal as oneadmin again but when I perform:
ssh oneadmin#localhost
here's what I get
Permission denied (publickey).
where am I making this damned mistake? We've lost more than one day for all these permissions!
I've just run into a similar problem - turns out Open Nebula didn't get on with selinux.
Finally found the solution over here - http://n40lab.wordpress.com/2012/11/26/69/ - we need to restore the context to ~/.ssh/authorized_keys:
$ chcon -v --type=ssh_home_t /var/lib/one/.ssh/authorized_keys
$ semanage fcontext -a -t ssh_home_t /var/lib/one/.ssh/authorized_keys

Best way to use multiple SSH private keys on one client [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 2 years ago.
Improve this question
I want to use multiple private keys to connect to different servers or different portions of the same server (my uses are system administration of server, administration of Git, and normal Git usage within the same server). I tried simply stacking the keys in the id_rsa files to no avail.
Apparently a straightforward way to do this is to use the command
ssh -i <key location> login#server.example.com
That is quite cumbersome.
Any suggestions as to how to go about doing this a bit easier?
From my .ssh/config:
Host myshortname realname.example.com
HostName realname.example.com
IdentityFile ~/.ssh/realname_rsa # private key for realname
User remoteusername
Host myother realname2.example.org
HostName realname2.example.org
IdentityFile ~/.ssh/realname2_rsa # different private key for realname2
User remoteusername
Then you can use the following to connect:
ssh myshortname
ssh myother
And so on.
You can instruct ssh to try multiple keys in succession when connecting. Here's how:
$ cat ~/.ssh/config
IdentityFile ~/.ssh/id_rsa
IdentityFile ~/.ssh/id_rsa_old
IdentityFile ~/.ssh/id_ed25519
# ... and so on
$ ssh server.example.com -v
....
debug1: Next authentication method: publickey
debug1: Trying private key: /home/example/.ssh/id_rsa
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/example/.ssh/id_rsa_old
debug1: read PEM private key done: type RSA
....
[server ~]$
This way you don't have to specify what key works with which server. It'll just use the first working key.
Also you would only enter a passphrase if a given server is willing to accept the key. As seen above ssh didn't try to ask for a password for .ssh/id_rsa even if it had one.
Surely it doesn't outbeat a per-server configuration as in other answers, but at least you won't have to add a configuration for all and every server you connect to!
The answer from Randal Schwartz almost helped me all the way.
I have a different username on the server, so I had to add the User keyword to my file:
Host friendly-name
HostName long.and.cumbersome.server.name
IdentityFile ~/.ssh/private_ssh_file
User username-on-remote-machine
Now you can connect using the friendly-name:
ssh friendly-name
More keywords can be found on the OpenSSH man page. NOTE: Some of the keywords listed might already be present in your /etc/ssh/ssh_config file.
The previous answers have properly explained the way to create a configuration file to manage multiple ssh keys. I think, the important thing that also needs to be explained is the replacement of a host name with an alias name while cloning the repository.
Suppose, your company's GitHub account's username is abc1234.
And suppose your personal GitHub account's username is jack1234
And, suppose you have created two RSA keys, namely id_rsa_company and id_rsa_personal. So, your configuration file will look like below:
# Company account
Host company
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_company
# Personal account
Host personal
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_personal
Now, when you are cloning the repository (named demo) from the company's GitHub account, the repository URL will be something like:
Repo URL: git#github.com:abc1234/demo.git
Now, while doing git clone, you should modify the above repository URL as:
git#company:abc1234/demo.git
Notice how github.com is now replaced with the alias "company" as we have defined in the configuration file.
Similary, you have to modify the clone URL of the repository in the personal account depending upon the alias provided in the configuration file.
ssh-add ~/.ssh/xxx_id_rsa
Make sure you test it before adding with:
ssh -i ~/.ssh/xxx_id_rsa username#example.com
If you have any problems with errors sometimes changing the security of the file helps:
chmod 0600 ~/.ssh/xxx_id_rsa
Generate an SSH key:
$ ssh-keygen -t rsa -C <email1#example.com>
Generate another SSH key:
$ ssh-keygen -t rsa -f ~/.ssh/accountB -C <email2#example.com>
Now, two public keys (id_rsa.pub, accountB.pub) should be exists in the ~/.ssh/ directory.
$ ls -l ~/.ssh # see the files of '~/.ssh/' directory
Create configuration file ~/.ssh/config with the following contents:
$ nano ~/.ssh/config
Host bitbucket.org
User git
Hostname bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
Host bitbucket-accountB
User git
Hostname bitbucket.org
PreferredAuthentications publickey
IdentitiesOnly yes
IdentityFile ~/.ssh/accountB
Clone from default account.
$ git clone git#bitbucket.org:username/project.git
Clone from the accountB account.
$ git clone git#bitbucket-accountB:username/project.git
Note: Because of the User git directive, you can omit the git# portion of the repo URL, shortening your clone command like so:
$ git clone bitbucket-accountB:username/project.git
This is the only purpose of that directive. If you don't need it (e.g. you always copy-paste the git clone command from the website), you can leave it out of the config.
See More Here
I would agree with Tuomas about using ssh-agent. I also wanted to add a second private key for work and this tutorial worked like a charm for me.
Steps are as below:
$ ssh-agent bash
$ ssh-add /path.to/private/key e.g ssh-add ~/.ssh/id_rsa
Verify by $ ssh-add -l
Test it with $ssh -v <host url> e.g ssh -v git#assembla.com
Now, with the recent version of Git, we can specify sshCommand in the repository-specific Git configuration file:
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
sshCommand = ssh -i ~/.ssh/id_rsa_user
[remote "origin"]
url = git#bitbucket.org:user/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
For me on MacOs, the only working solution was to simply add this in file ~/.ssh/config:
Host *
IdentityFile ~/.ssh/your_ssh_key
IdentityFile ~/.ssh/your_ssh_key2
IdentityFile ~/.ssh/your_ssh_key3
AddKeysToAgent yes
your_ssh_key is without any extension. Don't use .pub.
I had run into this issue a while back, when I had two Bitbucket accounts and wanted to had to store separate SSH keys for both. This is what worked for me.
I created two separate ssh configurations as follows.
Host personal.bitbucket.org
HostName bitbucket.org
User git
IdentityFile /Users/username/.ssh/personal
Host work.bitbucket.org
HostName bitbucket.org
User git
IdentityFile /Users/username/.ssh/work
Now when I had to clone a repository from my work account - the command was as follows.
git clone git#bitbucket.org:teamname/project.git
I had to modify this command to:
git clone git#**work**.bitbucket.org:teamname/project.git
Similarly the clone command from my personal account had to be modified to
git clone git#personal.bitbucket.org:name/personalproject.git
Refer this link for more information.
Use ssh-agent for your keys.
Here is the solution that I used inspired from the answer of sajib-khan. The default configuration is not set; it's my personal account on GitLab and the other specified is my company account. Here is what I did:
Generate the SSH key
ssh-keygen -t rsa -f ~/.ssh/company -C "name.surname#company.com"
Edit the SSH configuration
nano ~/.ssh/config
Host company.gitlab.com
HostName gitlab.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/company
Delete the cached SSH key(s)
ssh-add -D
Test it!
ssh -T git#company.gitlab.com
Welcome to GitLab, #hugo.sohm!
ssh -T git#gitlab.com
Welcome to GitLab, #HugoSohm!
Use it!
Company account
git clone git#company.gitlab.com:group/project.git
Personal/default account
git clone git#gitlab.com:username/project.git
Here is the source that I used.
For those who are working with aws I would highly recommend working with EC2 Instance Connect.
Amazon EC2 Instance Connect provides a simple and secure way to connect to your instances using Secure Shell (SSH).
With EC2 Instance Connect, you use AWS Identity and Access Management (IAM) policies and principles to control SSH access to your instances, removing the need to share and manage SSH keys.
After installing the relevant packages (pip install ec2instanceconnectcli or cloning the repo directly) you can connect very easy to multiple EC2 instances by just changing the instance id:
What is happening behind the scenes?
When you connect to an instance using EC2 Instance Connect, the Instance Connect API pushes a one-time-use SSH public key to the instance metadata where it remains for 60 seconds. An IAM policy attached to your IAM user authorizes your IAM user to push the public key to the instance metadata.
The SSH daemon uses AuthorizedKeysCommand and AuthorizedKeysCommandUser, which are configured when Instance Connect is installed, to look up the public key from the instance metadata for authentication, and connects you to the instance.
(*) Amazon Linux 2 2.0.20190618 or later and Ubuntu 20.04 or later comes preconfigured with EC2 Instance Connect.
For other supported Linux distributions, you must set up Instance Connect for every instance that will support using Instance Connect. This is a one-time requirement for each instance.
Links:
Set up EC2 Instance Connect
Connect using EC2 Instance Connect
Securing your bastion hosts with Amazon EC2 Instance Connect
You can create a configuration file named config in your ~/.ssh folder. It can contain:
Host aws
HostName *yourip*
User *youruser*
IdentityFile *idFile*
This will allow you to connect to machines like this
ssh aws
As mentioned on a Atlassian blog page,
generate a config file within the .ssh folder, including the following text:
#user1 account
Host bitbucket.org-user1
HostName bitbucket.org
User git
IdentityFile ~/.ssh/user1
IdentitiesOnly yes
#user2 account
Host bitbucket.org-user2
HostName bitbucket.org
User git
IdentityFile ~/.ssh/user2
IdentitiesOnly yes
Then you can simply checkout with the suffix domain and within the projects you can configure the author names, etc. locally.
Multiple key pairs on GitHub
1.0 SSH configuration file
1.1 Create ~/.ssh/config
1.2 chmod 600 ~/.ssh/config (must)
1.3 Input the following into the file:
Host pizza
HostName github.com
PreferredAuthentications publickey # optional
IdentityFile ~/.ssh/privatekey1
Case A: Fresh new Git clone
Use this command to Git clone:
$ git clone git#pizza:yourgitusername/pizzahut_repo.git
Note: If you want to change the host name “pizza” of .ssh/config in the future, go into the Git cloned folder, edit .git/config file URL line (see case B)
Case B: Already have Git clone folder
2.1 Go to the cloned folder, and then go into the .git folder
2.2 Edit configuration file
2.3 Update the URL from *old to new:
(Old) URL = git#github.com:yourgitusername/pizzahut_repo.git
(New) URL = git#pizza:yourgitusername/pizzahut_repo.git
IMPORTANT: You must start ssh-agent
You must start ssh-agent (if it is not running already) before using ssh-add as follows:
eval `ssh-agent -s` # start the agent
ssh-add id_rsa_2 # Where id_rsa_2 is your new private key file
Note that the eval command starts the agent on Git Bash on Windows. Other environments may use a variant to start the SSH agent.
On Ubuntu 18.04 (Bionic Beaver) there is nothing to do.
After having created an second SSH key successfully the system will try to find a matching SSH key for each connection.
Just to be clear you can create a new key with these commands:
# Generate key make sure you give it a new name (id_rsa_server2)
ssh-keygen
# Make sure ssh agent is running
eval `ssh-agent`
# Add the new key
ssh-add ~/.ssh/id_rsa_server2
# Get the public key to add it to a remote system for authentication
cat ~/.ssh/id_rsa_server2.pub
I love the approach to set the following in file ~/.ssh/config:
# Configuration for GitHub to support multiple GitHub keys
Host github.com
HostName github.com
User git
# UseKeychain adds each keys passphrase to the keychain so you
# don't have to enter the passphrase each time.
UseKeychain yes
# AddKeysToAgent would add the key to the agent whenever it is
# used, which might lead to debugging confusion since then
# sometimes the one repository works and sometimes the
# other depending on which key is used first.
# AddKeysToAgent yes
# I only use my private id file so all private
# repositories don't need the environment variable
# `GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa"` to be set.
IdentityFile ~/.ssh/id_rsa
Then in your repository you can create a .env file which contains the ssh command to be used:
GIT_SSH_COMMAND="ssh -i ~/.ssh/your_ssh_key"
If you then use e.g. dotenv the environment environment variable is exported automatically and whoop whoop, you can specify the key you want per project/directory. The passphrase is asked for only once since it is added to the keychain.
This solution works perfectly with Git and is designed to work on a Mac (due to UseKeychain).
On CentOS 6.5 running OpenSSH_5.3p1 and OpenSSL 1.0.1e-fips, I solved the problem by renaming my key files so that none of them had the default name.
My .ssh directory contains id_rsa_foo and id_rsa_bar, but no id_rsa, etc.
You can try this sshmulti npm package for maintaining multiple SSH keys.