Known hosts ssh windows

Содержание

Введение
Check version
Установка из Windows Settings
Установка из PowerShell
Запуск
Подключение к серверу
Конфигурационные файлы
Удалить через Settings
Удалить из PowerShell
Похожие статьи

Введение

Про использование SSH в Linux вы можете прочитать в статье

«ssh in Linux»

Проверить версию

В

PowerShell

вы можете использовать следующую команду

ssh -V

Установка OpenSSH через Windows Settings

OpenSSH сервер и клиент могут быть установлены через Windows Settings
в Windows Server 2019 и Windows 10.

Чтобы выполнить установку обоих компонентов OpenSSH:

Settings Apps Apps & Features Optional Features.

Scan the list to see if the OpenSSH is already installed. If not, at the top of the page, select Add a feature, then:
Find OpenSSH Client, then click Install
Find OpenSSH Server, then click Install

После завершения установки вернитесь в

Apps Apps & Features and Optional Features

И вы увидите OpenSSH в списке.

Установка OpenSSH через PowerShell

To install OpenSSH using PowerShell, run PowerShell as an Administrator.

To make sure that OpenSSH is available, run the following cmdlet:

Get-WindowsCapability -Online | Where-Object Name -like ‘OpenSSH*’

This should return the following output if neither are already installed:

Name : OpenSSH.Client~~~~0.0.1.0
State : NotPresent

Name : OpenSSH.Server~~~~0.0.1.0
State : NotPresent

Then, install the server or client components as needed:

# Install the OpenSSH Client

Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

# Install the OpenSSH Server

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

Both of these should return the following output:

Path :
Online : True
RestartNeeded : False

Start and configure OpenSSH Server

To start and configure OpenSSH Server for initial use, open PowerShell as an administrator, then run the following commands to start the sshd service:

# Start the sshd service
Start-Service sshd

# OPTIONAL but recommended:
Set-Service -Name sshd -StartupType ‘Automatic’

# Confirm the Firewall rule is configured. It should be created automatically by setup. Run the following to verify
if (!(Get-NetFirewallRule -Name «OpenSSH-Server-In-TCP» -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) {
Write-Output «Firewall Rule ‘OpenSSH-Server-In-TCP’ does not exist, creating it…»
New-NetFirewallRule -Name ‘OpenSSH-Server-In-TCP’ -DisplayName ‘OpenSSH Server (sshd)’ -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
} else {
Write-Output «Firewall rule ‘OpenSSH-Server-In-TCP’ has been created and exists.»
}

Connect to OpenSSH Server

Once installed, you can connect to OpenSSH Server from a Windows 10 or Windows Server 2019 device with the OpenSSH client
installed using PowerShell as follows. Be sure to run PowerShell as an administrator:

ssh username@servername

Once connected, you get a message similar to the following:

The authenticity of host ‘servername (10.00.00.001)’ can’t be established.
ECDSA key fingerprint is SHA256:(<a large string>).
Are you sure you want to continue connecting (yes/no)?

Selecting yes adds that server to the list of known SSH hosts on your Windows client.

You are prompted for the password at this point. As a security precaution, your password will not be displayed as you type.

Once connected, you will see the Windows command shell prompt:

domain\username@SERVERNAME C:\Users\username>

OpenSSH configuration files

OpenSSH has configuration files for both server and client settings. OpenSSH is open-source and is added to Windows Server and Windows Client operating systems, starting with Windows Server 2019 and Windows 10 (build 1809). As a result, documentation for OpenSSH configuration files is not repeated here. Client configuration files and can be found on the ssh_config manual page and for OpenSSH Server configuration files can be found on the sshd_config manual page. Further Windows-specific OpenSSH Server configuration is detailed in OpenSSH Server configuration for Windows.

In Windows, the OpenSSH Client (ssh) reads configuration data from a configuration file in the following order:

  1. By launching ssh.exe with the -F parameter, specifying a path to a configuration file and an entry name from that file.
  2. A user’s configuration file at %userprofile%\.ssh\config.
  3. The system-wide configuration file at %programdata%\ssh\ssh_config.

Open SSH Server (sshd) reads configuration data from %programdata%\ssh\sshd_config by default, or a different configuration file may be specified by launching sshd.exe with the -f parameter. If the file is absent, sshd generates one with the default configuration when the service is started.

Uninstall OpenSSH using Windows Settings

To uninstall OpenSSH using Windows Settings:

Open Settings, then go to Apps
Apps & Features.

Go to Optional Features.

In the list, select OpenSSH Client or OpenSSH Server.

Select Uninstall.

Uninstall OpenSSH using PowerShell

To uninstall the OpenSSH components using PowerShell, use the following commands:

# Uninstall the OpenSSH Client
Remove-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

# Uninstall the OpenSSH Server
Remove-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

You may need to restart Windows afterwards if the service was in use at the time it was uninstalled.

РЕКЛАМА хостинга Beget, которым я пользуюсь более десяти лет

Изображение баннера

Конец рекламы хостинга Beget, который я всем рекомендую

Check certificate with certutil

Certutil -verify -urlfetch cert_filename

WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!

При попытке подключения к, казалось бы, известному хосту можно получить ошибку

ssh user@host

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
The ED25519 host key for host has changed,
and the key for the corresponding IP address 12.123.123.123
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 a host key has just been changed.
The fingerprint for the ED25519 key sent by the remote host is
SHA256:pEhSoIzdqkEiaBE/pBc4ttgVJtohNCZDcoqNSuNDa94.
Please contact your system administrator.
Add correct host key in C:\\Users\\Andrei/.ssh/known_hosts to get rid of this message.
Offending ED25519 key in C:\\Users\\Andrei/.ssh/known_hosts:8
ED25519 host key for host has changed and you have requested strict checking.
Host key verification failed.

Из строки

Offending ED25519 key in C:\\Users\\Andrei/.ssh/known_hosts:8

Можно понять, что проблема вызвана третьей строкой файла /home/user/.ssh/known_hosts

Если вы уверены в надёжности хоста к которому подключаетесь, то можете просто удалить эту строку и подключиться снова

Например из

Git Bash

sed -i 8d /c/Users/Andrei/.ssh/known_hosts

sed -i 8d /c/Users/$USERNAME/.ssh/known_hosts

Другие статьи про SSH

Как подключиться к серверу по SSH из Windows
Автоматическая SSH-авторизация по ключу
Настройка подключения при помощи VS Code
Что такое SSH

Автор статьи: Андрей Олегович

Похожие статьи

Windows
Windows Firewall
pstools
Удалённый рабочий стол
SSH в Linux

About

Known Hosts File is a client file that:

  • lists all known remote host via their public key

Format

hostname algo public_key
hostname,ip algo public_key

where:

Add a host

ssh-keyscan server-ip 2>/dev/null >> ~/.ssh/known_hosts

Example

192.168.1.20 ecdsa-sha2-nistp256 public_key
gerardnico.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABA............

# Comments allowed at start of line
closenet,...,192.0.2.53 1024 37 159...93 closenet.example.net
cvs.example.net,192.0.2.10 ssh-rsa AAAA1234.....=
# A hashed hostname
|1|JfKTdBh7rNbXkVAQCRp4OQoPfmI=|USECr3SWf1JUPsms5AqfD5QfxkM= ssh-rsa AAAA1234.....=
# A revoked key
@revoked * ssh-rsa AAAAB5W...
# A CA key, accepted for any host in *.mydomain.com or *.mydomain.org
@cert-authority *.mydomain.org,*.mydomain.com ssh-rsa AAAAB5W...

Windows

Ie:

  • User: C:\Users\login\.ssh\known_hosts

  • System: C:\Windows\System32\config\systemprofile\.ssh\known_hosts

Linux

For OpenSSH

ssh -G host | grep hostsfile
# example: ssh -G [email protected] | grep hostsfile
globalknownhostsfile /etc/ssh/ssh_known_hosts /etc/ssh/ssh_known_hosts2
userknownhostsfile ~/.ssh/known_hosts ~/.ssh/known_hosts2

Implementation

Documentation / Reference

The quick:

Open a Windows File Explorer and type:

%USERPROFILE%\.ssh

This brings you to the .ssh directory that has the known_hosts file in it.

Open the known_host file delete the key that is causing you problems.

Source: https://superuser.com/questions/311886/where-is-the-known-hosts-file-for-openssh-for-windows/318749#318749?newreg=7793b32b40354caeab6d06206035d9f0


A bit more bloggy:

Due to the nature of the work I do, I often use the same IP address for the systems I install, this makes it easier for me to manage them. Unfortunately, this means that the ‘duplicate’ Linux systems raise security flags when I attempt to ssh into a new machine.

In order to solve this, I either use PuTTY, or, more often than not, I simply delete the offending SSH key so I can use Powershell.

The easiest way to delete the keys are to:

  1. Open Windows File Explorer
  2. Go to this location: %USERPROFILE%\.ssh
  3. Open the known_hosts file
  4. delete the key of the IP that is causing you issues

Hope this helps someone

Время на прочтение5 мин

Количество просмотров68K

Каждый раз, когда мы подключаемся по протоколу 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

Тут через пробел записаны три элемента: хэш от имени сервера, название используемого ассиметричного алгоритма и публичный ключ сервера. Разберём их по очереди.

А если почитать инструкцию

На самом деле согласно мануалу к Убунте там могут быть ещё 2 поля, так же отделённые пробелами:

  • в начале строки может находиться пометка «@cert-authority» или “@revoked”, означающие, соответственно, что в этой строке записан публичный ключ ЦА или что этот ключ был отозван и не может быть использован.
  • в конце строки может быть произвольный комментарий

Имя сервера

В примере хэш от имени сервера (хоста) выглядит так:

|1|CuXixZ+EWfgz40wpkMugPHPalyk=|KNoVhur7z5NAZmNndtwWq0kN1SQ=

На самом деле тут может быть записано и имя хоста в открытом виде или маска, задающая множество допустимых имён. Но у меня по умолчанию сохраняется хэшированое имя. Запись разделена на 3 части символом «|». Первая часть — алгоритм хэширования. «1» соответствует HMAC-SHA1 (других не видел). Вторая часть — соль (ключ для HMAC). Третья часть — собственно хэш (вывод HMAC).

Проверяем

from base64 import b64decode
import hmac

salt = b64decode("CuXixZ+EWfgz40wpkMugPHPalyk=")
host = b'192.168.0.2'
hash = hmac.HMAC(salt, host, 'sha1').digest()
print(b64encode(hash).decode())

> ‘KNoVhur7z5NAZmNndtwWq0kN1SQ=’

Ассиметричный алгоритм

В RFC-4253 перечислены 4 ассиметричных алгоритма: ssh-dss (по стандарту обязательный, но считается слабым и начиная с OpenSSH7.0 выключен по-умолчанию), ssh-rsa (рекомендуемый), pgp-sign-rsa (опциональный), pgp-sign-dss (опциональный). По умолчанию в Linux генерируются ключи первых двух видов и для не упомянутых в RFC алгоритмов на эллиптических кривых. Предпочтение отдаётся последним, однако клиент может выбрать алгоритм опцией HostKeyAlgorithms.

Как проверить нужный (не по-умолчанию) отпечаток ключа

Это может быть полезно если, например, при первом заходе на сервер вы хотите проверить отпечаток ключа, а знаете только отпечаток ключа ssh-rsa. Тогда можно подключиться такой командой:

ssh root@192.168.0.2 -o HostKeyAlgorithms=ssh-rsa

Если нужно задать ещё и алгоритм хэширования ключа, то можно использовать опцию FingerprintHash. Например, если известен только md5 от 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 кодирование, то внутри будет ещё раз название алгоритма и собственно компоненты ключа.

А чего бы и не снять Base64

b'\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x03\x01\x00\x01\x00\x00\x01\x01\x00\x9e\x88^\x0e8\xe5!Z\xf3\x98\xae\x1f\xde\xe2\xafu\xfa,\xfe\x8b\xd4\xb4\xb3s6,\xfa\xbe\x18\x08Q\x96\x12\xad\xe6\xf2\xb2\x11Wz\xc7\xa9\xb6\xe9\xc7=\xf1\x8f\x92Ay\xc2\x07\xd1\x96yV$\xf29E\x1cE\xe7c\x86\x16yb\xc3\xc1r!\x1c\x12X\xb7\x9c\xb3\xde>V\x92\x0fy\xc7\xe9\x8f\xbc\xefE- d\xfc\tv\x19\xb1\xf9\xab\xa1~\x85\x92%.c\xbar"\x12\x99~\x13\xb5\xc1\xb5\xb3\x0e\x12\xc2\x84\xc0\x0e\xba\xe1t\xcd\x0e%\xdf\x9c\xe4%<\x8a\xa0\x9bs\xa3\xf3\x9d\x86\xcbep\xaf\xa8\xf6SY\xe4\x9bL\xb5\x1cR\xedS\x8b\xee\xf1\x1b\x04\xfc\x0c_\xad#"\xc5qO\xb3\xc5\xdd\x10\x9f\x02Hl\xdb\xde\xc2A\xec\xd0\xbb\x0c9aU??\xcdwE\xe2Ux\xa6_\xeb\xa0\x080Y\xff\x8a\xbc5L\x07\xf5!\xb3\x08\xc0/\x9ez\xfe\x0fR<_k\xe1J\xe4lN\xc4\x17/\x93\xf7\xbd\xff\x1e\x94<Ot:\xcc\'3m\x94\x10\x9b-l\xd5'

Видно, что идут 4 байта, в которые записана длина поля, потом само поле и т.д. Первое поле — название алгоритма, остальные зависят от конкретного алгоритма. В приведённом выше ключе 3 поля:

b'ssh-rsa' - название 
b'\x01\x00\x01' - публичная экспонента
b'\x00\x9e\x88^\x0e8\xe5!Z\xf3\x98\xae\x1f\xde\xe2\xafu\xfa,\xfe\x8b\xd4\xb4\xb3s6,\xfa\xbe\x18\x08Q\x96\x12\xad\xe6\xf2\xb2\x11Wz\xc7\xa9\xb6\xe9\xc7=\xf1\x8f\x92Ay\xc2\x07\xd1\x96yV$\xf29E\x1cE\xe7c\x86\x16yb\xc3\xc1r!\x1c\x12X\xb7\x9c\xb3\xde>V\x92\x0fy\xc7\xe9\x8f\xbc\xefE- d\xfc\tv\x19\xb1\xf9\xab\xa1~\x85\x92%.c\xbar"\x12\x99~\x13\xb5\xc1\xb5\xb3\x0e\x12\xc2\x84\xc0\x0e\xba\xe1t\xcd\x0e%\xdf\x9c\xe4%<\x8a\xa0\x9bs\xa3\xf3\x9d\x86\xcbep\xaf\xa8\xf6SY\xe4\x9bL\xb5\x1cR\xedS\x8b\xee\xf1\x1b\x04\xfc\x0c_\xad#"\xc5qO\xb3\xc5\xdd\x10\x9f\x02Hl\xdb\xde\xc2A\xec\xd0\xbb\x0c9aU??\xcdwE\xe2Ux\xa6_\xeb\xa0\x080Y\xff\x8a\xbc5L\x07\xf5!\xb3\x08\xc0/\x9ez\xfe\x0fR<_k\xe1J\xe4lN\xc4\x17/\x93\xf7\xbd\xff\x1e\x94<Ot:\xcc\'3m\x94\x10\x9b-l\xd5' - модуль N (0x101 * 8 = 2048 бит)

Отпечаток ключа (Fingerprint)

Отпечаток ключа, который предлагается сверить при первом подключении — это соответствующий хэш (в примере — SHA256) от публичного ключа из прошлого пункта и из /etc/ssh/ssh_host_rsa_key.pub, закодированный в base64 для хэш функций семейства SHA или в hex для MD5.

Считаем

from hashlib import sha256
from base64 import b64decode, b64encode
pub_key_bin = b64decode("AAAAB3NzaC1yc2EAAAADAQABAAABAQCeiF4OOOUhWvOYrh/e4q91+iz+i9S0s3M2LPq+GAhRlhKt5vKyEVd6x6m26cc98Y+SQXnCB9GWeVYk8jlFHEXnY4YWeWLDwXIhHBJYt5yz3j5Wkg95x+mPvO9FLSBk/Al2GbH5q6F+hZIlLmO6ciISmX4TtcG1sw4SwoTADrrhdM0OJd+c5CU8iqCbc6PznYbLZXCvqPZTWeSbTLUcUu1Ti+7xGwT8DF+tIyLFcU+zxd0QnwJIbNvewkHs0LsMOWFVPz/Nd0XiVXimX+ugCDBZ/4q8NUwH9SGzCMAvnnr+D1I8X2vhSuRsTsQXL5P3vf8elDxPdDrMJzNtlBCbLWzV")
hash = sha256(pub_key_bin).digest()
fingerprint = b64encode(hash)
print(fingerprint)

> b'kd9mRkEGLo+RBBNpxKp7mInocF3/Yl/0fXRsGJ2JfYg='

Видим, что хэш и правда совпадает с отпечатком, показанным при первом подключении (цитата в начале статьи), с точностью до символа «=» в конце.

Тут небольшая программка для поиска хостов в файле known_hosts, появившаяся в процессе экспериментов.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как выключить безопасность windows 10 на время
  • Как отключить перо в windows 10 горячие клавиши
  • Команда перезагрузки windows 10 в безопасный режим
  • Faststone capture не пишет звук windows 10
  • Повтор экрана на ноутбуке windows с айфона