SSH-Agent and OpenSSH are tools in Windows that can be used to authenticate to remote Git repositories, such as GitLab, GitHub, Azure DevOps, etc. Once set up as a service that stores your various SSH keys, this can facilitate authentication without entering a password each time, removing the irritation of entering a password every time you wish to push/pull/etc. from a Git repository.
Prerequisites
- The OpenSSH Client optional service must be enabled on your machine, and OpenSSH must be added to your PATH environment variable. You can read how to do that here.
- A remote Git repository that you wish to access. We will use a GitLab repository for this article; however, the process will be similar for other Git management providers.
- Git must be installed on your machine.
How to Install the SSH-Agent Service in Windows
Using an elevated PowerShell window (run as admin), execute the following command to install the SSH-Agent service and configure it to start automatically when you log into your machine:
Get-Service ssh-agent | Set-Service -StartupType Automatic -PassThru | Start-Service
To avoid needing to restart your system to get the service running for the first time, execute this command:
start-ssh-agent.cmd
Setting up an SSH Key Pair to Access a Git Remote Provider
Using a command line tool such as Bash or PowerShell, you should be able to follow these steps to create a local SSH key pair. For our example, we will create an ED25519 key, but you can create other keys such as an RSA.
Create a new SSH ED25519 key, giving it a useful comment:
ssh-keygen -t ed25519 -C "Git-Demo"
By default, the file will be stored in your local user’s SSH repository in Windows. You can choose another storage location if you wish or rename the file by entering a new file path to save the key. Leave it blank to stick with the default.
In our example, we rename the file from the default id_ed25519 to id_ed25519_git_demo:
You can also add a password if you like or leave this blank:
You will then be shown the key’s randomart image to confirm creation:
Copy the contents of the public key to your clipboard. You can read this key with the following command:
cat path\to\ssh\key.pub
For example, our code is likely:
cat C:\Users\chastie/.ssh\id_ed25519_git_demo.pub
Note: We access the public key with the .pub suffix.
A sample is shown here. You can then select this and copy it with a right-click of your mouse:
In GitLab (or the appropriate location of your Git remote repository), you can now add this public key to your user profile. In GitLab, you can do this by adding it under the SSH Keys section of your user settings:
Test that you can connect to the repository when using the SSH private key directly with this command:
ssh -i path/to/ssh/private/key -T git@host
For example, our command could be:
ssh -i C:\Users\chastie/.ssh\id_ed25519_git_demo -T git@gitlab.mycompany.com or ssh -i C:\Users\chastie/.ssh\id_ed25519_git_demo -T git@github.com
We have now established an SSH key pair that can authenticate to our Git remote provider. It remains to set this up in the SSH-Agent service to automatically provide access. We can demonstrate the issue by attempting the same connection, but without specifically naming the SSH key, with the command below:
ssh -T git@host
As we can see, if we execute this command without specifying an SSH key, we are prompted for a password:
Adding the SSH Key to the SSH-Agent Service
Our goal is to be able to connect to a Git repository without entering a password. At this stage, we have a working SSH key pair and the SSH-Agent service installed and running.
Execute the following command to add your SSH key to your SSH-Agent service:
ssh-add path/to/ssh/private/key
For our example, our command could be:
ssh-add C:\Users\chastie/.ssh\id_ed25519_git_demo
We can now test our connection to our Git remote provider without specifying a key and connect successfully:
ssh -T git@host
Configuring Git to Leverage the Windows SSH-Agent
In an elevated console (run as admin), execute the following command to modify your existing Git configuration to leverage the windows OpenSSH service as the core SSH command:
git config --global core.sshCommand C:/Windows/System32/OpenSSH/ssh.exe
Congratulations! You have now set up your environment to automatically authenticate to your Git remote provider through an SSH key pair, without using passwords. If you wish to facilitate access to any other Git remote providers, simply follow the same steps to generate a key pair ( as outlined above) and add it to your existing SSH-Agent service.
Introduction
Git connects to remotes by default via HTTPS, which requires you to enter your login and password every time you run a command like Git pull or git push, using the SSH protocol. You may connect to servers and authenticate to access their services. The three services listed allow Git to connect through SSH rather than HTTPS. Using public-key encryption eliminates the need to type a login and password for each Git command.
Make sure a Git is installed
Make sure Git is installed before you start. Run the following command in your Windows terminal to see if Git is installed on your computer:
git --version
Enter fullscreen mode
Exit fullscreen mode
Install Git
To install Git, you can download the latest version from the official Git website. You can also install Git using Chocolatey or Winget package manager.
Install Git official website
To install Git from the official website, follow the steps below:
- Go to the official Git website and download the latest version of Git for Windows.
- Run the installer and follow the steps below:
- Click Next on the first two screens to accept the default options.
- Click Next on the Select Components screen.
- Click Next on the Choosing the default editor used by Git screen.
- Click Next on the Choosing the default terminal emulator screen.
- Select the Use Git from the Windows Command Prompt option.
- Select the Checkout Windows-style, commit Unix-style line endings option.
- Select the Use Windows’ default console window option.
- Click Next on the Configuring the line ending conversions screen.
- Click Next on the Configuring the terminal emulator to use with Git Bash screen.
- Click Install on the Choosing HTTPS transport backend screen.
- Click Finish on the Completing the Git Setup screen.
- Open a new command prompt window and verify that Git is installed correctly by typing
git --version
.
Install Git using Chocolatey
To install Git using Chocolatey, follow the steps below:
- Open Windows Terminal.
- Run the following command to install Git:
choco install git -y
Enter fullscreen mode
Exit fullscreen mode
- Verify that Git is installed correctly by typing
git --version
.
Install Git using Winget
To install Git using Winget, follow the steps below:
- Open Windows Terminal.
- Run the following command to install Git:
winget install --id=Git.Git -e
Enter fullscreen mode
Exit fullscreen mode
- Verify that Git is installed correctly by typing
git --version
.
Note: Don’t forget to specify global Git settings using the following command after installing git:
git config --global user.name 'USERNAME'
git config --global user.email 'YOUR_EMAIL@EXAMPLE.COM'
Enter fullscreen mode
Exit fullscreen mode
Generate SSH keys
To generate SSH keys, follow the steps below:
- Open Windows Terminal.
- Run the following command (change your
YOUR_EMAIL@EXAMPLE.COM
with your email address) to establish a new SSH key pair:
ssh-keygen -t rsa -b 4096 -C "YOUR_EMAIL@EXAMPLE.COM"
Enter fullscreen mode
Exit fullscreen mode
- It will ask you where you want to save the private key (id rsa), and you may accept the default location by pressing Enter.
Whether you already have a private key, it will ask if you want to override it:
Overwrite (y/n)?
Enter fullscreen mode
Exit fullscreen mode
- If this happens, hit Enter and type y. Then, enter and re-enter the following passcode (think of it as a password):
Enter a file in which to save the key (/c/Users/you/.ssh/id_rsa): [Press enter]
Enter fullscreen mode
Exit fullscreen mode
- Enter a secure passphrase.
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]
Enter fullscreen mode
Exit fullscreen mode
- The SSH key pair is created in ~/.ssh, and the whole interaction should look like this:
Enter fullscreen mode
Exit fullscreen mode
- Verify that the SSH key was created by running the following command:
ls .\.ssh\
Enter fullscreen mode
Exit fullscreen mode
Add SSH key to the ssh-agent to your account
Copy the SSH key to your clipboard by running the following command:
Get-Content .\.ssh\id_rsa.pub | Set-Clipboard
Enter fullscreen mode
Exit fullscreen mode
GitHub
Sign in to your GitHub account using a browser by going to github.com and entering your username and password. Click your profile photo in the upper-right corner of the page, then Settings:
Select SSH and GPG keys from the user settings sidebar. Then select New SSH key from the drop-down menu. Put a descriptive label for the new key in the Title area (for example, your computer’s name) and paste your public key into the Key field. Last but not least, click Add SSH key:
The key is now visible in the list of SSH keys linked to your account:
GitLab
Sign in to your GitLab account using a browser by going to gitlab.com and entering your username and password. Click your profile photo in the upper-right corner of the page, then Settings:
Click SSH Keys in the User Settings sidebar. In the Key area, paste your public key. Fill in the Title area for the new key with a descriptive term (for example, the name of your computer). Finally, click the Add key:
The key is now visible in the list of SSH keys linked to your account:
Bitbucket
Log in to your Bitbucket account using a browser by going to bitbucket.org and entering your username and password. Click your profile photo in the lower-left corner of the website, then Bitbucket settings:
SSH keys may be found in the Settings sidebar’s Security section. After that, select Add key from the drop-down menu. Fill up the Description box with a descriptive label for the new key (such as your computer’s name), and then paste your public key into the Key field. Last but not least, choose to Add key:
The key has now been added to your account’s list of SSH keys:
Test connecting via SSH
Before utilizing SSH with Git, GitHub, GitLab, and Bitbucket allow you to verify whether the connection has been set up successfully.
GitHub Test Connecting via SSH
Open the terminal once you’ve added your SSH key to your GitHub account and type:
ssh -T git@github.com
Enter fullscreen mode
Exit fullscreen mode
If you’re connecting to GitHub over SSH for the first time, the SSH client will ask if you trust the GitHub server’s public key:
The authenticity of host 'github.com (140.82.113.4)' can't be established.
RSA key fingerprint is SHA256:a5d6c20b1790b4c144b9d26c9b201bbee3797aa010f2701c09c1b3a6262d2c02.
Are you sure you want to continue connecting (yes/no)?
Enter fullscreen mode
Exit fullscreen mode
Press Enter after typing yes. GitHub has been added to the list of trustworthy hosts in the SSH client:
Warning: Permanently added 'github.com,140.82.113.4' (RSA) to the list of known hosts.
Enter fullscreen mode
Exit fullscreen mode
You won’t be asked about GitHub’s public key again once you’ve added it to the list of known hosts.
The server notifies you that you have successfully authenticated and ends the connection: Because this remote access through SSH is offered by GitHub only for testing purposes and not for practical usage, the server informs you that you have successfully authenticated and terminates the connection:
Hi YOUR_USER_NAME! You've successfully authenticated, but GitHub does not provide shell access.
Enter fullscreen mode
Exit fullscreen mode
If you passed the test, you may now utilize SSH with GitHub.
The entire interaction should look something like this:
ssh -T git@github.com
The authenticity of host 'github.com (140.82.113.4)' can't be established.
RSA key fingerprint is SHA256:a5d6c20b1790b4c144b9d26c9b201bbee3797aa010f2701c09c1b3a6262d2c02.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,140.82.113.4' (RSA) to the list of known hosts.
Hi your_user_name! You've successfully authenticated, but GitHub does not provide shell access.
YOUR_USER_NAME@YOUR_HOST_NAME:~>
Enter fullscreen mode
Exit fullscreen mode
GitLab Test Connecting via SSH
The test is pretty similar if you’ve added your SSH key to your GitLab account:
ssh -T git@gitlab.com
The authenticity of host 'gitlab.com (35.231.145.151)' can't be established.
ECDSA key fingerprint is SHA256:4ac7a7fd4296d5e6267c9188346375ff78f6097a802e83c0feaf25277c9e70cc.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'gitlab.com,35.231.145.151' (ECDSA) to the list of known hosts.
Welcome to GitLab, @YOUR_USER_NAME!
Enter fullscreen mode
Exit fullscreen mode
If you passed the test, you may now utilize SSH with GitLab.
Bitbucket Test Connecting via SSH
The test is pretty similar if you’ve added your SSH key to your Bitbucket account:
ssh -T git@bitbucket.org
The authenticity of host 'bitbucket.org (104.192.143.1)' can't be established.
RSA key fingerprint is SHA256:fb7d37d5497c43f73325e0a98638cac8dda3b01a8c31f4ee11e2e953c19e0252.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'bitbucket.org,104.192.143.1' (RSA) to the list of known hosts.
logged in as YOUR_USER_NAME.
You can use git or hg to connect to Bitbucket. Shell access is disabled.
Enter fullscreen mode
Exit fullscreen mode
If you passed the test, you may now utilize SSH with Bitbucket.
References
- GitHub SSH Key Setup
- GitLab SSH Key Setup
- Bitbucket SSH Key Setup
При первой загрузке/выгрузке изменений в/из Github часто возникает ошибка git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Данная статья раз и навсегда положит этим ошибкам конец!
Всё то, о чём пойдет речь ниже, можно посмотреть в этом видео
Открываем терминал в том месте где у вас лежит код, который вы хотите интегрировать в Github или Gitlab. Проверяем есть ли уже существующий SSH ключ, для этого вводим команду ниже:
ls -al ~/.ssh
Пример НЕсуществующего ключа SSH:
Пример существующего ключа SSH:
Если ключ существует переходите сразу к шагу 4 или создайте отдельный новый ключ специально для Github.
ШАГ 2. Генерация нового SSH ключа
- Введите в терминале команду ниже:
ssh-keygen -t ed25519 -C «your_email@example.com»
Пояснения команды:ssh-keygen команда для генерации SSH ключа -t ed25519 алгоритм шифрования, по умолчанию алгоритм rsa, Github рекомендует использовать алгоритм ed25519 -C значит «комментарий», все что после этой команды в кавычках будет комментарием «your_email@example.com» комментарий, замените на свой email в Github — это нужно чтобы различать SSH ключи между собой, их может быть несколько - Теперь нужно указать путь и название файла, можно оставить по умолчанию и нажать Enter, но давайте поменяем имя файла, чтобы понимать что он сгенерирован именно для Github!
Скопируйте и вставьте путь по умолчанию, поменяйте имя файла и нажмите Enter. - Далее нужно будет задать пароль (кодовую фразу) для нашего ключа, пропускаем этот шаг, просто два раза нажимаем Enter, иначе придется постоянно вводить этот пароль.
- Если вы все сделали правильно будет примерно также, как на скриншоте ниже:
ШАГ 3. Добавление SSH ключа в SSH-agent
Не пропускайте этот шаг! Без него ничего работать не будет.
Что же такое SSH-agent на сайте habr.com вот такое описание: «ssh-agent — это менеджер ключей для SSH. Он хранит ваши ключи и сертификаты в памяти, незашифрованные и готовые к использованию ssh . Это избавляет вас от необходимости вводить пароль каждый раз, когда вы подключаетесь к серверу.»
- Сначала запустим SSH-agent командой ниже:
eval «$(ssh-agent -s)»
надпись Agent pid 61 (у вас будет любое другое число) говорит о том, что агент успешно запущен! - Добавьте SSH ключ в SSH агент командой ниже, предварительно поменяв название SSH ключа на ваше:
ssh-add ~/.ssh/id_ed25519_github
надпись примерная как на скрине ниже, говорит о том, что ключ успешно добавлен - Добавим конфигурационный файл, чтобы SSH ключ автоматически добавлялся в SSH-agent, введите команду ниже, она создаст файл config, если он отсутствует:
touch ~/.ssh/config - Теперь в созданный файл config добавим следующий текст, заменив id_ed25519_github на название своего ключа, если нужно:
Host * AddKeysToAgent yes IdentityFile ~/.ssh/id_ed25519_github
- Для пользователей MacOS вводим команду ниже, откроется обычный редактор текста, вставляем в него текст и сохраняем изменения
open ~/.ssh/config - Для пользователей Windows вводим команду ниже и нажимаем Enter
cat > ~/.ssh/config <<EOF
далее вставить текст, нажать Enter, ввести команду ниже и нажать Enter
EOF
- Для пользователей MacOS вводим команду ниже, откроется обычный редактор текста, вставляем в него текст и сохраняем изменения
- Проверьте что текст был добавлен в файл config командой
cat ~/.ssh/config
должно быть как на скриншоте:
ШАГ 4. Добавление SSH в Github
Готово! Проверьте что ключ работает
Возвращаемся в наш терминал и вводим команду git pull, файлы должны загрузиться или как в моем случае должна появиться надпись, что все уже обновлено.
Спасибо за внимание!
Инструменты
Git SSH Windows — пошаговое руководство
Дата размещения статьи 08/12/2019 👁31067
Git SSH Windows — пошаговое руководство
Настроим пошагово Git SSH для Windows 10. Это позволит вам выполнять команды git без ввода пароля от своей учетной записи GitHub.
Порядок действий:
- Генерация ключа SSH.
- Добавление SSH-ключа в ssh-agent.
- Добавление ключа SSH в учетную запись GitHub.
Генерация ключа SSH
Откройте bash/терминал. Добавьте следующий текст, подставив свой адрес электронной почты GitHub.
ssh-keygen -t rsa -b 4096 -C "ваша@почта.com"
Будет создан ключ ssh, используя e-mail в качестве метки.
Когда вам будет предложено «Введите файл, в котором вы хотите сохранить ключ», нажмите Enter. Это установит в местоположение по умолчанию.
Enter a file in which to save the key (/c/Users/you/.ssh/id_rsa):[Press enter]
Далее введите безопасную фразу-пароль дважды или просто нажмите Enter.
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]
Добавление SSH-ключа в ssh-agent
Чтобы запустить ssh-агент введите следующую команду.
На экране отобразится похожая строка.
Agent pid 31724
Добавим свой закрытый ключ SSH в ssh-agent. Если вы создали свой ключ с другим именем (или добавляете существующий ключ с другим именем), замените в команде id_rsa на имя вашего файла закрытого (приватного) ключа.
Ключ будет успешно добавлен в ssh-агент.
Добавление ключа SSH в учетную запись GitHub
Мы сгенерировали у себя на компьютере закрытый ключ SSH и добавили его в ssh-агент. Теперь нам необходимо добавить SSH ключ в учетную запись GitHub.
Сейчас нам необходимо скопировать SSH ключ в буфер обмена.
Способов есть несколько, но я же вам предлагаю следующее решения для Windows 10: введите команду ниже.
Прямо в терминале вы увидите содержимое необходимого файла с ключем. Скопируйте его в буфер.
Теперь зайдите на вашу страницу GitHub » Settings.
Перейдите во вкладку SSH and GPG keys и нажмите на кнопку New SSH key для добавления SSH ключа в вашу учетную запись GitHub.
В поле Title добавьте заголовок для данного ключа. Например, если вы захотите настроить SSH доступ на нескольких устройствах, то вы будите понимать какой ключ принадлежит какому устройству.
В поле Key добавьте свой ssh-ключ, который вы скопировали в буфер обмена на предыдущем шаге.
Нажмите Add SSH key.
Для подтверждения вам потребуется ввести свой пароль от учетной записи GitHub.
На этом настройка SSH для вашего устройства завершена, теперь вы можете работать с git без ввода пароля от своей учетной записи.
Если вам понравилась данная статья, можете прочитать как настроить моментальную загрузку сайта на хостинг и синхронизацию файлов.
JavaScript: Window Location Checkbox Checked — Проверка Состояния Чекбокса ✔️
Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки,
то можете следить за выходом новых статей в Telegram.
- Настройка Gulp Babel
- Микроразметка сайта
- Как перенести сайт WordPress на хостинг
- Настройте показ всего текста во время загрузки веб-шрифтов
- Сниппеты в VS Code
- Не удается проверить так как не задан исполняемый PHP-файл
В этой статье мы настроим SSH аутентификацию в Windows по RSA или EdDSA ключам для безопасного доступа к удаленным компьютерам/серверам. Рассмотрим, как сгенерировать открытый и закрытый ключи (сертификаты) в Windows и настроить сервер OpenSSH в Windows 10/11 и Windows Server 2019/2022 для аутентификации по ключам (без паролей).
Аутентификация по SSH ключам широко используется в мире Linux, а в Windows этот функционал появился относительно недавно. Идея заключается в том, что на SSH сервере добавляется открытый ключ клиента и при подключении сервер проверяет наличие соответствующего закрытого ключа у клиента. Таким образом удаленный пользователь может аутентифицироваться в Windows без ввода пароля.
Содержание:
- Генерация SSH ключей на клиенте Windows
- Настройка OpenSSH в Windows для авторизации по ключам
- Вход по SSH ключу для локальных администраторов Windows
Генерация SSH ключей на клиенте Windows
На клиентском, компьютере, с которого вы будет подключаетесь к удалённому серверу Windows с OpenSSH, вам нужно сгенерировать пару ключей (открытый и закрытый). Закрытый ключ хранится на клиенте (не отдавайте его никому!), а открытый ключ нужно скопировать в файл authorized_keys на SSH сервере. Чтобы сгенерировать SSH ключи на клиенте Windows, вы должны установить клиент OpenSSH.
В Windows 10/11 и Windows Server 2019/2022 клиент OpenSSH устанавливается как отдельный встроенный компонент с помощью PowerShell:
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Запустите обычную (непривилегированную сессию PowerShell) и сгенерируйте пару ED25519 ключей:
ssh-keygen -t ed25519
По умолчанию утилита ssh-keygen генерирует ключи RSA 2048. В настоящий момент вместо RSA ключей рекомендуется использовать именно ED25519.
Утилита попросит вас указать пароль для защиты закрытого ключа. Если вы укажете пароль, то каждый раз при использовании этого ключа для SSH авторизации, вы должны будете вводить этот пароль. Я не стал указывать пароль для ключа (не рекомендуется).
Generating public/private ed25519 key pair. Enter file in which to save the key (C:\Users\myuser/.ssh/id_ed25519): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in C:\Users\myuser/.ssh/id_ed25519. Your public key has been saved in C:\Users\myuser/.ssh/id_ed25519.pub. The key fingerprint is: SHA256:C2wXeCQSUcJyq0 myuser@computername The key's randomart image is: +--[ED25519 256]--+ | ..*O=..o. | +----[SHA256]-----+
Утилита ssh-keygen создаст каталог .ssh в профиле текущего пользователя Windows (%USERPROFILE%\.ssh) и сгенерирует 2 файла:
-
id_ed25519
– закрытый ключ (если вы сгенерировали ключ типа RSA, файл будет называться
id_rsa
) -
id_ed25519.pub
– публичный ключ (аналогичный RSA ключ называется
id_rsa.pub
)
После того, как ключи созданы, вы можете добавить закрытый ключ в службу SSH Agent, которая позволяет удобно управлять закрытыми ключами и использовать их для аутентификации.
SSH Agent может хранить закрытые ключи и предоставлять их в контексте безопасности текущего пользователя. Запустите службу ssh-agent и настройте автоматический запуск с помощью PowerShell команд управления службами:
Set-service ssh-agent StartupType ‘Automatic’
Start-Service ssh-agent
Добавьте ваш закрытый ключ в базу ssh-agent:
ssh-add "C:\Users\user\.ssh\id_ed25519"
Identity added: C:\Users\kbuldogov\.ssh\id_ed25519 (kbuldogov@computername)
Или так:
ssh-add.exe $ENV:UserProfile\.ssh\id_ed25519
Настройка OpenSSH в Windows для авторизации по ключам
SSH сервер (в этом примере это удаленный компьютер с Windows 11 и настроенной службой OpenSSH).
Скопируйте файл id_ed25519.pub в каталог .ssh профиля пользователя, под которым вы будете подключаться к SSH серверу. Например, у меня в Windows 11 создан пользователь user1, значит я должен скопировать ключ в файл C:\Users\user1\.ssh\authorized_keys.
В данном примере подразумевается, что user1 это обычная учетная запись пользователя без прав локального администратора на компьютере с сервером SSH.
Если каталог .ssh в профиле отсутствует, его нужно создать вручную.
Можно скопировать ключ на SSH сервер с клиента с помощью SCP:
scp C:\Users\youruser\.ssh\id_rsa.pub [email protected]:c:\users\user1\.ssh\authorized_keys
В один файл authorized_keys можно добавить несколько открытых ключей.
По умолчанию в OpenSSH сервере в Windows отключена аутентификация по ключам. Вы можете проверить это в конфигурационном файле sshd_config. Проще всего получить список разрешенных способов аутентификации в OpenSSH с помощью такой PowerShell команды (Select-String используется как аналог grep в PowerShell):
cat "C:\ProgramData\ssh\sshd_config"| Select-String "Authentication"
#PubkeyAuthentication yes #HostbasedAuthentication no # HostbasedAuthentication PasswordAuthentication yes #GSSAPIAuthentication no
В этом примере строка PubkeyAuthentication закомментирована, значит этот способ аутентификации отключен.
Откройте файл sshd_config с помощью блокнота, раскоментируйте строку:
Notepad C:\ProgramData\ssh\sshd_config
PubkeyAuthentication yes
Также в конфигурационном файле sshd_config придется отключить режим StrictModes. По умолчанию этот режим включен и запрещает аутентификацию по ключам, если закрытый и открытый ключ недостаточно защищены. Раскомментируйте строку
#StrictModes yes
, измените на
StrictModes no
.
Сохраните файл и перезапустите службу sshd:
Restart-Service sshd
Теперь вы можете подключиться к SSH серверу без ввода пароля пользователя. А если вы не задали пароль (passphrase) для закрытого ключа, вы сразу автоматически подключитесь к вашему удаленному серверу Windows.
Для подключения через SSH к удаленному хосту используется следующая команда:
ssh (username)@(имя или IP адрес SSH сервера)
Например,
ssh [email protected]
Это означает, что вы хотите подключиться к удаленному SSH серверу с адресом 192.168.1.90 под учетной записью admin. Служба SSH Agent автоматически попытается использовать для авторизации сохраненный ранее закрытый ключ.
- Если вы не хотите использовать ssh-agent для управления ключами, вы можете указать путь к закрытому ключу, который нужно использовать для SSH аутентификации:
ssh [email protected] -i "C:\Users\user\.ssh\id_ed25519"
- Для подключения с помощью учетной записи пользователя из домена Active Directory используется формат:
ssh [email protected]@168.1.90 -i <private_key_absolute_path>
При первом подключении нужно добавить отпечаток ключа SSH сервера в доверенные. Наберите yes -> Enter.
The authenticity of host '192.168.1.90 (192.168.1.90)' can't be established. ECDSA key fingerprint is SHA256:LNMJTbTS0EmrsGYTHB3Aa3Tisp+7fvHwZHbTA900ofw. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Информацию по аутентификации в Windows с помощью SSH ключей можно найти в журнале события. В современных версиях OpenSSH логи пишутся не в текстовые файлы, а в отдельный журнал Event Viewer (Application and services logs -> OpenSSH -> Operational).
При успешном подключении с помощью ключа в журнале появится событие:
EventID 4 sshd: Accepted publickey for locadm from 192.168.14.1 port 55772 ssh2: ED25519 SHA256:FEHDWM/J74FbIzCCoJNbh14phS67kQgh7k8UrKPSvCM
Если вы не смогли подключиться к вашему SSH серверу по RSA ключу, и у вас все равно запрашивается пароль, скорее всего пользователь, под которым вы подключаетесь, входит в группу локальных администраторов сервера (SID группы S-1-5-32-544). Об этом далее.
Вход по SSH ключу для локальных администраторов Windows
В OpenSSH используются особые настройки доступа по ключам для пользователей с правами локального администратора Windows.
В первую очередь, вместо ключа authorized_keys в профиле пользователя нужно использовать файл с ключами C:\ProgramData\ssh\administrators_authorized_keys. Вам нужно добавить ваш ключ в этот текстовый файл (в целях безопасности права на этот файл должны быть только у группы Administrators и SYSTEM).
Вы можете изменить NTFS права на файл с помощью:
- утилиты icacls:
icacls.exe "C:\ProgramData\ssh\administrators_authorized_keys" /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F
- или с помощью PowerShell командлетов get-acl и set-acl:
get-acl "$env:programdata\ssh\ssh_host_rsa_key" | set-acl "$env:programdata\ssh\administrators_authorized_keys"
После этого SSH аутентификация по ключам работает даже при отключенном режиме StrictModes
alert]Чтобы использовать ключ authorized_keys из профиля пользователя, и не переносить данные открытого ключа в файл administrators_authorized_keys, вы можете закомментировать строку в файле конфигурации OpenSSH (C:\ProgramData\ssh\sshd_config).
Закомментируйте строки:
#Match Group administrators # AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys
Дополнительно в файле sshd_config вы можете запретить SSH подключение по паролю по паролю:
PasswordAuthentication no
После сохранения изменений в файле sshd_config не забудьте перезапустить службу sshd.
restart-service sshd
Если вы установили PasswordAuthentication no, и некорректно настроите аутентификацию по ключам, то при подключении по ssh будет появляться ошибка:
[email protected]: Permission denied (publickey,keyboard-interactive).
В OpenSSH на Linux доступна опция PermitRootLogin, позволяющая ограничить доступ к SSH серверу под аккаунтом root. В Windows OpenSSH эта директива не доступна и для ограничения доступа администраторов нужно использовать параметр DenyGroups.
Итак, вы настроили SSH аутентификацию в Windows по открытому RSA-ключу (сертификату). Теперь вы можете использовать такой способ аутентификации для безопасного доступа к удаленным северам, автоматического поднятия проброса портов в SSH туннеле, запуска скриптов и других задачах автоматизации.