Linux generate ssh key
Авторизация по ключу SSH
SSH или Secure Shell — это зашифрованный протокол, который часто используется для взаимодействия и удаленного управления серверами. Если вы захотите что-либо сделать на удаленном сервере, скорее всего, вам придется воспользоваться SSH и работать через терминал.
В SSH существует несколько способов авторизации. Вы можете каждый раз вводить пароль пользователя или использовать более безопасный и надежный способ — ключи SSH. Что самое интересное, он более удобен для применения, вам даже не нужно будет вводить пароль. В этой статье мы рассмотрим как настраивается авторизация по ключу SSH.
Как работают ключи SSH?
SSH сервер может выполнять аутентификацию пользователей с помощью различных алгоритмов. Самый популярный — это аутентификация по паролю. Он достаточно прост, но не очень безопасный. Пароли передаются по безопасному каналу, но они недостаточно сложны для противостояния попыткам перебора. Вычислительная мощность современных систем в сочетании со специальными скриптами делают перебор очень простым. Конечно, существуют другие способы дополнительной безопасности, например, fail2ban, но аутентификация по ключу SSH более надежна.
Каждая пара ключей состоит из открытого и закрытого ключа. Секретный ключ сохраняется на стороне клиента и не должен быть доступен кому-либо еще. Утечка ключа позволит злоумышленнику войти на сервер, если не была настроена дополнительная аутентификация по паролю.
Открытый ключ используется для шифрования сообщений, которые можно расшифровать только закрытым ключом. Это свойство и используется для аутентификации с помощью пары ключей. Открытый ключ загружается на удаленный сервер, к которому необходимо получить доступ. Его нужно добавить в специальный файл
Когда клиент попытается выполнить проверку подлинности через этот ключ, сервер отправит сообщение, зашифрованное с помощью открытого ключа, если клиент сможет его расшифровать и вернуть правильный ответ — аутентификация пройдена.
Как создать ключи SSH?
Сначала необходимо создать ключи ssh для аутентификации на локальном сервере. Для этого существует специальная утилита ssh-keygen, которая входит в набор утилит OpenSSH. По умолчанию она создает пару 2048 битных RSA ключей, которая подойдет не только для SSH, но и для большинства других ситуаций.
И так, генерация ключей ssh выполняется командой:
Утилита предложит вам выбрать расположение ключей. По умолчанию ключи располагаются в папке
/.ssh/. Лучше ничего не менять, чтобы все работало по умолчанию и ключи автоматически подхватывались. Секретный ключ будет называться id_rsa, а публичный id_rsa.pub.
Затем утилита предложит ввести пароль для дополнительного шифрования ключа на диске. Его можно не указывать, если не хотите. Использование дополнительного шифрования имеет только один минус — необходимость вводить пароль, и несколько преимуществ:
- Пароль никогда не попадет в сеть, он используется только на локальной машине для расшифровки ключа. Это значит что перебор по паролю больше невозможен.
- Секретный ключ хранится в закрытом каталоге и у клиента ssh нет к нему доступа пока вы не введете пароль;
- Если злоумышленник хочет взломать аутентификацию по ключу SSH, ему понадобится доступ к вашей системе. И даже тогда ключевая фраза может стать серьезной помехой на его пути.
Но все же, это необязательное дополнение и если не хотите, то вы можете просто нажать Enter. Тогда доступ по ключу ssh будет выполняться автоматически и вам не нужно будет что-либо вводить.
Теперь у вас есть открытый и закрытый ключи SSH и вы можете использовать их для проверки подлинности. Дальше нам осталось разместить открытый ключ на удаленном сервере.
Загрузка ключа на сервер
Когда генерация ключей завершена, нам осталось только загрузить ключ на сервер. Для загрузки ключа можно использовать несколько способов. В некоторых случаях вы можете указать ключ в панели управления сервером, например, сPanel или любой другой. Но мы такой способ рассматривать не будем. Мы рассмотрим ручные способы.
Самый простой способ скопировать ключ на удаленный сервер — это использовать утилиту ssh-copy-id. Она тоже входит в пакет программ OpenSSH. Но для работы этого метода вам нужно иметь пароль доступа к серверу по SSH. Синтаксис команды:
При первом подключении к серверу система может его не распознать, поэтому вам нужно ввести yes. Затем введите ваш пароль пользователя на удаленном сервере. Утилита подключится к удаленному серверу, а затем использует содержимое ключа id.rsa.pub для загрузки его на сервер в файл
/.ssh/authorized_keys. Дальше вы можете выполнять аутентификацию с помощью этого ключа.
Если такой способ по какой-либо причине для вас не работает, вы можете скопировать ключ по ssh вручную. Мы создадим каталог
/.ssh, а затем поместим наш ключ в файл authorized_keys с помощью символа >>, это позволит не перезаписывать существующие ключи:
/.ssh/id_rsa.pub | ssh username@remote_host «mkdir -p
Здесь вам тоже нужно набрать yes, если вы подключаетесь к новому серверу, а затем ввести пароль. Теперь вы можете использовать созданный ключ для аутентификации на сервере:
Если вы не захотели создать ssh ключ с доступом по паролю, то вы сразу же будете авторизованы, что очень удобно. Иначе, сначала вам придется ввести фразу-пароль для расшифровки ключа.
Отключение проверки пароля
Если пароль больше не будет использоваться, то для увеличения безопасности системы лучше его вовсе отключить. Но убедитесь, что ключ надежно сохранен и вы его не потеряете, потому что по паролю вы больше не войдете. Авторизуйтесь на сервере, затем откройте конфигурационный файл /etc/ssh/sshd_config и найдите там директиву PasswordAuthenticatin. Нужно установить ее значение в No:
sudo vi /etc/ssh/sshd_config
Теперь сохраните файл и перезапустите службу ssh:
sudo service ssh restart
Дальше будет возможно только подключение по ключу ssh, пароль не будет приниматься.
Выводы
В этой статье мы рассмотрели как выполняется авторизация по ключу ssh, настройка ключей ssh и добавить ssh ключ. Теперь вы можете войти на сервер без ввода пароля. Если у вас остались вопросы, спрашивайте в комментариях!
ssh-keygen — 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.
-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.
Generating a new SSH key and adding it to the ssh-agent
After you’ve checked for existing SSH keys, you can generate a new SSH key to use for authentication, then add it to the ssh-agent.
In this article
If you don’t already have an SSH key, you must generate a new SSH key. If you’re unsure whether you already have an SSH key, check for existing keys.
If you don’t want to reenter your passphrase every time you use your SSH key, you can add your key to the SSH agent, which manages your SSH keys and remembers your passphrase.
Generating a new SSH key
Open Terminal Terminal Git Bash .
Paste the text below, substituting in your GitHub email address.
This creates a new ssh key, using the provided email as a label.
When you’re prompted to «Enter a file in which to save the key,» press Enter. This accepts the default file location.
At the prompt, type a secure passphrase. For more information, see «Working with SSH key passphrases».
Adding your SSH key to the ssh-agent
Before adding a new SSH key to the ssh-agent to manage your keys, you should have checked for existing SSH keys and generated a new SSH key. When adding your SSH key to the agent, use the default macOS ssh-add command, and not an application installed by macports, homebrew, or some other external source.
Start the ssh-agent in the background.
If you’re using macOS Sierra 10.12.2 or later, you will need to modify your
/.ssh/config file to automatically load keys into the ssh-agent and store passphrases in your keychain.
Add your SSH private key to the ssh-agent and store your passphrase in the keychain. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_rsa in the command with the name of your private key file.
Note: The -K option is Apple’s standard version of ssh-add , which stores the passphrase in your keychain for you when you add an ssh key to the ssh-agent.
If you don’t have Apple’s standard version installed, you may receive an error. For more information on resolving this error, see «Error: ssh-add: illegal option — K.»
If you have GitHub Desktop installed, you can use it to clone repositories and not deal with SSH keys. It also comes with the Git Bash tool, which is the preferred way of running git commands on Windows.
Ensure the ssh-agent is running:
- If you are using the Git Shell that’s installed with GitHub Desktop, the ssh-agent should be running.
If you are using another terminal prompt, such as Git for Windows, you can use the «Auto-launching the ssh-agent» instructions in «Working with SSH key passphrases», or start it manually:
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_rsa in the command with the name of your private key file.
Start the ssh-agent in the background.
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_rsa in the command with the name of your private key file.
Как создать ключ для авторизации по SSH и добавить его на сервер?
SSH-ключи используются для идентификации клиента при подключении к серверу по SSH-протоколу . Используйте этот способ вместо аутентификации по паролю.
SSH-ключи представляют собой пару — закрытый и открытый ключ. Закрытый должен храниться в закрытом доступе у клиента, открытый отправляется на сервер и размещается в файле authorized_keys.
Создание SSH-ключей в Linux на примере CentOS
На клиентской стороне должен быть установлен пакет ssh (openssh). На серверах FirstVDS с шаблонами по умолчанию необходимое ПО уже установлено.
На клиентском компьютере в командной строке выполните команду генерации ключей:
Введите путь файла, в который будут помещены ключи. Каталог по умолчанию указан в скобках, в примере /домашний_каталог/.ssh/id_rsa . Если хотите оставить расположение по умолчанию, нажмите Enter .
Пароль (passphrase) используется для ограничения доступа к закрытому ключу. Пароль усложнит использование ключа третьими лицами в случае утраты. Если не хотите использовать секретную фразу, нажмите Enter без заполнения строки.
Успешно сгенерировав пару ключей, вы увидите уведомление:
Открытый ключ хранится в файле /домашний_каталог/.ssh/id_rsa.pub , закрытый — /домашний_каталог/.ssh/id_rsa .
Скопируйте открытый ключ на сервер в файл /домашний_каталог/.ssh/authorized_keys . Одной строкой:
Или откройте этот файл на сервере редактором vi и вставьте строку с открытым ключом после ssh-rsa .
Ещё один способ скопировать ключ в authorized_keys — команда echo , которая помещает строку в конец файла.
Теперь можно отключить на сервере аутентификацию по паролю и использовать только SSH-ключи.
Создание SSH-ключей на Windows с PuTTYgen
Если вы используете ОС Windows, то подключиться по SSH к вашему (Linux) серверу можно через PuTTY или OpenSSH . Генерация ключей в этом случае выполняется также при помощи этих программ. В примере мы используем клиент PuTTY.
Запустите приложение PuTTYgen , которое устанавливается вместе с PuTTY.
Выберите тип ключа SSH2-RSA и нажмите Generate .
В процессе генерации ключей несколько раз произвольно проведите мышкой по экрану приложения для создания случайных величин, используемых для ключей.
После завершения создания ключей открытый ключ выводится на экран, закрытый хранится в памяти приложения. Чтобы сохранить эти ключи нажмите Save public key и Save private key . Укажите расположение файлов с ключами.
При сохранении закрытого ключа, если не заполнено поле Key passphrase , появится запрос «Хотите ли вы сохранить ключ без секретной фразы?»
Теперь открытый ключ необходимо скопировать на сервер в файл authorized_keys . Используйте WinSCP или другой клиент для работы с файлами на удалённом Linux-сервере. Вы можете скопировать файл с открытым ключом целиком на сервер, чтоб его копия хранилась в папке .ssh
Откройте файл authorized_keys через WinSCP и файл, в который вы сохранили открытый ключ (public), на локальном компьютере текстовым редактором. Скопируйте значение ключа, сохраните и закройте файл в WinSCP.
При запуске PuTTY укажите путь к закрытому ключу на локальном компьютере. Для этого во вкладке Connections → Auth выберите необходимый путь.
Теперь можно отключить на сервере аутентификацию по паролю и использовать только SSH-ключи.
Отключение аутентификации по паролю
Подключитесь к серверу по SSH, используя пароль, и откройте файл sshd_config для редактирования.
Убедитесь, что указан правильный путь к открытым ключам SSH, поставьте значение параметра PasswordAuthentication no .
Перезапустите службу sshd.
Подключитесь к серверу по SSH без использования пароля. Например, запустите PuTTY, проверьте, что во вкладке Connections -> Auth содержится путь к закрытому ключу и откройте подключение.
В случае успешной аутентификации по SSH-ключу вы получите доступ к командной строке сервера и сообщение вида Authenticating with public key «rsa-key-20170510» , где rsa-key-20170510 — имя применённого закрытого ключа, указанное вами в файле authorized_keys .
Ubuntu Documentation
Public and Private Keys
Public key authentication is more secure than password authentication. This is particularly important if the computer is visible on the internet. If you don’t think it’s important, try logging the login attempts you get for the next week. My computer — a perfectly ordinary desktop PC — had over 4,000 attempts to guess my password and almost 2,500 break-in attempts in the last week alone.
With public key authentication, the authenticating entity has a public key and a private key. Each key is a large number with special mathematical properties. The private key is kept on the computer you log in from, while the public key is stored on the .ssh/authorized_keys file on all the computers you want to log in to. When you log in to a computer, the SSH server uses the public key to «lock» messages in a way that can only be «unlocked» by your private key — this means that even the most resourceful attacker can’t snoop on, or interfere with, your session. As an extra security measure, most SSH programs store the private key in a passphrase-protected format, so that if your computer is stolen or broken in to, you should have enough time to disable your old public key before they break the passphrase and start using your key. Wikipedia has a more detailed explanation of how keys work.
Public key authentication is a much better solution than passwords for most people. In fact, if you don’t mind leaving a private key unprotected on your hard disk, you can even use keys to do secure automatic log-ins — as part of a network backup, for example. Different SSH programs generate public keys in different ways, but they all generate public keys in a similar format:
Key-Based SSH Logins
Key-based authentication is the most secure of several modes of authentication usable with OpenSSH, such as plain password and Kerberos tickets. Key-based authentication has several advantages over password authentication, for example the key values are significantly more difficult to brute-force, or guess than plain passwords, provided an ample key length. Other authentication methods are only used in very specific situations.
SSH can use either «RSA» (Rivest-Shamir-Adleman) or «DSA» («Digital Signature Algorithm») keys. Both of these were considered state-of-the-art algorithms when SSH was invented, but DSA has come to be seen as less secure in recent years. RSA is the only recommended choice for new keys, so this guide uses «RSA key» and «SSH key» interchangeably.
Key-based authentication uses two keys, one «public» key that anyone is allowed to see, and another «private» key that only the owner is allowed to see. To securely communicate using key-based authentication, one needs to create a key pair, securely store the private key on the computer one wants to log in from, and store the public key on the computer one wants to log in to.
Using key based logins with ssh is generally considered more secure than using plain password logins. This section of the guide will explain the process of generating a set of public/private RSA keys, and using them for logging into your Ubuntu computer(s) via OpenSSH.
Generating RSA Keys
The first step involves creating a set of RSA keys for use in authentication.
This should be done on the client.
To create your public and private SSH keys on the command-line:
You will be prompted for a location to save the keys, and a passphrase for the keys. This passphrase will protect your private key while it’s stored on the hard drive:
Your public key is now available as .ssh/id_rsa.pub in your home folder.
Congratulations! You now have a set of keys. Now it’s time to make your systems allow you to login with them
Choosing a good passphrase
You need to change all your locks if your RSA key is stolen. Otherwise the thief could impersonate you wherever you authenticate with that key.
An SSH key passphrase is a secondary form of security that gives you a little time when your keys are stolen. If your RSA key has a strong passphrase, it might take your attacker a few hours to guess by brute force. That extra time should be enough to log in to any computers you have an account on, delete your old key from the .ssh/authorized_keys file, and add a new key.
Your SSH key passphrase is only used to protect your private key from thieves. It’s never transmitted over the Internet, and the strength of your key has nothing to do with the strength of your passphrase.
The decision to protect your key with a passphrase involves convenience x security. Note that if you protect your key with a passphrase, then when you type the passphrase to unlock it, your local computer will generally leave the key unlocked for a time. So if you use the key multiple times without logging out of your local account in the meantime, you will probably only have to type the passphrase once.
If you do adopt a passphrase, pick a strong one and store it securely in a password manager. You may also write it down on a piece of paper and keep it in a secure place. If you choose not to protect the key with a passphrase, then just press the return when ssh-keygen asks.
Key Encryption Level
Note: The default is a 2048 bit key. You can increase this to 4096 bits with the -b flag (Increasing the bits makes it harder to crack the key by brute force methods).
Password Authentication
The main problem with public key authentication is that you need a secure way of getting the public key onto a computer before you can log in with it. If you will only ever use an SSH key to log in to your own computer from a few other computers (such as logging in to your PC from your laptop), you should copy your SSH keys over on a memory stick, and disable password authentication altogether. If you would like to log in from other computers from time to time (such as a friend’s PC), make sure you have a strong password.
Transfer Client Key to Host
The key you need to transfer to the host is the public one. If you can log in to a computer over SSH using a password, you can transfer your RSA key by doing the following from your own computer:
Where and should be replaced by your username and the name of the computer you’re transferring your key to.
Due to this bug, you cannot specify a port other than the standard port 22. You can work around this by issuing the command like this: ssh-copy-id " @ -p
". If you are using the standard port 22, you can ignore this tip.
Another alternative is to copy the public key file to the server and concatenate it onto the authorized_keys file manually. It is wise to back that up first:
You can make sure this worked by doing:
You should be prompted for the passphrase for your key:
Enter passphrase for key ‘/home/ /.ssh/id_rsa’:
Enter your passphrase, and provided host is configured to allow key-based logins, you should then be logged in as usual.
Troubleshooting
Encrypted Home Directory
If you have an encrypted home directory, SSH cannot access your authorized_keys file because it is inside your encrypted home directory and won’t be available until after you are authenticated. Therefore, SSH will default to password authentication.
To solve this, create a folder outside your home named /etc/ssh/ (replace » » with your actual username). This directory should have 755 permissions and be owned by the user. Move the authorized_keys file into it. The authorized_keys file should have 644 permissions and be owned by the user.
Then edit your /etc/ssh/sshd_config and add:
Finally, restart ssh with:
The next time you connect with SSH you should not have to enter your password.
username@host’s password:
If you are not prompted for the passphrase, and instead get just the
prompt as usual with password logins, then read on. There are a few things which could prevent this from working as easily as demonstrated above. On default Ubuntu installs however, the above examples should work. If not, then check the following condition, as it is the most frequent cause:
On the host computer, ensure that the /etc/ssh/sshd_config contains the following lines, and that they are uncommented;
If not, add them, or uncomment them, restart OpenSSH, and try logging in again. If you get the passphrase prompt now, then congratulations, you’re logging in with a key!
Permission denied (publickey)
If you’re sure you’ve correctly configured sshd_config, copied your ID, and have your private key in the .ssh directory, and still getting this error:
Permission denied (publickey).
Chances are, your /home/ or
/.ssh/authorized_keys permissions are too open by OpenSSH standards. You can get rid of this problem by issuing the following commands:
Error: Agent admitted failure to sign using the key.
This error occurs when the ssh-agent on the client is not yet managing the key. Issue the following commands to fix:
This command should be entered after you have copied your public key to the host computer.
Debugging and sorting out further problems
The permissions of files and folders is crucial to this working. You can get debugging information from both the client and server.
if you think you have set it up correctly , yet still get asked for the password, try starting the server with debugging output to the terminal.
To connect and send information to the client terminal
Where to From Here?
No matter how your public key was generated, you can add it to your Ubuntu system by opening the file .ssh/authorized_keys in your favourite text editor and adding the key to the bottom of the file. You can also limit the SSH features that the key can use, such as disallowing port-forwarding or only allowing a specific command to be run. This is done by adding «options» before the SSH key, on the same line in the authorized_keys file. For example, if you maintain a CVS repository, you could add a line like this:
When the user with the specified key logged in, the server would automatically run /usr/bin/cvs server, ignoring any requests from the client to run another command such as a shell. For more information, see the sshd man page. /755
SSH/OpenSSH/Keys (последним исправлял пользователь larsnooden 2015-07-30 19:26:16)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details