- Key Storage and Retrieval
- Key Storage Architecture
- Key Types
- Supported Algorithms
- Key Directories and Files
- Управление ключами OpenSSH OpenSSH key management
- Сведения о парах ключей About key pairs
- Создание ключей узла Host key generation
- Создание ключей пользователя User key generation
- Развертывание открытого ключа Deploying the public key
Key Storage and Retrieval
Key Storage Architecture
CNG provides a model for private key storage that allows adapting to the current and future demands of creating applications that use cryptography features such as public or private key encryption, as well as the demands of the storage of key material. The key storage router is the central routine in this model and is implemented in Ncrypt.dll. An application accesses the key storage providers (KSPs) on the system through the key storage router, which conceals details, such as key isolation, from both the application and the storage provider itself. The following illustration shows the design and function of the CNG key isolation architecture.
To comply with common criteria (CC) requirements, the long-lived keys must be isolated so that they are never present in the application process. CNG currently supports the storage of asymmetric private keys by using the Microsoft software KSP that is included with Windows Server 2008 and Windows Vista and installed by default.
Key isolation is enabled by default in Windows Server 2008 and Windows Vista. The key isolation feature is not available on platforms prior to these. Also, third party KSPs are not loaded in the key isolation service (LSA process). Only the Microsoft KSP is loaded in the key isolation service.
The LSA process is used as the key isolation process to maximize performance. All access to private keys goes through the key storage router, which exposes a comprehensive set of functions for managing and using private keys.
CNG stores the public portion of the stored key separately from the private portion. The public portion of a key pair is also maintained in the key isolation service and is accessed by using local remote procedure call (LRPC). The key storage router uses LRPC when calling into the key isolation process. All access to private keys goes through the private key router and is audited by CNG.
As described above, a wide range of hardware storage devices can be supported. In each case, the interface to all of these storage devices is identical. It includes functions to perform various private key operations as well as functions that pertain to key storage and management.
CNG provides a set of APIs that are used to create, store, and retrieve cryptographic keys. For a list of these APIs, see CNG Key Storage Functions.
Key Types
CNG supports the following key types:
- Diffie-Hellman public and private keys.
- Digital Signature Algorithm (DSA, FIPS 186-2) public and private keys.
- RSA (PKCS #1) public and private keys.
- Several legacy (CryptoAPI) public and private keys.
- Elliptic Curve Cryptography public and private keys.
Supported Algorithms
CNG supports the following key algorithms.
Algorithm | Key/hash length (bits) |
---|---|
RSA | 512 to 16384, in 64 bit increments |
DH | 512 to 16384, in 64 bit increments |
DSA | 512 to 1024, in 64 bit increments |
ECDSA | P-256, P-384, P-521 (NIST Curves) |
ECDH | P-256, P-384, P-521 (NIST Curves) |
MD2 | 128 |
MD4 | 128 |
MD5 | 128 |
SHA-1 | 160 |
SHA-256 | 256 |
SHA-384 | 384 |
SHA-512 | 512 |
Key Directories and Files
The Microsoft legacy CryptoAPI CSPs store private keys in the following directories.
Key type | Directories |
---|---|
User private | %APPDATA%\Microsoft\Crypto\RSA\User SID\ %APPDATA%\Microsoft\Crypto\DSS\User SID\ |
Local system private | %ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\RSA\S-1-5-18\ %ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\DSS\S-1-5-18\ |
Local service private | %ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\RSA\S-1-5-19\ %ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\DSS\S-1-5-19\ |
Network service private | %ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\RSA\S-1-5-20\ %ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\DSS\S-1-5-20\ |
Shared private | %ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\RSA\MachineKeys %ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\DSS\MachineKeys |
CNG stores private keys in the following directories.
Key type | Directory |
---|---|
User private | %APPDATA%\Microsoft\Crypto\Keys |
Local system private | %ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\SystemKeys |
Local service private | %WINDIR%\ServiceProfiles\LocalService |
Network service private | %WINDIR%\ServiceProfiles\NetworkService |
Shared private | %ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\Keys |
The following are some of the differences between the CryptoAPI and CNG key containers.
- CNG uses different file names for key files than key files that are created by the Rsaenh.dll and Dssenh.dll legacy CSPs. The legacy key files also have the .key extension, but CNG key files do not have the .key extension.
- CNG fully supports Unicode key container names; CNG uses a hash of the Unicode container name, whereas CryptoAPI uses a hash of the ANSI container name.
- CNG is more flexible with regard to RSA key pairs. For example, CNG supports public exponents larger than 32-bits in length, and it supports keys in which p and q are different lengths.
- In CryptoAPI, the key container file is stored in a directory whose name is the textual equivalent of the user’s SID. This is no longer the case in CNG, which removes the difficulty of moving users from one domain to another without losing all of their private keys.
- The CNG KSP and key names are limited to MAX_PATH Unicode characters. The CryptoAPI CSP and key names are limited to MAX_PATH ANSI characters.
- CNG offers the capability of user-defined key properties. Users can create and associate custom properties with keys, and have them stored with persisted keys.
When persisting a key, CNG can create two files. The first file contains the private key in the new CNG format and is always created. This file is not usable by the legacy CryptoAPI CSPs. The second file contains the same private key in the legacy CryptoAPI key container. The second file conforms to the format and location used by Rsaenh.dll. Creation of the second file only occurs if the NCRYPT_WRITE_KEY_TO_LEGACY_STORE_FLAG flag is specified when the NCryptFinalizeKey function is called to finalize an RSA key. This feature is not supported for DSA and DH keys.
When an application attempts to open an existing persisted key, CNG first attempts to open the native CNG file. If this file does not exist, then CNG attempts to locate a matching key in the legacy CryptoAPI key container.
When you move or copy CryptoAPI keys from a source machine to a target machine with Windows User State Migration Tool (USMT), CNG will fail to access the keys on the target machine. To access such migrated keys, you must use the CryptoAPI.
Управление ключами OpenSSH OpenSSH key management
Большинство операций аутентификации в средах Windows выполняется с использованием имени пользователя и пароля. 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.
С другой стороны, среды Linux традиционно используют для аутентификации пару открытого и закрытого ключей, что делает ненужным использование угадываемых паролей. By comparison, Linux environments commonly use public-key/private-key pairs to drive authentication which doesn’t require the use of guessable passwords. OpenSSH содержит средства, поддерживающие такой сценарий: OpenSSH includes tools to help support this, specifically:
- ssh-keygen для создания защищенных ключей; ssh-keygen for generating secure keys
- ssh-agent и ssh-add для защищенного хранения закрытых ключей; ssh-agent and ssh-add for securely storing private keys
- scp и sftp для защищенного копирования файлов открытого ключа при первом использовании сервера. scp and sftp to securely copy public key files during initial use of a server
В этом документе описано, как использовать эти средства в Windows для перехода на аутентификацию с использованием ключей по протоколу SSH. This document provides an overview of how to use these tools on Windows to begin using key authentication with SSH. Если вы ничего не знаете об управлении ключами через SSH, мы настоятельно рекомендуем ознакомиться с документом NIST IR 7966 о защите интерактивного и автоматизированного управления доступом через Secure Shell (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 на основе открытого ключа используются асимметричные алгоритмы шифрования для создания двух файлов ключей, один из которых считается закрытым, а второй открытым. 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. Если кто-то получит ваш закрытый ключ, он сможет войти от вашего имени на любой сервер с поддержкой SSH, к которому у вас есть доступ. If someone acquires your private key, they can log in as you to any SSH server you have access to. Открытый ключ размещается на сервере SSH. Его можно свободно распространять, не компрометируя закрытый ключ. The public key is what is placed on the SSH server, and may be shared without compromising the private key.
Если на сервере SSH используется аутентификация с помощью ключей, сервер и клиент SSH сравнивают открытые ключи, связанные с предоставленным именем пользователя, с закрытым ключом. 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
Для открытых ключей действуют определенные требования к ACL, которые в среде Windows соответствуют предоставлению доступа только администраторам и системной учетной записи. Public keys have specific ACL requirements that, on Windows, equate to only allowing access to administrators and System. Чтобы упростить эту задачу, To make this easier,
- был создан модуль PowerShell OpenSSHUtils для корректной настройки ACL для ключей. Этот модуль нужно установить на сервере. The OpenSSHUtils PowerShell module has been created to set the key ACLs properly, and should be installed on the server
- При первом использовании sshd будет автоматически создана пара ключей для узла. On first use of sshd, the key pair for the host will be automatically generated. Если ssh-agent в этот момент работает, ключи будут автоматически добавлены в локальное хранилище. If ssh-agent is running, the keys will be automatically added to the local store.
Чтобы упростить аутентификацию на сервере SSH, выполните следующие команды в командной строке PowerShell с повышенными привилегиями: To make key authentication easy with an SSH server, run the following commands from an elevated PowerShell prompt:
Так как со службой sshd пользователи не связаны, ключи узла сохраняются в папке \ProgramData\ssh. 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. Выполните ssh-keygen в командной строке PowerShell или cmd, чтобы создать файлы ключей. From PowerShell or cmd, use ssh-keygen to generate some key files.
Эта команда возвращает примерно такие выходные данные (где вместо username будет указано ваше имя пользователя). 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.
Теперь у вас есть пара открытого и закрытого ключей ED25519 (PUB-файлы содержат открытые ключи, а все остальные файлы нужны для закрытого ключа): Now you have a public/private ED25519 key pair (the .pub files are public keys and the rest are private keys):
Помните, что файлы закрытых ключей выполняют функцию пароля и должны защищаться так же тщательно. Remember that private key files are the equivalent of a password should be protected the same way you protect your password. Для этого, чтобы безопасно хранить закрытые ключи в контексте безопасности Windows, связанным с определенным именем входа Windows, используйте ssh-agent. To help with that, use ssh-agent to securely store the private keys within a Windows security context, associated with your Windows login. Запустите службу ssh-agent от имени администратора и выполните ssh-add, чтобы сохранить закрытый ключ. To do that, start the ssh-agent service as Administrator and use ssh-add to store the private key.
После этого при каждом выполнении аутентификации с этого клиента с использованием закрытого ключа, ssh-agent будет автоматически извлекать его и передавать клиенту SSH. 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.
Мы настоятельно рекомендуем создать резервную копию закрытого ключа в безопасном расположении, а затем удалить его из локальной системы после добавления в ssh-agent. 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
Чтобы использовать созданный ранее ключ пользователя, следует поместить открытый ключ на сервер в текстовый файл с именем authorized_keys в папке users\username\.ssh\. 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\. Для этого для безопасной передачи файлов в составе средств OpenSSH предоставляется служебная программа scp. The OpenSSH tools include scp, which is a secure file-transfer utility, to help with this.
Переместите содержимое открытого ключа (
.ssh\id_ed25519.pub) в текстовый файл с именем authorized_keys в папке
.ssh\ на нужном сервере или узле. 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.
В этом примере используется функция Repair-AuthorizedKeyPermissions модуля OpenSSHUtils, который вы ранее установили на узле согласно инструкциям выше. This example uses the Repair-AuthorizedKeyPermissions function in the OpenSSHUtils module which was previously installed on the host in the instructions above.
Эти действия завершают настройку, которая требуется для использования аутентификации SSH на основе ключей в среде Windows. These steps complete the configuration required to use key-based authentication with SSH on Windows. Теперь пользователь может подключаться к узлу sshd с любого клиента, где есть закрытый ключ. After this, the user can connect to the sshd host from any client that has the private key.