How to select the private key used by a remote machine to create the known_hosts entry given to my local server - ssh

Passwordless ssh has two components, user authentication and server authentication. My user authentication is fine. I have created a public private key pair and place my public key in the authorized_keys file. My question is about the public key my local machine obtains from the remote machine which is used to authenticate the remote machine I'm connecting to:
How do I select the private key used by the remote server that goes into my local server's known_hosts?
I am constantly creating and deleting remove VMs on a cloud provider on demand to save money. Unfortunately, the new VM which replaces the delete one has generated a new private-public key pair used in the known_hosts
I do not want to have to manually type ssh-keygen -R <host> for each host. I thought the easiest would be if I have a hardcoded private key on the remote server already.
Please note this is related to previous public-private key questions like ssh remote host identification has changed , but is not duplicated! I know that you can manually fix the issue with ssh-keygen -R <host>. I am looking for a more automatic approach.
Diagram:
-------------------- -----------------------
| My machine | | Remote Machine |
| - - - - - - - - -| | - - - - - - - - - - |
| Host Public Key |<---host-authentication---| ** Host Private Key |
| (known_hosts) | | |
| - - - - - - - - -| | - - - - - - - - - - |
| User Private Key |----user-authentication-->| User Public Key |
| | | (authorized_hosts) |
-------------------- -----------------------
** : How do I change this part?

META: this is really SysOps not programming and probably belongs on serverfault or superuser, or maybe unix.SX.
You don't say which SSH server(s) your VMs are using, although I expect cloud providers probably use OpenSSH to avoid possible license issues. IF this guess is correct sshd normally has its configuration and key files in /etc/ssh although this can be changed. See the man page on any system or on the web under FILES, duplicated here per SO convention:
/etc/ssh/ssh_host_dsa_key
/etc/ssh/ssh_host_ecdsa_key
/etc/ssh/ssh_host_ed25519_key
/etc/ssh/ssh_host_rsa_key
These files contain the private parts of the host keys. These files should only be owned by root, readable only by root, and not accessible to others. Note that sshd does not start if these files are group/world-accessible.
/etc/ssh/ssh_host_dsa_key.pub
/etc/ssh/ssh_host_ecdsa_key.pub
/etc/ssh/ssh_host_ed25519_key.pub
/etc/ssh/ssh_host_rsa_key.pub
These files contain the public parts of the host keys. These files should be world-readable but writable only by root. Their contents should match the respective private parts. These files are not really used for anything; they are provided for the convenience of the user so their contents can be copied to known hosts files. These files are created using ssh-keygen(1).
A host can have up to four keypairs for protocol v2: RSA, DSA, ECDSA, and ED25519. Very old versions only support RSA and DSA. Oldish versions don't support ED25519. Newish versions don't use DSA by default but do support it. The code still supports protocol v1 with ssh_host_key[.pub] (no algorithm in name) but v1 is way obsolete and broken and you shouldn't use it.
The man page doesn't say so that I can see, but in practice for some years now OpenSSH server usually autogenerates host keys if they are missing, either in code or in the package install/startup scripts, so just deleting keytypes you don't want may not work. Your client may be able to control which of the supported pubkey algorithms the host uses; for fairly recent versions of OpenSSH see the man page for ssh_config under HostKeyAlgorithms. Otherwise either upload all supported key types, or upload the one(s) you want and tweak the sshd_config file to not use the others or create invalid but unwritable and undeletable files for the others so sshd can't use them.
ASIDE: I would reverse your diagram. Host auth always occurs first and in practice is always pubkey (the standard has other options but they aren'[t used); client auth usually occurs second, but can be skipped, and can be either pubkey or password.

I ended up hacking my scripts with (which is insecure):
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null <hostname>
-o StrictHostKeyChecking=no : will accept connect to a new host
-o UserKnownHostsFile=/dev/null : saves new hosts to /dev/null so every time you ssh, it's a new host
This was originally suggested in https://askubuntu.com/questions/87449/how-to-disable-strict-host-key-checking-in-ssh to solve a similar problem.

Related

PyCharm says remote host ID has changed, but ssh-keyscan does not

This morning PyCharm started warning me:
Warning: remote host identification has changed! IT IS
POSSIBLE THAT SOMEONE IS DOING SOMETHING
NASTY! Someone could be eavesdropping on you
right now (man-in-the-middle-attack)! It is also
possible that the host key has just been changed. The
fingerprint for the ssh-ed25519 key sent by the
remote host is
[redacted A]
Do you want to update the key in
/Users/[myhome]/.ssh/known_hosts and resume
connecting?
Then it asks if I want to change ~/Users/[myhome]/.ssh/known_hosts.
The target host is used as an sftp to transfer my code to the remote server. Its name is an alias for two data transfer nodes. I can look at their ssh public keys using ssh-keyscan -t ed25519 alias.remotehost.com and I get a key that matches the one in my known_hosts file. I can also connect to a different remote server, at which time I do not get a warning about changed ssh keys, and ssh-keyscan the original remote host and I get the same keys in known_hosts.
The key that PyCharm says is new does not match any of the now twice confirmed ssh keys. The format of the PyCharm-message-derived key is even totally different from the keys from ssh-keyscan.
What is going on? I don't want to just blast through a security warning, and I'd like some guidance on where to look to see why PyCharm is giving me this warning that I cannot confirm otherwise.
The reason is not necessarily a security issue. Did you double-check your SSH configuration, in particular the known_hosts file used by PyCharm is the same you're checking?
https://man.openbsd.org/ssh_config#UserKnownHostsFile
You may want to take a look at the PyCharm SSH Configurations ... Connection Parameters; for example the different format you're seeing might be related to storing hosts in hash format option (to be confirmed):
https://www.jetbrains.com/help/pycharm/settings-tools-ssh-configurations.html
You can try to recreate a SSH configuration from scratch as described here:
https://www.jetbrains.com/help/pycharm/create-ssh-configurations.html
If you're 100% sure that the key in the known_hosts file is the right one and matches your target server's, this will remove the entry in known_hosts file and you should be again prompted to accept the server key on the next connection:
ssh-keygen -R <host>
(where host is your target server, IP or hostname: "alias.remotehost.com" in your example; you can provide the path for the file using -f <path>)
References
ssh remote host identification has changed
https://stackabuse.com/how-to-fix-warning-remote-host-identification-has-changed-on-mac-and-linux/
https://youtrack.jetbrains.com/issue/CPP-19720

Can I specify the expected host key fingerprint for Ansible ssh?

I'd like to be able to check the public key fingerprint for each host (the ssh servers) in an inventory into my host_vars directory. All my searches on the topic lead me to various resources describing either how to specify the client key or how to disable host key checking altogether. It seems to me though that once I've established that a host (server) key is authentic, it would be good to share that knowledge with others and keep the security benefit of host key checking. Is this possible?
I would suspect that in the same way those articles you have read are updating ansible_ssh_common_args in order to set -o UserKnownHostsFile=/dev/null you can similarly update that fact to use -o UserKnownHostsFile={{ playbook_dir }}/my_known_hosts to bundle the known hosts file alongside the playbooks that would use them

Stop Karaf from generating new SSH keys on startup

I've noticed that Karaf keeps generating new SSH keys on each startup. It makes automatic scripts connecting via ssh useless, because new key must be manually accepted each time.
Is it possible to stop that behaviour and generate new keys only once per new installation?
More debug info: I've noticed, that 'etc/host.key' has not changed. However, after stopping and starting karaf I get the message:
ssh -p 8101 localhost -oHostKeyAlgorithms=+ssh-dss
Offending DSA key in ~/.ssh/known_hosts:5
remove with:
ssh-keygen -f "~/.ssh/known_hosts" -R [localhost]:8101
DSA host key for [localhost]:8101 has changed and you have requested strict checking.
Host key verification failed.
The fact that DSA keys are generated doesn't match the log message from karaf.log as well:
INFO | sshd-SshServer[20056f77]-nio2-thread-2 |
SimpleGeneratorHostKeyProvider | 48 - org.apache.sshd.core - 1.2.0 |
generateKeyPair(RSA) generating host key - size=4096
My etc/org.apache.karaf.shell.cfg:
sshPort=8101
sshHost=0.0.0.0
sshRealm=karaf
hostKey=${karaf.etc}/host.key
algorithm=RSA
keySize=4096
After digging in logs I've found out, that host.key file is not loaded properly:
2017-03-29T13:44:58,977 | WARN |
sshd-SshServer[18c17f90]-nio2-thread-1 |
SimpleGeneratorHostKeyProvider | 48 - org.apache.sshd.core - 1.2.0 |
resolveKeyPair(~/karaf-docker/apache-karaf-4.1.0/etc/host.key) Failed
(InvalidKeySpecException) to load: Missing classes:
org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPrivateCrtKey
2017-03-29T13:45:00,340 | ERROR |
sshd-SshServer[18c17f90]-nio2-thread-1 |
SimpleGeneratorHostKeyProvider | 48 - org.apache.sshd.core - 1.2.0 |
Overwriting key (~/karaf-docker/apache-karaf-4.1.0/etc/host.key) is
disabled: using throwaway ssh-dss:
SHA256:3yWwxdzoymMvEBYIWMIguQ8G3J7kfapd+avCMoue2R4
2017-03-29T13:45:00,342 | WARN |
sshd-SshServer[18c17f90]-nio2-thread-1 | ServerSessionImpl
The Apache SSHD reads/writes host.key using Java Serialization which might cause issues in OSGi (and, maybe even worse, redeploy of feature might turn the file useless).
Karaf creates the server key when you first connect using ssh. It will then place the key in karaf home etc/host.key. So the key should only be created once for each karaf server.
You can also provide your own key there to avoid the overhead of the creation.
The key is generated by org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider. When it creates a key you should see this message in the log:
generateKeyPair(RSA) generating host key - size=4096
I've decided to answer my own question because I've found a solution that doesn't require involving in discussions about karaf implementations etc.
The cause of the problem was because Karaf module org.apache.karaf.shell.ssh is unable either to persist or to read generated keys from host.key, I suppose it was tested only against the scenario below:
Use keys in PEM format by adding the line
hostKeyFormat=PEM
to file etc/org.apache.karaf.shell.cfg
Generate the key using openssl tools:
openssl genrsa -out etc/host.key 4096
After starting, the Karaf will use the key generated by openssl, and not try to generate its own. Tested against karaf 4.1.x

How to specify a different location for ssh keys loading during rhc setup?

I am using rhc cli tool for OpenShift projects. I have encountered a problem with default rhc ssh key.
On any ssh related action (setup, app-create, etc..) rhc creates ~/.ssh/id_rsa key if it does not exist. I do not like that behaviour, and I would like it to use something like ~/.ssh/OpenShift-SSH-Keys/my_id_rsa.
Because during rhc setup, it did not ask me from which location I wanted to load the keys. Thus I also looked in ~/.openshift/express.conf and I only saw the configurations for ssl; not ssh.
So I found on the internet this following configuration line to add to ~/.openshift/express.conf:
ssh_key_file='~/.ssh/OpenShift-SSH-Keys/my_id_rsa'
I added it and also modified my ~/.ssh/config file:
# Openshift *.rhcloud.com ssh-key config
Host *.rhcloud.com
IdentityFile ~/.ssh/OpenShift-SSH-Keys/my_id_rsa
IdentitiesOnly yes
VerifyHostKeyDNS yes
StrictHostKeyChecking no
PasswordAuthentication no
UserKnownHostsFile ~/.ssh/known_hosts
To finish I setup my account like that:
rhc setup --config ~/.openshift/express.conf -l myusername#gmail.com
Output of this command line:
OpenShift Client Tools (RHC) Setup Wizard
This wizard will help you upload your SSH keys, set your application namespace, and check that other programs like Git are
properly installed.
If you have your own OpenShift server, you can specify it now. Just hit enter to use the server for OpenShift Online:
openshift.redhat.com.
Enter the server hostname: |openshift.redhat.com|
You can add more servers later using 'rhc server'.
Using myusername#gmail.com to login to openshift.redhat.com
RSA 1024 bit CA certificates are loaded due to old openssl compatibility
Password: ************************
OpenShift can create and store a token on disk which allows to you to access the server without using your password. The
key is stored in your home directory and should be kept secret. You can delete the key at any time by running 'rhc
logout'.
Generate a token now? (yes|no) yes
Generating an authorization token for this client ... RSA 1024 bit CA certificates are loaded due to old openssl compatibility
lasts 29 days
Saving configuration to /Users/theuser/.openshift/express.conf ... done
No SSH keys were found. We will generate a pair of keys for you.
Created: /Users/theuser/.ssh/id_rsa.pub
Your public SSH key must be uploaded to the OpenShift server to access code. Upload now? (yes|no) no
You can upload your public SSH key at a later time using the 'rhc sshkey' command
Checking for git ... found git version 2.5.0
Checking common problems .. done
Checking for a domain ... mydomainz1955
Checking for applications ... found 1
myapp http://myapp-mydomainz1955.rhcloud.com/
You are using 2 of 3 total gears
The following gear sizes are available to you: small
Your client tools are now configured.
As you can see in the output of the command line: No SSH keys were found. We will generate a pair of keys for you., although I specified in the ~/.openshift/express.conf that I already had ssh keys generated, rhc setup did not take them in consideration or did not find them.
So according to you guys, is it possible to somehow specify a different location for ssh keys loading during rhc setup?
Note: I know how to add additional ssh key, but I would like to stop rhc creating/using ~/.ssh/id_rsa
As far as I see you just want rhc to not use your default ssh key. So here is how you create a separate key and configure rhc to use it instead of the default one.
Key points are that:
you select no to generating and uploading ssh key during rhc
setup
you add your key separately with rhc sshkey add
you configure ssh to use the different key for that domain as you
list in your original example
Does this cover your concerns?
[crackit#koTapaH ~]$ mkdir /home/crackit/my_key_location
[crackit#koTapaH ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/crackit/.ssh/id_rsa): /home/crackit/my_key_location/key.rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/crackit/my_key_location/key.rsa.
Your public key has been saved in /home/crackit/my_key_location/key.rsa.pub.
The key fingerprint is:
c5:20:15:fb:17:96:86:8f:88:28:18:17:2a:b8:eb:51 crackit#koTapaH
The key's randomart image is:
+--[ RSA 2048]----+
| . ..+. |
|.. . . + . . |
|= . . + = |
|.= . . + = . |
|o .E. . S o o |
| ... . |
|.. |
|. . |
| . |
+-----------------+
[crackit#koTapaH ~]$ rhc setup
OpenShift Client Tools (RHC) Setup Wizard
This wizard will help you upload your SSH keys, set your application namespace,
and check that other programs like Git are properly installed.
If you have your own OpenShift server, you can specify it now. Just hit enter to
use the server for OpenShift Online: openshift.redhat.com.
Enter the server hostname: |openshift.redhat.com|
You can add more servers later using 'rhc server'.
Login to openshift.redhat.com:
Login to openshift.redhat.com: asdfgg#example.com
Password: *************
OpenShift can create and store a token on disk which allows to you to access the
server without using your password. The key is stored in your home directory and
should be kept secret. You can delete the key at any time by running 'rhc
logout'.
Generate a token now? (yes|no) yes
Generating an authorization token for this client ... lasts about 1 month
Saving configuration to /home/crackit/.openshift/express.conf ... done
No SSH keys were found. We will generate a pair of keys for you.
Created: /home/crackit/.ssh/id_rsa.pub
Your public SSH key must be uploaded to the OpenShift server to access code.
Upload now? (yes|no)
no
You can upload your public SSH key at a later time using the 'rhc sshkey'
command
Checking for git ... found git version 2.1.0
Checking common problems .. done
Checking for a domain ... foobar
Checking for applications ... found 2
jenkins http://jenkins-foobar.rhcloud.com/
tmp http://tmp-foobar.rhcloud.com/
You are using 2 of 3 total gears
The following gear sizes are available to you: small, medium
Your client tools are now configured.
[crackit#koTapaH ~]$ rhc sshkey add mykey my_key_location/key.rsa.pub
RESULT:
SSH key my_key_location/key.rsa.pub has been added as 'mykey'
[crackit#koTapaH ~]$ vi .ssh/config
<.. do your modifications here ..>
[crackit#koTapaH ~]$ rhc ssh tmp
Connecting to 550000a0e0b8cdca4c000040#tmp-foobar.rhcloud.com ...
*********************************************************************
You are accessing a service that is for use only by authorized users.
If you do not have authorization, discontinue use at once.
Any use of the services is subject to the applicable terms of the
agreement which can be found at:
https://www.openshift.com/legal
*********************************************************************
Welcome to OpenShift shell
This shell will assist you in managing OpenShift applications.
!!! IMPORTANT !!! IMPORTANT !!! IMPORTANT !!!
Shell access is quite powerful and it is possible for you to
accidentally damage your application. Proceed with care!
If worse comes to worst, destroy your application with "rhc app delete"
and recreate it
!!! IMPORTANT !!! IMPORTANT !!! IMPORTANT !!!
Type "help" for more info.
[tmp-foobar.rhcloud.com 550000a0e0b8cdca4c000040]\> exit
exit
Connection to tmp-foobar.rhcloud.com closed.
[crackit#koTapaH ~]$
Update: I didn't notice keys are generated. But I am sure that the generated keys during rhc setup are not actually used. First because the keys from default location are never added to openshift. And you can see a quick proof below. Another way to see is rhc sshkeys list.
Another thing is that if you already have keys in default location, then no keys are generated (in which case you still select no to not upload them). But it is actually a minor bug IMO in rhc that ssh keys are generated without asking the user. It might be a very rare use case - you don't have default key and you want to use a key from non-standard location (this is not your use case where you have a key in standard location, just don't want to use it) but still IMO one shouldn't generate something user did not request. So here's how I show you that only my desired custom key is used:
[crackit#koTapaH ~]$ rm -rf .ssh/id_rsa*
[crackit#koTapaH ~]$ rhc ssh tmp
Connecting to 550000a0e0b8cdca4c000040#tmp-foobar.rhcloud.com ...
<...>
Type "help" for more info.
[tmp-foobar.rhcloud.com 550000a0e0b8cdca4c000040]\> exit
exit
Connection to tmp-foobar.rhcloud.com closed.
[crackit#koTapaH ~]$ ls .ssh/
config known_hosts
[crackit#koTapaH ~]$
Update 2 Of course token cannot help you with ssh:
[crackit#koTapaH ~]$ rm -rf my_key_location
[crackit#koTapaH ~]$ rhc ssh tmp
Connecting to 550000a0e0b8cdca4c000040#tmp-foobar.rhcloud.com ...
no such identity: /home/crackit/my_key_location/key.rsa: No such file or directory
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
SSH key is used for ssh. Token is used for API requests. These are different use cases. rhc uses the ssh executable underneath so using a custom key means to edit ~/.ssh/config to set your default key to another location or set different keys for different hosts. This is not handled well by rhc setup. But once you have your key set, you don't have to run rhc setup anymore.

Can not SSH to openshift

I have problem with accessing SSH to Openshift.
I still can push code to Openshift via Git. But when trying to SSH to Openshift, the server denied with error "no supported authentication methods available (server sent: public key, gssapi-keyex, gssapi-with-mic". I'm using Windows 7.
Do you know what's the problem and how to solve it?
This answer is for Windows users.
Who used puttygen.exe to generate your RSA keys.
And you added the PUBLIC key to your Openshift account, via the web console.
And you can PUTTY in OK, but not SSH from GIT-BASH (or cannot git clone via SSH).
One common reason is the key generated by puttygen.exe, is a PUTTY specific file.
You can convert this to OPENSSH format, from within the puttygen.exe program.
(Menu > Conversions > Export OpenSSH Key)
Save it to a new file, in the same directory as your original PUTTY generated PUBLIC/PRIVATE key pair.
Reference this OPENSSH key from your ~/.ssh/config file.
See step 4 here, if you dont have this config file.
https://confluence.atlassian.com/display/BITBUCKET/Set+up+SSH+for+Git
Test by opening GIT-BASH, and trying your specific "ssh user#yourhost.rhcloud.com" (without the quotes, and where user and your host are specific to your account). If that works, you should be good to go...
Short version:
remove the leading "ssh " from the ssh url provided by the OpenShift web console.
I was frustrated when this happened to me. I tried all things mentioned above. At last I gave up in windows 7 and opened my Ubuntu virtual machine. Then I noticed the leading "ssh " in the url.
I'm also using Windows 7 and I had the same problem.
I created ssh keys with rhc tool and then public key for putty (id_rsa.ppk). Their permissions (GIT Bash, "ls -l" command) were 700 (but I couldn't connect):
-rwx------+ 1 User123 None 1706 Mar 4 19:46 id_rsa
-rwx------+ 1 User123 None 1464 Mar 4 19:52 id_rsa.ppk
-rwx------+ 1 User123 None 394 Mar 4 19:46 id_rsa.pub
So I changed the permission (with chmod command) to 755:
-rwxr-xr-x+ 1 User123 None 1706 Mar 4 19:46 id_rsa
-rwxr-xr-x+ 1 User123 None 1464 Mar 4 19:52 id_rsa.ppk
-rwxr-xr-x+ 1 User123 None 394 Mar 4 19:46 id_rsa.pub
And then both git-bash and ssh from putty started working. I know that these are not the most secure permissions, but for me it's enough. It may also help to run git/putty as administrator, but I didn't try that.
You may want to reach look into what the OpenShift forums provided on no supported authentication methods available (server sent: public key, gssapi-keyex, gssapi-with-mic. The Red Hat Customer Portal also has a good article on this error, however you will need a Silver plan to see this article.
Typically, on linux this error is caused because the key you are using does not have the right permissions. In short your .ssh/id_rsa key's permissions are too lax (they should be 600).
Note that other people have seen similar issues related to this error with OpenShift so permissions may not be the root cause of your particular issue.
go to preference in eclipse and in ssh key menu, click KEY MANAGEMENT and ther is a rsa key tab click that and copy your public key and click the button save as private key... then go to your open shift application and paste your public key and work on it... i hope it working
Reference
TOOLS
We will need two tools to work with :
PuTTY
PuTTYgen
METHOD
Step 1: Generate a brand-new SSH-2 RSA key.
Step 2: Add the generated key in the host (for ex. in settings >> keys on Openshift) that requires the authentication.
Step 3: Export this key from PuTTYgen Conversions >> Export OpenSSH Key and save it on your file-system
Step 4: Add/Edit your ~/.ssh/config file
// ~/.ssh/config
Host HOST_NAME // for example - https://my-domain.rhcloud.com
Port PORT_NUMBER // ideally 22
IdentityFile PATH/TO/FILE/CREATED/IN/STEP/3 // the path to where the key was exported
Example Configuration of ~/.ssh/config
Host cool-websites.rhcloud.com
Port 22
IdentityFile C:/Users/cool_dude/Desktop/rhcloud
Good Luck.
You need to create keys in Puttygen - https://the.earth.li/~sgtatham/putty/latest/x86/puttygen.exe. Format - SSH-2 RSA.
This keys have correct format. It works.
This answer is for Linux users. If you have the same problem, disabling GSSAPI may help.
Edit your ~/.ssh/config (user) or /etc/ssh/ssh_config (system-wide) file to set GSSAPIAuthentication no.
Source: Speed up SSH logon by disabling GSSAPIAuthentication
Connecting the SSH servers can sometimes be delayed when the client
and server try to sort out if they should be using GSSAPI to
authenticate.