- Как сгенерировать открытый/закрытый SSH-ключ в Linux
- 4.3 Git на сервере — Генерация открытого SSH ключа
- Генерация открытого SSH ключа
- How To Generate Ssh Key With ssh-keygen In Linux?
- Public Cryptography
- Configuration Files
- Generate Keys with ssh-keygen
- Set Key File Name and Path
- Encrypt Private SSH Keys with ssh-keygen
- Generate RSA Key with ssh-keygen
- Generate DSA Key with ssh-keygen
- Set Key Size for ssh-keygen
- Write Keys To File with ssh-keygen
- Encrypt Generated Keys with ssh-keygen
- How to use ssh-keygen to generate a new SSH key
- Contents
- What Is ssh-keygen ?
- SSH Keys and Public Key Authentication
- Creating an SSH Key Pair for User Authentication
- Choosing an Algorithm and Key Size
- Specifying the File Name
- Copying the Public Key to the Server
- Adding the Key to SSH Agent
- Creating Host Keys
- Using X.509 Certificates for Host Authentication
- Using OpenSSH’s Proprietary Certificates
- Key Management Requires Attention
- Make Sure There Is Enough Randomness
- General Purpose Systems
- Embedded Devices and Internet of Things
- Command and Option Summary
Как сгенерировать открытый/закрытый SSH-ключ в Linux
Если вы часто используете ssh для подключения к удаленному хосту, одним из способов обеспечения безопасности соединения является применение открытого/закрытого SSH-ключа, так как при этом по сети не передается никакой пароль и система устойчива к атакам методом «грубой силы».
Создать открытый/закрытый SSH-ключ в Linux очень просто.
1. Откройте терминал. Введите:
Альтернативой является использование для создания ключа технологии DSA (Digital Signing Algorithm):
Примечание: Было много дебатов о том, что безопаснее, DSA или RSA. По моему мнению, если только вы не любитель копаться в технических подробностях, большой разницы между этими технологиями нет. Обе работают хорошо.
2. На нижеследующем скриншоте вы видите предложение указать место для сохранения ключа. По умолчанию это папка .ssh в вашей домашней директории. Для того, чтобы согласиться с настройками по умолчанию, просто нажмите «Enter».
3. Далее, вас попросят ввести идентификационную фразу. Это не идентификационная фраза для соединения с удаленным хостом. Это идентификационная фраза для разблокировки закрытого ключа, поэтому она не поможет вам получить доступ к удаленному серверу, даже если на нем хранится ваш закрытый ключ. Ввод идентификационной фразы не является обязательным. Чтобы оставить ее пустой, просто нажмите «Enter».
4. Теперь ваши открытый и закрытый SSH-ключи должны быть сгенерированы. Откройте файловый менеджер и перейдите в директорию .ssh. Вы должны увидеть два файла: id_rsa и id_rsa.pub.
5. Загрузите файл id_rsa.pub в домашнюю директорию вашего удаленного хоста (предполагается, что удаленный хост работает под Linux). Подключитесь к удаленному хосту с помощью SSH и переместите открытый ключ в его целевую директорию с помощью команд:
6. Оставаясь на удаленном хосте, откройте конфигурационный файл SSH:
Убедитесь, что следующие атрибуты имеют корректные значения:
Нажмите «ctrl + o», чтобы сохранить изменения, затем «ctrl + x», чтобы закрыть файл.
7. И последнее, перезапустите сервер SSH на удаленном хосте:
На этом все. Теперь вы можете соединяться со своим удаленным хостом с помощью команды:
Источник
4.3 Git на сервере — Генерация открытого SSH ключа
Генерация открытого SSH ключа
Как отмечалось ранее, многие Git-серверы используют аутентификацию по открытым SSH-ключам. Для того чтобы предоставить открытый ключ, каждый пользователь в системе должен его сгенерировать, если только этого уже не было сделано ранее. Этот процесс аналогичен во всех операционных системах. Сначала вам стоит убедиться, что у вас ещё нет ключа. По умолчанию пользовательские SSH ключи сохраняются в каталоге
/.ssh домашнем каталоге пользователя. Вы можете легко проверить наличие ключа перейдя в этот каталог и посмотрев его содержимое:
Ищите файл с именем id_dsa или id_rsa и соответствующий ему файл с расширением .pub . Файл с расширением .pub — это ваш открытый ключ, а второй файл — ваш приватный ключ. Если указанные файлы у вас отсутствуют (или даже нет каталога .ssh ), вы можете создать их используя программу ssh-keygen , которая входит в состав пакета SSH в системах Linux/Mac, а для Windows поставляется вместе с Git:
Сначала программа попросит указать расположение файла для сохранения ключа ( .ssh/id_rsa ), затем дважды ввести пароль для шифрования. Если вы не хотите вводить пароль каждый раз при использовании ключа, то можете оставить его пустым или использовать программу ssh-agent . Если вы решили использовать пароль для приватного ключа, то настоятельно рекомендуется использовать опцию -o , которая позволяет сохранить ключ в формате, более устойчивом ко взлому методом подбора, чем стандартный формат.
Теперь каждый пользователь должен отправить свой открытый ключ вам или тому, кто администрирует Git-сервер (подразумевается, что ваш SSH-сервер уже настроен на работу с открытыми ключами). Для этого достаточно скопировать содержимое файла с расширением .pub и отправить его по электронной почте. Открытый ключ выглядит примерно так:
Источник
How To Generate Ssh Key With ssh-keygen In Linux?
Ssh is a secure and popular protocol for managing different types of IT devices like Linux systems, network devices, etc. What makes ssh secure is the encryption of network traffic. Network traffic is encrypted with different types of encryption algorithms. There is also user authentication done with encryption algorithms. These algorithms need keys to operate. Keys are generally produced with auxiliary tools. ssh-keygen is a defacto tool used by ssh and other applications to create different types of keys. In this tutorial, we will look at how it works.
Public Cryptography
We will look at some terms and concepts about public cryptography in this part. In public cryptography, there are two keys. These keys are called public and private. Public keys are known by others to create encrypted data. Private keys are only known by its owner. Data are encrypted by public keys by anyone but only the private key owner can decrypt the message. So keeping the private keys is important. ssh-keygen is used to create a different type of public-private keys.
Configuration Files
There are some configurations files those used by ssh. We will look at the public-private keys related configuration files.
/.ssh/identity.pub contains the protocol version 1 RSA public key
/.ssh/id_dsa c ontains the protocol version 2 DSA authentication identity of the user.
/.ssh/id_dsa.pub c ontains the protocol version 2 DSA public key for authentication
/.ssh/id_rsa c ontains the protocol version 2 RSA authentication identity of the user
/.ssh/id_rsa.pub c ontains the protocol version 2 RSA public key for authentication
Generate Keys with ssh-keygen
Generating keys without any parameter is very easy. This will generate default values and options a key. This will take 3 steps just enter after issuing the sshkeygen command.
Set Key File Name and Path
Now we will specify the path key files to be saved. We do not enter a path if we want to use default path which is
Encrypt Private SSH Keys with ssh-keygen
Now we will enter passphrase but we will not. Where our private key will
Again do not enter passphrase
Generate RSA Key with ssh-keygen
In previous example we have generated ssh key with default settings. The default settings was like below.
But we can specify the public key algorithm explicitly by using -t option like below.
Generate DSA Key with ssh-keygen
DSA is a less popular but useful public key algorithm. DSA keys can be generated by specifying key types with -t dsa
Set Key Size for ssh-keygen
Keys have different size for different purposes. Bigger size means more security but brings more processing need which is a trade of. We can specify the size of the keys according to our needs with -s option and the length of key. The size count specifies bits in a key. So following example will create 1024 bit key.
Write Keys To File with ssh-keygen
Created keys will be written to the
/.ssh with related name. This default behavior can be changed with -f option and file with path. In this example we will write keys to the current users home directory.
As we can see the path is not asked to us because we have all ready provided explicitly.
Encrypt Generated Keys with ssh-keygen
Private keys must be protected. There are different ways to protect privates. We should use symmetric cryptography to crypt private key. ssh-key all ready provide this feature. We will set a password to access the private key. In an interactive run, the passphrase is asked but we can also specify explicitly while calling the command with -N option like below. We will provide passphrase in cleartext. This passphrase also saved in a bash history file which will create a security vulnerability. Keep these while using option based encryption of public keys.
Источник
How to use ssh-keygen to generate a new SSH key
This page is about the OpenSSH version of ssh-keygen . For Tectia SSH , see here . If you wish to generate keys for PuTTY , see PuTTYgen on Windows or PuTTYgen on Linux .
Contents
What Is ssh-keygen ?
Ssh-keygen is a tool for creating new authentication key pairs for SSH. Such key pairs are used for automating logins, single sign-on, and for authenticating hosts.
SSH Keys and Public Key Authentication
The SSH protocol uses public key cryptography for authenticating hosts and users. The authentication keys, called SSH keys , are created using the keygen program.
SSH introduced public key authentication as a more secure alternative to the older .rhosts authentication. It improved security by avoiding the need to have password stored in files, and eliminated the possibility of a compromised server stealing the user’s password.
However, SSH keys are authentication credentials just like passwords. Thus, they must be managed somewhat analogously to user names and passwords. They should have a proper termination process so that keys are removed when no longer needed.
Creating an SSH Key Pair for User Authentication
The simplest way to generate a key pair is to run ssh-keygen without arguments. In this case, it will prompt for the file in which to store keys. Here’s an example:
First, the tool asked where to save the file. SSH keys for user authentication are usually stored in the user’s .ssh directory under the home directory. However, in enterprise environments, the location is often different. The default key file name depends on the algorithm, in this case id_rsa when using the default RSA algorithm. It could also be, for example, id_dsa or id_ecdsa .
Then it asks to enter a passphrase . The passphrase is used for encrypting the key, so that it cannot be used even if someone obtains the private key file. The passphrase should be cryptographically strong. Our online random password generator is one possible tool for generating strong passphrases.
Choosing an Algorithm and Key Size
SSH supports several public key algorithms for authentication keys. These include:
rsa — an old algorithm based on the difficulty of factoring large numbers. A key size of at least 2048 bits is recommended for RSA; 4096 bits is better. RSA is getting old and significant advances are being made in factoring. Choosing a different algorithm may be advisable. It is quite possible the RSA algorithm will become practically breakable in the foreseeable future. All SSH clients support this algorithm.
dsa — an old US government Digital Signature Algorithm. It is based on the difficulty of computing discrete logarithms. A key size of 1024 would normally be used with it. DSA in its original form is no longer recommended.
ecdsa — a new Digital Signature Algorithm standarized by the US government, using elliptic curves. This is probably a good algorithm for current applications. Only three key sizes are supported: 256, 384, and 521 (sic!) bits. We would recommend always using it with 521 bits, since the keys are still small and probably more secure than the smaller keys (even though they should be safe as well). Most SSH clients now support this algorithm.
ed25519 — this is a new algorithm added in OpenSSH. Support for it in clients is not yet universal. Thus its use in general purpose applications may not yet be advisable.
The algorithm is selected using the -t option and key size using the -b option. The following commands illustrate:
Specifying the File Name
Normally, the tool prompts for the file in which to store the key. However, it can also be specified on the command line using the -f option.
Copying the Public Key to the Server
To use public key authentication, the public key must be copied to a server and installed in an authorized_keys file. This can be conveniently done using the ssh-copy-id tool. Like this:
Once the public key has been configured on the server, the server will allow any connecting user that has the private key to log in. During the login process, the client proves possession of the private key by digitally signing the key exchange.
Adding the Key to SSH Agent
ssh-agent is a program that can hold a user’s private key, so that the private key passphrase only needs to be supplied once. A connection to the agent can also be forwarded when logging into a server, allowing SSH commands on the server to use the agent running on the user’s desktop.
For more information on using and configuring the SSH agent, see the ssh-agent page.
Creating Host Keys
The tool is also used for creating host authentication keys. Host keys are stored in the /etc/ssh/ directory.
Host keys are just ordinary SSH key pairs. Each host can have one host key for each algorithm. The host keys are almost always stored in the following files:
The host keys are usually automatically generated when an SSH server is installed. They can be regenerated at any time. However, if host keys are changed, clients may warn about changed keys. Changed keys are also reported when someone tries to perform a man-in-the-middle attack. Thus it is not advisable to train your users to blindly accept them. Changing the keys is thus either best done using an SSH key management tool that also changes them on clients, or using certificates.
Using X.509 Certificates for Host Authentication
OpenSSH does not support X.509 certificates. Tectia SSH does support them. X.509 certificates are widely used in larger organizations for making it easy to change host keys on a period basis while avoiding unnecessary warnings from clients. They also allow using strict host key checking, which means that the clients will outright refuse a connection if the host key has changed.
Using OpenSSH’s Proprietary Certificates
OpenSSH has its own proprietary certificate format, which can be used for signing host certificates or user certificates. For user authentication, the lack of highly secure certificate authorities combined with the inability to audit who can access a server by inspecting the server makes us recommend against using OpenSSH certificates for user authentication.
However, OpenSSH certificates can be very useful for server authentication and can achieve similar benefits as the standard X.509 certificates. However, they need their own infrastructure for certificate issuance. See more information on certificate authentication .
Key Management Requires Attention
It is easy to create and configure new SSH keys. In the default configuration, OpenSSH allows any user to configure new keys. The keys are permanent access credentials that remain valid even after the user’s account has been deleted.
In organizations with more than a few dozen users, SSH keys easily accumulate on servers and service accounts over the years. We have seen enterprises with several million keys granting access to their production servers. It only takes one leaked, stolen, or misconfigured key to gain access.
In any larger organization, use of SSH key management solutions is almost necessary. SSH keys should also be moved to root-owned locations with proper provisioning and termination processes. For more information, see how to manage SSH keys . A widely used SSH key management tool for OpenSSH is Universal SSH Key Manager .
Practically all cybersecurity regulatory frameworks require managing who can access what. SSH keys grant access, and fall under this requirement. This, organizations under compliance mandates are required to implement proper management processes for the keys. NIST IR 7966 is a good starting point.
Make Sure There Is Enough Randomness
It is important to ensure there is enough unpredictable entropy in the system when SSH keys are generated. There have been incidents when thousands of devices on the Internet have shared the same host key when they were improperly configured to generate the key without proper randomness.
General Purpose Systems
On general purpose computers, randomness for SSH key generation is usually not a problem. It may be something of an issue when initially installing the SSH server and generating host keys, and only people building new Linux distributions or SSH installation packages generally need to worry about it.
Our recommendation is to collect randomness during the whole installation of the operating system, save that randomness in a random seed file. Then boot the system, collect some more randomness during the boot, mix in the saved randomness from the seed file, and only then generate the host keys. This maximizes the use of the available randomness. And make sure the random seed file is periodically updated, in particular make sure that it is updated after generating the SSH host keys.
Many modern general-purpose CPUs also have hardware random number generators. This helps a lot with this problem. The best practice is to collect some entropy in other ways, still keep it in a random seed file, and mix in some entropy from the hardware random number generator. This way, even if one of them is compromised somehow, the other source of randomness should keep the keys secure.
Embedded Devices and Internet of Things
Available entropy can be a real problem on small IoT devices that don’t have much other activity on the system. They may just not have the mechanical randomness from disk drive mechanical movement timings, user-caused interrupts, or network traffic. Furthermore, embedded devices often run on low-end processors that may not have a hardware random number generator.
The availability of entropy is also critically important when such devices generate keys for HTTPS.
Our recommendation is that such devices should have a hardware random number generator. If the CPU does not have one, it should be built onto the motherboard. The cost is rather small.
Command and Option Summary
Here’s a summary of commonly used options to the keygen tool:
-b “Bits” This option specifies the number of bits in the key. The regulations that govern the use case for SSH may require a specific key length to be used. In general, 2048 bits is considered to be sufficient for RSA keys.
-e “Export” This option allows reformatting of existing keys between the OpenSSH key file format and the format documented in RFC 4716 , “SSH Public Key File Format”.
-p “Change the passphrase” This option allows changing the passphrase of a private key file with [-P old_passphrase] and [-N new_passphrase] , [-f keyfile] .
-t “Type” This option specifies the type of key to be created. Commonly used values are: — rsa for RSA keys — dsa for DSA keys — ecdsa for elliptic curve DSA keys
-i «Input» When ssh-keygen is required to access an existing key, this option designates the file.
-f «File» Specifies name of the file in which to store the created key.
-N «New» Provides a new passphrase for the key.
-P «Passphrase» Provides the (old) passphrase when reading a key.
-c «Comment» Changes the comment for a keyfile.
-p Change the passphrase of a private key file.
-q Silence ssh-keygen.
-v Verbose mode.
-l «Fingerprint» Print the fingerprint of the specified public key.
-B «Bubble babble» Shows a «bubble babble» (Tectia format) fingerprint of a keyfile.
-F Search for a specified hostname in a known_hosts file.
-R Remove all keys belonging to a hostname from a known_hosts file.
-y Read a private OpenSSH format file and print an OpenSSH public key to stdout.
This only listed the most commonly used options. For full usage, including the more exotic and special-purpose options, use the man ssh-keygen command.
Together with our customers, our mission is to secure their digital business on on-premises, cloud, and hybrid ecosystems cost-efficiently, at scale, and without disruptions to their operations or business continuity.
Источник