Как сгенерить ssh key linux
Перейти к содержимому

Как сгенерить ssh key linux

  • автор:

Авторизация по ключу 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 ключ. Теперь вы можете войти на сервер без ввода пароля. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

How to Set Up SSH Keys

How to Set Up SSH Keys

In this tutorial you will learn how to set up SSH keys on your local device and use the generated pair of keys for connecting to a remote server. This method is more convenient and provides a more secure way of connecting to the remote server/machine than simply using a password.

Additionally, you can check out this tutorial on “How to Connect to your VPS using Putty”. It will be very helpful if you are running Windows OS and not sure how to connect to the server: How to Connect to your VPS using Putty.

What Will You Need?

Before you begin this guide you’ll need the following:

  • Access to your local device
  • Access to the remote device
  • A terminal suitable for SSH connection

Step 1 — Generating the SSH Keys

You can generate and set up the RSA keys on both Windows and Linux/Unix systems using any kind of Terminal type of environment which your local device comes with.

After entering the Terminal, you will be taken to a window similar to this:

Main terminal window

Here you can start writing needed commands:

The first thing you need to do is generate the pair of keys on your local machine. You can do it with this simple command:

Once you enter this command, a few new questions will pop up:

Enter file in which to save the key (/home/tautvydas/.ssh/id_rsa):

Generally it is recommended to simply leave it as it is – press ENTER without typing anything – so that the key generator could create the key pair in the default location (in this tutorial I entered a different name tut_id to avoid duplicate keys, since my local device already had an id_rsa keys generated). Two questions which will pop up:

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Now for convenience reasons, I like to leave those empty as well. That way, after setting the keys up with your remote server, you won’t need to use any kind of password to log in. You will simply enter the ssh user@serverip command and it will log you in as long as the keys are properly set up. But if you need even more security, you can enter a passphrase in this section. If you choose this option, you will need to enter the password every time you connect to the remote device.

That is basically it, you should see something like this in your Terminal:

Main terminal window

Your generated Image WILL look different from mine. As well as the key fingerprint.

Important! There are two keys created here (private and public): tut_id and tut_id.pub (in your case, should be id_rsa and id_rsa.pub). Take a very good care of the file named id_rsa (this is the private key), have it only on your local device and do not give it to anyone.

Other file, id_rsa.pub must be uploaded to your remote machine. So for example, if you and your friend is working on the same project in the same remote server, you both can put your public keys in that remote server. In the next step, we will learn how to do that.

Step 2 — Copying the Public Key to Your Remote Server

After generating the RSA key pair, we have to put our public key to the remote virtual server.

There is a simple command which will put your public key directly to the remote server’s authorized_keys file (this file keeps all the public keys:

Here instead of serverip, you have to enter your remote server’s IP address and instead of user, you have to enter the username of the server you are connecting to.

After entering the command, you should be greeted with a Warning message similar to this:

Type in yes in the command line and hit ENTER. This message appears only the first time you are performing this action.

Another message will pop up:

Here you must enter the password of remote server user (in most cases username is root). After entering the password, that should basically be it. You will be greeted with another message:

as the new public key has been added to your remote server. Now every time you log into your remote server, you won’t be prompted for a password (unless you set up a passphrase for your RSA key in the generation process).

Conclusion

In this tutorial, you have learned how to generate SSH private/public key pair and use those keys with your remote server in order to set up a more secure connection than simply using the password.

Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.

Ключи ssh

В SSH поддерживается четыре алгоритма аутентификации по открытым ключам:

  • DSA,
    • размер ключей DSA не может превышать 1024, его следует отключить
    • следует создавать ключ большого размера: 4096 бит
    • ECDSA завязан на технологиях NIST, его следует отключить
    • используется пока не везде
    1.1.1 Отключение ключей у сервера sshd
    • Ключи отключаются у сервера.
    • Если просто удалить ключ, он будет повторно создан при перезапуске демона.
      • Можно воспользоваться обходным путём с создать заведомо нерабочую символическую ссылку, которая помешает создать и использовать ключ:
      1.1.2 Создание серверных ключей
      • Для RSA следует создать ключ большего размера:
      1.1.3 Создание клиентских ключей
      • Для создания клиентских ключей лучше использовать команды:

      1.2 Симметричные шифры

      • Из 15 поддерживаемых в SSH алгоритмов симметричного шифрования, безопасными можно считать:
        • chacha20-poly1305 ;
        • aes*-ctr ;
        • aes*-gcm .
        1.2.1 Конфигурация сервера
        • В /etc/ssh/sshd_config рекомендуется добавить:
        1.2.2 Конфигурация для клиентов
        • В /etc/ssh/ssh_config рекомендуется добавить:

        1.3 Обмен ключами

        • Применяемые в SSH методы обмена ключей DH (Diffie-Hellman) и ECDH (Elliptic Curve Diffie-Hellman) можно считать безопасными.
        • Из 8 поддерживаемых в SSH протоколов обмена ключами вызывают подозрения три, основанные на рекомендациях NIST:
          • ecdh-sha2-nistp256 ;
          • ecdh-sha2-nistp384 ;
          • ecdh-sha2-nistp521 .
          1.3.1 Настройка сервера
          • В /etc/ssh/sshd_config рекомендуется указать:
          1.3.2 Настройка клиента
          • В /etc/ssh/ssh_config рекомендуется добавить

          2 Файлы ssh-ключей

          По умолчанию пользовательские ssh-ключи сохраняются в каталоге

          /.ssh в домашнем каталоге пользователя.

          Убедитесь, что у вас ещё нет ключа.

          Файлы закрытых ключей имеют названия типа id_<алгоритм> (например, id_dsa , id_rsa ).

          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 <username> and <host> 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 "<username>@<host> -p <port_nr>". 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 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/<username> (replace "<username>" 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:

          Chances are, your /home/<user> 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 (последним исправлял пользователь mobile-access-5d6aa9-200 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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *