Ssh keys windows location

OpenSSH key management

Most authentication in Windows environments is done with a username-password pair. This works well for systems that share a common domain. When working across domains, such as between on-premise and cloud-hosted systems, it becomes vulnerable to brute force intrusions.

By comparison, Linux environments commonly use public-key/private-key pairs to drive authentication which doesn’t require the use of guessable passwords. OpenSSH includes tools to help support this, specifically:

  • ssh-keygen for generating secure keys
  • ssh-agent and ssh-add for securely storing private keys
  • scp and sftp to securely copy public key files during initial use of a server

This document provides an overview of how to use these tools on Windows to begin using key authentication with SSH. If you are unfamiliar with SSH key management, we strongly recommend you review NIST document IR 7966 titled «Security of Interactive and Automated Access Management Using Secure Shell (SSH).»

About key pairs

Key pairs refer to the public and private key files that are used by certain authentication protocols.

SSH public-key authentication uses asymmetric cryptographic algorithms to generate two key files – one «private» and the other «public». The private key files are the equivalent of a password, and should stay protected under all circumstances. If someone acquires your private key, they can log in as you to any SSH server you have access to. The public key is what is placed on the SSH server, and may be shared without compromising the private key.

When using key authentication with an SSH server, the SSH server and client compare the public keys for username provided against the private key. If the server-side public key cannot be validated against the client-side private key, authentication fails.

Multi-factor authentication may be implemented with key pairs by requiring that a passphrase be supplied when the key pair is generated (see key generation below). During authentication the user is prompted for the passphrase, which is used along with the presence of the private key on the SSH client to authenticate the user.

Host key generation

Public keys have specific ACL requirements that, on Windows, equate to only allowing access to administrators and System. To make this easier,

  • The OpenSSHUtils PowerShell module has been created to set the key ACLs properly, and should be installed on the server
  • On first use of sshd, the key pair for the host will be automatically generated. If ssh-agent is running, the keys will be automatically added to the local store.

To make key authentication easy with an SSH server, run the following commands from an elevated PowerShell prompt:

Since there is no user associated with the sshd service, the host keys are stored under \ProgramData\ssh.

User key generation

To use key-based authentication, you first need to generate some public/private key pairs for your client. From PowerShell or cmd, use ssh-keygen to generate some key files.

This should display something like the following (where «username» is replaced by your user name)

You can hit Enter to accept the default, or specify a path where you’d like your keys to be generated. At this point, you’ll be prompted to use a passphrase to encrypt your private key files. The passphrase works with the key file to provide 2-factor authentication. For this example, we are leaving the passphrase empty.

Now you have a public/private ED25519 key pair (the .pub files are public keys and the rest are private keys):

Читайте также:  Как отключить тайм аут экрана windows 10

Remember that private key files are the equivalent of a password should be protected the same way you protect your password. To help with that, use ssh-agent to securely store the private keys within a Windows security context, associated with your Windows login. To do that, start the ssh-agent service as Administrator and use ssh-add to store the private key.

After completing these steps, whenever a private key is needed for authentication from this client, ssh-agent will automatically retrieve the local private key and pass it to your SSH client.

It is strongly recommended that you back up your private key to a secure location, then delete it from the local system, after adding it to ssh-agent. The private key cannot be retrieved from the agent. If you lose access to the private key, you would have to create a new key pair and update the public key on all systems you interact with.

Deploying the public key

To use the user key that was created above, the public key needs to be placed on the server into a text file called authorized_keys under users\username\.ssh\. The OpenSSH tools include scp, which is a secure file-transfer utility, to help with this.

To move the contents of your public key (

.ssh\id_ed25519.pub) into a text file called authorized_keys in

.ssh\ on your server/host.

This example uses the Repair-AuthorizedKeyPermissions function in the OpenSSHUtils module which was previously installed on the host in the instructions above.

These steps complete the configuration required to use key-based authentication with SSH on Windows. After this, the user can connect to the sshd host from any client that has the private key.

Как использовать ключи SSH с Windows в Azure How to use SSH keys with Windows on Azure

Эта статья предназначена для пользователей Windows, желающих создать и использовать ключи Secure Shell (SSH) для подключения к виртуальным машинам Linux в Azure. This article is for Windows users who want to create and use secure shell (SSH) keys to connect to Linux virtual machines (VMs) in Azure. Вы также можете создать и сохранить ключи SSH в портал Azure, которые будут использоваться при создании виртуальных машин на портале. You can also generate and store SSH keys in the Azure portal to use when creating VMs in the portal.

Чтобы использовать ключи SSH из клиента Linux или macOS, ознакомьтесь с краткими инструкциями. To use SSH keys from a Linux or macOS client, see the quick steps. Более подробный обзор SSH см. в статье Создание ключей SSH и управление ими для проверки подлинности на виртуальной машине Linux в Azure. For a more detailed overview of SSH, see Detailed steps: Create and manage SSH keys for authentication to a Linux VM in Azure.

Общие сведения о SSH и ключах Overview of SSH and keys

SSH — это протокол зашифрованного соединения, позволяющий выполнять безопасные входы по незащищенным соединениям. SSH is an encrypted connection protocol that allows secure sign-ins over unsecured connections. SSH — это протокол подключения по умолчанию для виртуальных машин Linux, размещенных в Azure. SSH is the default connection protocol for Linux VMs hosted in Azure. Хотя протокол SSH и обеспечивает зашифрованное подключение, при использовании паролей с SSH виртуальные машины все равно не защищены от атак методом подбора. Although SSH itself provides an encrypted connection, using passwords with SSH still leaves the VM vulnerable to brute-force attacks. Мы рекомендуем подключаться к виртуальной машине по протоколу SSH с помощью пары открытого и закрытого ключей, также называемых ключами SSH. We recommend connecting to a VM over SSH using a public-private key pair, also known as SSH keys.

Пара открытого и закрытого ключей аналогична блокировке передней дверцы. The public-private key pair is like the lock on your front door. Блокировка предоставляется общедоступной, любой пользователь с правом ключом может открыть дверцу. The lock is exposed to the public, anyone with the right key can open the door. Ключ является частным и предоставляется только доверенным людям, так как его можно использовать для разблокировки дверцы. The key is private, and only given to people you trust because it can be used to unlock the door.

Читайте также:  Космические рейнджеры запуск под windows 10

Открытый ключ размещается на виртуальной машине Linux при создании виртуальной машины. The public key is placed on your Linux VM when you create the VM.

Закрытый ключ остается в локальной системе. The private key remains on your local system. Его нужно защищать Protect this private key. и нельзя никому предоставлять. Do not share it.

При подключении к виртуальной машине Linux виртуальная машина проверяет SSH-клиент, чтобы убедиться, что он имеет правильный закрытый ключ. When you connect to your Linux VM, the VM tests the SSH client to make sure it has the correct private key. Если у клиента есть закрытый ключ, он получает доступ к виртуальной машине. If the client has the private key, it’s granted access to the VM.

В зависимости от политик безопасности Организации можно повторно использовать одну пару ключей для доступа к нескольким виртуальным машинам и службам Azure. Depending on your organization’s security policies, you can reuse a single key pair to access multiple Azure VMs and services. Для каждой виртуальной машины не требуется отдельная пара ключей. You do not need a separate pair of keys for each VM.

Открытый ключ можно использовать совместно с любым пользователем, но только вы (или ваша локальная инфраструктура безопасности) должны иметь доступ к вашему закрытому ключу. Your public key can be shared with anyone, but only you (or your local security infrastructure) should have access to your private key.

Поддерживаемые форматы ключей SSH Supported SSH key formats

В настоящее время платформа Azure поддерживает пары из открытого и закрытого ключей SSH-2 RSA длиной не менее 2048 битов. Azure currently supports SSH protocol 2 (SSH-2) RSA public-private key pairs with a minimum length of 2048 bits. Другие форматы ключей, например ED25519 и ECDSA, не поддерживаются. Other key formats such as ED25519 and ECDSA are not supported.

SSH-клиенты SSH clients

В последние версии Windows 10 входят клиентские команды OpenSSH для создания и использования ключей SSH и создания SSH-подключений из PowerShell или командной строки. Recent versions of Windows 10 include OpenSSH client commands to create and use SSH keys and make SSH connections from PowerShell or a command prompt. Это самый простой способ создать SSH-подключение к виртуальной машине Linux с компьютера Windows. This is the easiest way to create an SSH connection to your Linux VM, from a Windows computer.

Можно также использовать Bash в Azure Cloud Shell для подключения к виртуальной машине. You can also use Bash in the Azure Cloud Shell to connect to your VM. Cloud Shell можно использовать в веб-браузере, портал Azureили в качестве терминала в Visual Studio Code с помощью расширения учетной записи Azure. You can use Cloud Shell in a web browser, from the Azure portal, or as a terminal in Visual Studio Code using the Azure Account extension.

Вы также можете установить подсистему Windows для Linux , чтобы подключиться к виртуальной машине по протоколу SSH и использовать другие собственные средства Linux в оболочке bash. You can also install the Windows Subsystem for Linux to connect to your VM over SSH and use other native Linux tools within a Bash shell.

Создание пары ключей SSH Create an SSH key pair

Создайте пару ключей SSH с помощью ssh-keygen команды. Create an SSH key pair using the ssh-keygen command. Введите имя файла или используйте значение по умолчанию, показанное в скобках (например, C:\Users\username/.ssh/id_rsa ). Enter a filename, or use the default shown in parenthesis (for example C:\Users\username/.ssh/id_rsa ). Введите парольную фразу для файла или оставьте пустым парольную фразу, если вы не хотите использовать парольную фразу. Enter a passphrase for the file, or leave the passphrase blank if you do not want to use a passphrase.

Создание виртуальной машины с помощью ключа Create a VM using your key

Чтобы создать виртуальную машину Linux, использующую ключи SSH для проверки подлинности, укажите открытый ключ SSH при создании виртуальной машины. To create a Linux VM that uses SSH keys for authentication, provide your SSH public key when creating the VM.

Читайте также:  Launcher windows как удалить

С помощью Azure CLI вы указываете путь и имя файла для открытого ключа с помощью az vm create и —ssh-key-value параметра. Using the Azure CLI, you specify the path and filename for the public key using az vm create and the —ssh-key-value parameter.

В PowerShell используйте New-AzVM и добавьте ключ SSH в конфигурацию виртуальной машины с помощью. With PowerShell, use New-AzVM and add the SSH key to the VM configuration using`. Пример см. в разделе Краткое руководство. Создание виртуальной машины Linux в Azure с помощью PowerShell. For an example, see Quickstart: Create a Linux virtual machine in Azure with PowerShell.

При выполнении большого количества развертываний с помощью портала может потребоваться передать открытый ключ в Azure, где его можно легко выбрать при создании виртуальной машины на портале. If you do a lot of deployments using the portal, you might want to upload your public key to Azure, where it can be easily selected when creating a VM from the portal. Дополнительные сведения см. в разделе Отправка ключа SSH. For more information, see Upload an SSH key.

Подключение к виртуальной машине Connect to your VM

С помощью открытого ключа, развернутого на виртуальной машине Azure, и закрытого ключа в локальной системе установите SSH-подключение к виртуальной машине, используя ее IP-адрес или DNS-имя. With the public key deployed on your Azure VM, and the private key on your local system, SSH to your VM using the IP address or DNS name of your VM. Замените azureuser и 10.111.12.123 в следующей команде на имя пользователя администратора, IP-адрес (или полное доменное имя) и путь к закрытому ключу: Replace azureuser and 10.111.12.123 in the following command with the administrator user name, the IP address (or fully qualified domain name), and the path to your private key:

Если вы настроили парольную фразу при создании пары ключей, введите парольную фразу при появлении запроса. If you configured a passphrase when you created your key pair, enter the passphrase when prompted.

Если виртуальная машина использует политику доступа JIT, запросите доступ, прежде чем подключиться к виртуальной машине. If the VM is using the just-in-time access policy, you need to request access before you can connect to the VM. Дополнительные сведения о политике JIT см. в статье Управление доступом к виртуальным машинам с помощью JIT-доступа. For more information about the just-in-time policy, see Manage virtual machine access using the just in time policy.

Дальнейшие действия Next steps

Сведения о ключах SSH в портал Azure см. в разделе Создание и хранение ключей SSH в портал Azure , которые используются при создании виртуальных машин на портале. For information about SSH keys in the Azure portal, see Generate and store SSH keys in the Azure portal to use when creating VMs in the portal.

Подробные инструкции, параметры и дополнительные примеры работы с ключами SSH приведены в статье Подробные инструкции: создание ключей SSH для аутентификации на виртуальной машине Linux в Azure и управление этими ключами. For detailed steps, options, and advanced examples of working with SSH keys, see Detailed steps to create SSH key pairs.

Для создания ключей SSH и установления SSH-подключений к виртуальным машинам Linux можно также использовать PowerShell в Azure Cloud Shell. You can also use PowerShell in Azure Cloud Shell to generate SSH keys and make SSH connections to Linux VMs. Ознакомьтесь с разделом Краткое руководство по использованию PowerShell в Azure Cloud Shell (предварительная версия). See the PowerShell quickstart.

Если при подключении к виртуальным машинам Linux по протоколу SSH возникают трудности, см. статью Troubleshoot SSH connections to an Azure Linux VM that fails, errors out, or is refused (Устранение неполадок с ошибками, сбоем или отклонением SSH-подключения к виртуальной машине Azure Linux). If you have difficulty using SSH to connect to your Linux VMs, see Troubleshoot SSH connections to an Azure Linux VM.

Оцените статью