- Question: Q: Access to .ssh/known_hosts
- Что записано в файле .ssh/known_hosts
- Имя сервера
- Ассиметричный алгоритм
- Публичный ключ
- Mac OS X Remove SSH Known Host
- Test it
- Getting help
- Mac, known_hosts location not default?
- 2 Answers 2
- SSH Keys, Part 1: Host Verification
- Asymmetric Key Encryption
- OK, how does this work with SSH?
- Fingerprints
- Making a list, checking it twice…
- Don’t copy these keys
- Locking down even more
- Recap
Question: Q: Access to .ssh/known_hosts
I’m trying to edit or remove a known_hosts file in my .ssh folder, but have no idea how I can find that folder.
Someone suggested a command I could use in Terminal, but when I tried, I got the message that I didn’t have the permission. Repairing permissions didn’t help.
The reason I need to do this, i sthat I get the following message when trying to log in via SSH to a shared server:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
The RSA host key for ********.com has changed,
and the key for the corresponding IP address **************
is unknown. This could either mean that
DNS SPOOFING is happening or the IP address for the host
and its host key have changed at the same time.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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 RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
**********************************.
Please contact your system administrator.
Add correct host key in /Users/ *********/.ssh/known_hosts to get rid of this message.
Offending key in /Users/ *******/.ssh/known_hosts:1
RSA host key for ************** has changed and you have requested strict checking.
Host key verification failed.
Any advice would be highly appreciated.
8-core Mac Pro 2.8ghz, Mac OS X (10.5.6), 8x1g RAM
Источник
Что записано в файле .ssh/known_hosts
Каждый раз, когда мы подключаемся по протоколу ssh к серверу, ssh клиент проверяет совпадает ли публичный ключ для этого сервера с тем, который был прошлый раз (по крайней мере так рекомендует делать стандарт ssh). В OpenSSH список известных ключей серверов хранится в файле known_hosts. Под катом коротко о том, что и как конкретно там хранится.
Все эксперименты проводились на Linux (Debian/Mint/Ubuntu). За расположение и содержание файлов в других ОС не ручаюсь.
Подключаясь первый раз к ssh серверу, мы видим примерно такое сообщение:
The authenticity of host ‘192.168.0.2 (192.168.0.2)’ can’t be established.
RSA key fingerprint is SHA256:kd9mRkEGLo+RBBNpxKp7mInocF3/Yl/0fXRsGJ2JfYg.
Are you sure you want to continue connecting (yes/no)?
/.ssh/known_hosts добавится такая строка:
|1|CuXixZ+EWfgz40wpkMugPHPalyk=|KNoVhur7z5NAZmNndtwWq0kN1SQ= ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCeiF4OOOUhWvOYrh/e4q91+iz+i9S0s3M2LPq+GAhRlhKt5vKyEVd6x6m26cc98Y+SQXnCB9GWeVYk8jlFHEXnY4YWeWLDwXIhHBJYt5yz3j5Wkg95x+mPvO9FLSBk/Al2GbH5q6F+hZIlLmO6ciISmX4TtcG1sw4SwoTADrrhdM0OJd+c5CU8iqCbc6PznYbLZXCvqPZTWeSbTLUcUu1Ti+7xGwT8DF+tIyLFcU+zxd0QnwJIbNvewkHs0LsMOWFVPz/Nd0XiVXimX+ugCDBZ/4q8NUwH9SGzCMAvnnr+D1I8X2vhSuRsTsQXL5P3vf8elDxPdDrMJzNtlBCbLWzV
Тут через пробел записаны три элемента: хэш от имени сервера, название используемого ассиметричного алгоритма и публичный ключ сервера. Разберём их по очереди.
Имя сервера
На самом деле тут может быть записано и имя хоста в открытом виде или маска, задающая множество допустимых имён. Но у меня по умолчанию сохраняется хэшированое имя. Запись разделена на 3 части символом «|». Первая часть — алгоритм хэширования. «1» соответствует HMAC-SHA1 (других не видел). Вторая часть — соль (ключ для HMAC). Третья часть — собственно хэш (вывод HMAC).
Ассиметричный алгоритм
В RFC-4253 перечислены 4 ассиметричных алгоритма: ssh-dss (по стандарту обязательный, но считается слабым и начиная с OpenSSH7.0 выключен по-умолчанию), ssh-rsa (рекомендуемый), pgp-sign-rsa (опциональный), pgp-sign-dss (опциональный). По умолчанию в Linux генерируются ключи первых двух видов и для не упомянутых в RFC алгоритмов на эллиптических кривых. Предпочтение отдаётся последним, однако клиент может выбрать алгоритм опцией HostKeyAlgorithms.
ssh root@192.168.0.2 -o HostKeyAlgorithms=ssh-rsa
ssh root@192.168.0.2 -o HostKeyAlgorithms=ssh-rsa -o FingerprintHash=md5
Публичный ключ
Публичный ключ в known_hosts совпадает с тем, который записан в файле /etc/ssh/ssh_host_rsa_key.pub на сервере (вместо rsa подставить название используемого алгоритма). Если снять Base64 кодирование, то внутри будет ещё раз название алгоритма и собственно компоненты ключа.
Видно, что идут 4 байта, в которые записана длина поля, потом само поле и т.д. Первое поле — название алгоритма, остальные зависят от конкретного алгоритма. В приведённом выше ключе 3 поля:
Источник
Mac OS X Remove SSH Known Host
But I’m getting an error which read as follows:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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 RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
5c:9b:16:56:a6:cd:11:10:3a:cd:1b:a2:91:cd:e5:1c.
Please contact your system administrator.
Add correct host key in /Users/user/.ssh/known_hosts to get rid of this message.
Offending key in /Users/user/.ssh/known_hosts:1
RSA host key for server1.example.com has changed and you have requested strict checking.
Host key verification failed.
How do I fix this problem under Mac OX X?
You need to run the following command to get rid of this problem. Open the terminal application and then type the following command on your macOS Unix system:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Fig.01: Removing /Users/user/.ssh/known_hosts file
/.ssh/known_hosts file which contains a list of host keys for all hosts the user has logged into that are not already in the systemwide list of known host keys.
Test it
Now you can connect to remote host with ssh or sftp or scp command:
Use -p Port to connect to on the remote host using given Port. This can be specified on a per-host basis in the configuration file such as
Getting help
The ssh-keygen command generates, manages and converts authentication keys for ssh. The ssh-keygen can create keys for use by SSH protocol version 2 and do other stuff for use. Hence, read the man page by typing the following commands:
man ssh-keygen
man ssh
man sshd
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Mac, known_hosts location not default?
I developped a software in Java for some customers and my soft needs to access the known_hosts file since it’s using JSCH commands. I tested it on my computer running on Linux and several Mac machines and it works fine. But I have an issue with one customer :
My soft can’t access the known_hosts file. I know that its default location (and mostly always) is : /Users/username/.ssh/known_hosts
when I asked him to type in the terminal nano /users/username/.ssh/known_hosts it created a new file instead of opening one. So my question is :
Is it possible for the known_hosts file to be somewhere else ? If so, how do you find it’s location .
NB : I have no remote access to the Mac (like with TeamViewer or things like that) since it is not connected to internet.
2 Answers 2
Since the default location may be overridden for a particular host through entries in
/.ssh/config , you need to determine the file for a particular target.
MacOS uses a recent enough version of openSSH that you should be able to use the -G option to determine configuration for a particular connection:
Rather than editing a file with nano or any other text editor, the correct way to create a known_hosts file would be to make a successful connection using SSH, and answer the SSH client’s challenge about correctness of the host key.
If you want to impress your client with your sensitivity to security requirements he may not even know he has, then rather than asking him to type a pathname, send him an ssh command line along with the intended key for him to verify, so that he can confidently say «Yes, this is the right host.» Let SSH do its job.
Источник
SSH Keys, Part 1: Host Verification
So far in this series of posts on ssh on macOS:
In the earlier post, we talked about basic ssh setup and use.
We briefly mentioned ssh is securely encrypted. We encountered a cryptic prompt (pun intended) when connecting to the machine for the first time:
At that point we just wanted to connect and ignored this prompt. However, this is a crucial part of the ssh infrastructure and understanding it will help you use ssh securely and to its full potential.
Asymmetric Key Encryption
This is what ssh uses to encrypt traffic. It uses a two part encryption key to encode the data transmitted. The first part of the key is private and kept securely on the ssh host (the remote computer you want to log in to) and the second part is public and shared to the users who want to connect.
Data encrypted with one key can be decrypted with the other and vice versa. This way data can be kept secure between the client and the host.
When you connect for the first the remote host will send its public key to your computer. This is convenient, but opens the chance for malicious computer to impersonate the host you actually want to reach and set itself as a ‘man in the middle’, passing data back and forth and decrypting it in between.
OK, how does this work with SSH?
The key fingerprint the system displays on first connection is a ‘hash’ of the public key.
Using this fingerprint, you can verify that the DNS address or IP you are connecting to, is really the computer you want to connect to. To verify, you would need obtain the fingerprint from the host though some other means and compare.
On macOS the host keys are stored in /private/etc/ssh/ along with some other files required for ssh configuration. The key filenames have the format ssh_host_ABC_key where ABC is the key encryption type. On my Sierra Mac there are keys for dsa , ecdsa , rsa and ed25519 . There two files for every type, the private key (no file extension) and the public key, with the .pub extension.
ECDSA (Elliptic Curve Digital Signature Algorithm – Wikipedia) is the default type of key ssh uses on macOS. The other keys are present for compatibility with other platforms and older versions of macOS/OS X. Usually the client and the server will negotiate which keys to use from the available options.
These keys are generated on every host, when the ssh server process starts for the first time. These keys are unique to this host.
When you look closely at the key files, you will see that the private keys can only be read by root , no other users. Private keys are like really important passwords and have to be kept safe. If someone can obtain both keys, they can impersonate this host.
The public keys are the part that are meant to be shared and can be read by any user.
Fingerprints
You can generate the fingerprint from a public key with the ssh-keygen command:
ECDSA (Elliptic Curve Digital Signature Algorithm – Wikipedia) is the default type of key ssh uses on macOS. The other keys are present for compatibility with other platforms and older versions of macOS/OS X.
A security conscious admin would go to the remote machine in question (or ask another user/admin who has access to the server/machine) and generate the fingerprint. Then go back to the Mac from where he wants to remotely connect with ssh and compare the fingerprint shown on first connection:
Since the key and the fingerprint are unique, you can be sure you are talking to the correct remote machine and there is no other malicious computer impersonating the remote machine on the network.
Making a list, checking it twice…
Once you confirm the prompt to connect to a new host, its public key will be added to the file
/.ssh/known_hosts . This file will contain one line per remote host. Each line will contain the hostname, the IP address, the key type and the public key data itself. You can view the file in a text editor, or you can use the ssh-keygen tool to search this file for a particular host:
Once the key is stored in your known_hosts file, ssh can detect if the public key presented by a remote ssh host changes and warn you. The warning is not subtle:
In most cases this means that IP addresses have changed. In the worst case, someone is maliciously attempting to impersonate an ssh host in your network, probably in an attempt to gather login information.
As administrators, there is another common reason for this warning. When you re-install or re-image a client Mac, it will generate new ssh keys. So every time you re-image and re-connect to a test machine, your Mac will compare the old keys in known_hosts with a newly generated, different key on the freshly imaged Mac and bring up this warning.
You can remove the old keys from the
/.ssh/known_hosts file directly in a text editor or use the ssh-keygen command to remove out of date keys:
The hostname is used to identify hosts and keys in this file. If you connect to the client with different hostnames, DNS aliases, or you alternate between the ‘proper’ DNS name mac.example.com , partial DNS name mac , the Bonjour name (i.e. Mac.local ), or the IP address, you may end up with multiple entries for the same host in known_hosts . Usually this is not a problem, but is useful to know when cleaning out stale keys.
If you have the public key for a host, you can pre-add it to your known_hosts file. The format you have to use is
Don’t copy these keys
If you use ‘Golden Master’ imaging on macOS (you really shouldn’t, for several reasons, this being one of them), you might inadvertently copy the host ssh keys from your Golden Master to all the other clients. While this does not break how ssh works, it will undermine some of its security. You can simply delete the existing keys on the Golden Master and new keys will be created on the clients when needed.
Remember there are other files in /private/etc/ssh/ that are required for ssh to work which you should not delete.
Locking down even more
You can increase or decrease the host key security with the StrictHostKeyChecking setting in the
/.ssh/config file for a particular user or the /private/etc/ssh/ssh_config` file for all users on a system.
The default value is ask which means that ssh will ask what to do with an unknown key from a host. This is the behavior described above.
You can increase security by changing this setting to yes which means ssh will refuse to connect to a host which is not listed in
With this setting you will have to manually obtain a host’s public key and add it to your known_hosts file.
You can also set StrictHostKeyChecking to no . With this setting, unknown hosts will automatically be added to the known_hosts file and changed public keys will automatically be replaced. This could be useful in a very dynamic, low-security environment (i.e. a classroom where Macs are re-imaged frequently). However, it does undermine the security of ssh and you will not notice any attempts to insert malicious hosts. In general you should not use this setting.
Recap
- the ssh host (remote machine) has a set of encryption keys in /private/etc/ssh/
- the public key is sent to the client. A fingerprint of the public key is presented with a prompt wether you should connect. You should use the public key fingerprint to verify the host’s authenticity on first connect.
- generate the fingerprint from the public key on the host with ssh-keygen -l -f keyfile.pub
- the public keys of approved hosts are stored in
/.ssh/known_hosts
When you verify the fingerprint of the host, you can be sure of its identity. The host however, cannot verify a client’s identity in this setup. This is why you still have to enter a password every time you log in with ssh remotely.
We will discuss how to improve on that in the next post : SSH Keys, Part 2: Client Verification
Источник