One place for hosting & domains

      Troubleshooting SSH


      Updated by Linode Written by Linode

      This guide presents troubleshooting strategies for when you can’t connect to your Linode via SSH. If you currently cannot ping your Linode, then your server also likely has more basic connection issues. If this is the case, you should instead follow the Troubleshooting Basic Connection Issues guide. If you restore basic networking to your Linode but still can’t access SSH, return to this guide.

      If you can access SSH but not other services, refer to the Troubleshooting Web Servers, Databases, and Other Services guide.

      Where to go for help outside this guide

      This guide explains how to use different troubleshooting commands on your Linode. These commands can produce diagnostic information and logs that may expose the root of your connection issues. For some specific examples of diagnostic information, this guide also explains the corresponding cause of the issue and presents solutions for it.

      If the information and logs you gather do not match a solution outlined here, consider searching the Linode Community Site for posts that match your system’s symptoms. Or, post a new question in the Community Site and include your commands’ output.

      Linode is not responsible for the configuration or installation of software on your Linode. Refer to Linode’s Scope of Support for a description of which issues Linode Support can help with.

      Before You Begin

      Before troubleshooting your SSH service, familiarize yourself with the Linode Shell.

      The Linode Shell (Lish)

      Lish is a shell that provides access to your Linode’s serial console. Lish does not establish a network connection to your Linode, so you can use it when your networking is down or SSH is inaccessible. While troubleshooting SSH, all commands you enter on your Linode will be performed from the Lish console.

      To learn about Lish in more detail, and for instructions on how to connect to your Linode via Lish, review the Using the Linode Shell (Lish) guide. In particular, using your web browser is a fast and simple way to access Lish.

      Forgotten your Password?

      If you have forgotten your Linux user’s password, you will not be able to log in with Lish. You can reset the root password for your Linode with these instructions. If you are logged in as root, you can change the password of another user with the passwd command:

      passwd <username>
      

      If you reset your password and can log in with Lish, try logging in with SSH, as that may have been the cause of your connection problems.

      Troubleshoot Unresponsive SSH Connections

      If your SSH connection attempts are timing out or are being immediately rejected, then your SSH daemon may not be running, or your firewall may be blocking SSH connections. This section will help troubleshoot these issues.

      If your connections are not timing out or being rejected, or if you are able to resolve these issues but you still can’t access SSH because of rejected login attempts, then continue to the Troubleshoot Rejected SSH Logins section.

      Is SSH Running?

      1. To check on the status of your SSH daemon, run:

        DistributionCommand                                           
        systemd systems (Arch, Ubuntu 16.04+, Debian 8+, CentOS 7+, etc)sudo systemctl status sshd -l
        CentOS 6sudo service sshd status
        Ubuntu 14.04, Debian 7sudo service ssh status
      2. If the command reports the service is running, review the Is SSH Running on a Non-Standard Port? section.

      3. If the command reports the service is not running, then try restarting it:

        DistributionCommand
        systemd systemssudo systemctl restart sshd
        CentOS 6sudo service sshd restart
        Ubuntu 14.04, Debian 7sudo service ssh restart
      4. Check the status of the service again. If it’s still not running, view the logs for the service:

        DistributionCommand
        systemd systemssudo journalctl -u sshd -u ssh
        CentOS 6less /var/log/secure
        Ubuntu 14.04, Debian 7less /var/log/auth.log

        Note

        Review the journalctl and less guides for help with navigating your logs when using those commands.
      5. Review the Is Another Service Bound on the Same Port? section. Then:

        • If you can start the SSH service successfully, but your connections still time out or are rejected, then review your firewall rules.

        • If you can’t get the service to start, try pasting your logs into a search engine or searching for your logs in the Linode Community Site to see if anyone else has run into similar issues. If you don’t find any results, you can try asking about your issues in a new post on the Linode Community Site.

      Is SSH Running on a Non-Standard Port?

      Run netstat on your Linode to check which port is used by SSH:

      sudo netstat -plntu | grep ssh
      tcp        0      0 0.0.0.0:41              0.0.0.0:*               LISTEN      4433/sshd
      tcp6       0      0 :::41                   :::*                    LISTEN      4433/sshd
      

      This example output shows that SSH is running on port 41. You can connect to SSH by manually specifying this port:

      ssh [email protected] -p 41
      

      Alternatively, you can bind SSH on the standard port (22).

      Is Another Service Bound on the Same Port?

      Check your SSH logs for a message that looks like:

        
      Jan 23 10:29:52 localhost sshd[4370]: error: Bind to port 22 on 0.0.0.0 failed: Address already in use.
      
      

      This error indicates that another service on your system is already using the same port that SSH binds to, and so SSH can’t start. To resolve this issue, choose one of the following solutions.

      • Bind SSH to a different port

        Follow instructions for setting SSH’s port number, and specify a different number than the one that is already in-use.

      • Stop the other service

        1. Use the netstat command to discover which other process is using the same port:

          sudo netstat -plntu | grep :22
          
          tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      4433/some-other-service
          tcp6       0      0 :::22                   :::*                    LISTEN      4433/some-other-service
          
        2. Stop and disable that other service:

          sudo systemctl stop some-other-service
          sudo systemctl disable some-other-service
          

          Or, kill the process using the process ID listed next to the process name in the output from netstat.

      • Assign a different port to the other service

        1. Use the netstat command to find out what service is bound to the same port.

        2. Then, change the configuration for that service to use a different port.

        3. Restart SSH.

      Bind SSH to a Port Number

      1. Open /etc/ssh/sshd_config in your editor. Search for a line in this file that declares the port for SSH:

        /etc/ssh/sshd_config
      2. Uncomment this line and provide a different number.

      3. Save the file and restart the SSH service.

      Review Firewall Rules

      If your service is running but your connections still fail, your firewall (which is likely implemented by the iptables software) may be blocking the connections. To review your current firewall ruleset, run:

      sudo iptables-save # displays IPv4 rules
      sudo ip6tables-save # displays IPv6 rules
      

      Note

      Your deployment may be running FirewallD or UFW, which are frontends used to more easily manage your iptables rules. Run these commands to find out if you are running either package:

      sudo ufw status
      sudo firewall-cmd --state
      

      Review How to Configure a Firewall with UFW and Introduction to FirewallD on CentOS to learn how to manage and inspect your firewall rules with those packages.

      Firewall rulesets can vary widely. Review the Control Network Traffic with iptables guide to analyze your rules and determine if they are blocking connections. A rule which allows incoming SSH traffic could look like this:

        
      -A INPUT -p tcp -m tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
      
      

      Disable Firewall Rules

      In addition to analyzing your firewall ruleset, you can also temporarily disable your firewall to test if it is interfering with your connections. Leaving your firewall disabled increases your security risk, so we recommend re-enabling it afterward with a modified ruleset that will accept your connections. Review Control Network Traffic with iptables for help with this subject.

      1. Create a temporary backup of your current iptables rules:

        sudo iptables-save > ~/iptables.txt
        
      2. Set the INPUT, FORWARD and OUTPUT packet policies as ACCEPT:

        sudo iptables -P INPUT ACCEPT
        sudo iptables -P FORWARD ACCEPT
        sudo iptables -P OUTPUT ACCEPT
        
      3. Flush the nat table that is consulted when a packet that creates a new connection is encountered:

        sudo iptables -t nat -F
        
      4. Flush the mangle table that is used for specialized packet alteration:

        sudo iptables -t mangle -F
        
      5. Flush all the chains in the table:

        sudo iptables -F
        
      6. Delete every non-built-in chain in the table:

        sudo iptables -X
        
      7. Repeat these steps with the ip6tables command to flush your IPv6 rules. Be sure to assign a different name to the IPv6 rules file (e.g. ~/ip6tables.txt).

      Troubleshoot Rejected SSH Logins

      If SSH is listening and accepting connections but is rejecting login attempts, review these instructions:

      Is Root Login Permitted?

      SSH can be configured to disable logins for the root user. To check your SSH configuration, run:

      grep PermitRootLogin /etc/ssh/sshd_config
      

      If the value of the PermitRootLogin is no, then try logging in with another user. Or, set the value in /etc/ssh/sshd_config to yes, restart SSH, and try logging in as root again.

      Note

      This option can also be set with the value without-password. If this value is used, root logins are accepted with public key authentication.

      Are Password Logins Accepted?

      SSH can be configured to not accept passwords and instead accept public key authentication. To check your SSH configuration, run:

      grep PasswordAuthentication /etc/ssh/sshd_config
      

      If the value of the PasswordAuthentication is no, create a key-pair. Or, set the value in /etc/ssh/sshd_config to yes, restart SSH, and try logging in with your password again.

      Is your Public Key Stored on the Server?

      If you prefer to use public key authentication, but your login attempts with your key are not working, double-check that the server has your public key. To check which keys are recognized for your user, run:

      cat ~/.ssh/authorized_keys
      

      If your public key is not listed in this file, add it to the file on a new line.

      On some systems, your authorized keys file may be listed in a different location. Run this command to show where your file is located:

      grep AuthorizedKeysFile /etc/ssh/sshd_config
      

      Collect Login Attempt Logs

      If the previous troubleshooting steps do not resolve your issues, collect more information about how your logins are failing:

      • View your login attempts in the log files described in step 4 of Is SSH Running?. In particular, you can search these logs for your local IP address, and the results will show what error messages were recorded for your logins. To find out what your local IP is, visit a website like https://www.whatismyip.com/.

      • Use your SSH client in verbose mode, which will show details for each part of the connection process. Verbose mode is invoked by passing the -v option. Passing more than one v increases the verbosity. You can use up to three vs:

        ssh -v [email protected]
        ssh -vv [email protected]
        ssh -vvv [email protected]
        

      Try pasting your logs into a search engine or searching for your logs in the Linode Community Site to see if anyone else has run into similar issues. If you don’t find any results, you can try asking about your issues in a new post on the Linode Community Site.

      Find answers, ask questions, and help others.

      This guide is published under a CC BY-ND 4.0 license.



      Source link

      Как настроить ключи SSH в Ubuntu 18.04


      Введение

      SSH (secure shell, безопасная оболочка) представляет собой шифрованный протокол для администрирования и взаимодействия между серверами. Во время работы с сервером Ubuntu вы, скорее всего, будете проводить большую часть времени в вашем терминале, подключенном через SSH к вашему серверу.

      В этом руководстве мы рассмотрим процесс настройки ключей SSH на вновь установленной Ubuntu. Ключи SSH представляют собой простой и безопасный способ входа на ваш сервер, и являются рекомендованным способом входа для всех пользователей.

      Шаг 1 – Создание пары ключей RSA

      Сперва создадим пару ключей на клиентской машине (обычно, это ваш компьютер):

      По умолчанию ssh-keygen создаёт 2048-битную пару ключей RSA, которая достаточно безопасна для большинства сценариев использования (вы можете также добавить к этой команде флаг -b 4096 для получения 4096-битный ключей).

      После ввода этой команды вы должны увидеть следующий вывод:

      Вывод

      Generating public/private rsa key pair. Enter file in which to save the key (/your_home/.ssh/id_rsa):

      Нажмите Enter для сохранения пары ключей в директорию .ssh/ внутри вашей домашней директории или задайте другую директорию.

      Если ранее вы уже генерировали пару SSH ключей, вы можете увидеть следующий вывод:

      Вывод

      /home/your_home/.ssh/id_rsa already exists. Overwrite (y/n)?

      Если вы выберете перезаписать ключи на диск, вы не сможете использовать старые ключи для аутентификации. Будьте очень осторожны при выборе yes, это решение нельзя будет отменить.

      Вы должны увидеть следующий вывод:

      Вывод

      Enter passphrase (empty for no passphrase):

      Здесь вы можете задать ключевую фразу (passphrase), что обычно рекомендуется сделать. Ключевая фраза добавляет дополнительный уровень безопасности для предотвращения входа на сервер неавторизованных пользователей. Для того, чтобы узнать больше о том, как это работает, рекомендуем ознакомиться с нашим руководством по настройке аутентификации по ключам SSH на серверах Linux.

      Вы должны увидеть следующий вывод:

      Вывод

      Output Your identification has been saved in /your_home/.ssh/id_rsa. Your public key has been saved in /your_home/.ssh/id_rsa.pub. The key fingerprint is: a9:49:2e:2a:5e:33:3e:a9:de:4e:77:11:58:b6:90:26 username@remote_host The key's randomart image is: +--[ RSA 2048]----+ | ..o | | E o= . | | o. o | | .. | | ..S | | o o. | | =o.+. | |. =++.. | |o=++. | +-----------------+

      Теперь у вас есть пара из публичного и секретного ключей, которые вы можете использовать для аутентификации. Далее мы поместим публичный ключ на ваш сервер, для того, чтобы вы могли использовать аутентификацию по ключам SSH для входа.

      Шаг 2 - Копирование публичного ключа на сервер Ubuntu

      Самым быстрым способом скопировать ваш публичный ключ на машину с Ubuntu - использовать утилиту ssh-copy-id. Поскольку этот метод невероятно прост, он рекомендуется для использования в первую очередь. Если по какой либо причине использование ssh-copy-id невозможно, вы можете использовать один из двух альтернативных методов, описанных далее (копирование в входом по SSH с использованием пароля и ручное копирование ключа).

      Копирование ключа с использованием ssh-copy-id

      Утилита ssh-copy-id доступна по умолчанию во многих операционных системах, поэтому, скорее всего, она доступна и на вашей локальной машине. Для использования этого метода копирования ключа вам необходимо иметь доступ к своему серверу по SSH с использованием пароля.

      Для использования утилиты вам необходимо указать адрес удалённого хоста, к которому вы хотите подключиться, а также имя пользователя, имеющего доступ к хосту по SSH. Именно для аккаунта этого пользователя и будет скопирован ваш публичный ключ SSH.

      Синтаксис команды выглядит следующим образом:

      • ssh-copy-id username@remote_host

      Вы можете увидеть вывод следующего вида:

      Вывод

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      Это означает, что ваш локальный компьютер не узнал удалённый хост. Это случается, когда вы пытаетесь подключиться к новому хосту в первый раз. Напечатайте "yes" и нажмите ENTER для продолжения.

      Далее утилита будет искать в директории вашего локального пользователя файл ключа id_rsa.pub, созданный нами ранее. Если файл ключа будет успешно обнаружен, утилита запросит пароль для входа на удалённый хост:

      Вывод

      /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys username@203.0.113.1's password:

      Введите пароль (при вводе он не будет отображаться из соображений безопасности) и нажмите ENTER. Утилита зайдёт на удалённый хост, используя данные аккаунта, пароль для которого вы ввели. Далее утилита скопирует содержимое файла публичного ключа из ~/.ssh/id_rsa.pub в файл authorized_keys в поддиректории ~/.ssh домашней директории вашего пользователя на удалённом хосте.

      Вы должны увидеть следующий вывод:

      Вывод

      Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'username@203.0.113.1'" and check to make sure that only the key(s) you wanted were added.

      Теперь ваш публичный ключ id_rsa.pub загружен на удалённый хост. Вы можете перейти к Шагу 3.

      Копирование публичного ключа через SSH

      Если у вас нет утилиты ssh-copy-id, но у вас есть пароль для входа по SSH на ваш удалённый сервер, мы можете загрузить свой ключ вручную.

      Для этого можно использовать команду cat, которая прочитает содержимое файла публичного ключа на локальной машине, а затем мы сможем отправить прочитанные данные ключа по SSH на удалённый сервер.

      Кроме этого, нам потребуется убедиться, что директория ~/.ssh существует, а также имеет корректные права доступа для используемого нами аккаунта пользователя.

      Далее мы сможем отправить содержимое файла ключа в файл authorized_keys внутри этой директории. Мы будем использовать синтаксис >> для добавление данных в конец файла вместо перезаписи содержимого файла. Это позволит нам добавить ключ без удаления ранее добавленных ключей.

      Команда выглядит следующим образом:

      • cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod -R go= ~/.ssh && cat >> ~/.ssh/authorized_keys"

      Вы можете увидеть вывод следующего вида:

      Вывод

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      Это означает, что ваш локальный компьютер не узнал удалённый хост. Это случается, когда вы пытаетесь подключиться к новому хосту в первый раз. Напечатайте "yes" и нажмите ENTER для продолжения.

      Далее вам будет предложено ввести пароль аккаунта пользователя на удалённом хосте:

      Вывод

      username@203.0.113.1's password:

      После ввода пароля содержимое вашего файла публичного ключа id_rsa.pub будет скопировано в конец файла authorized_keys на удалённом хосте. Если всё прошло успешно, вы можете перейти к Шагу 3.

      Копирование публичного ключа вручную

      Если у вас нет доступа к вашей удалённой машине по SSH с использованием пароля, вам придётся проделать описанный выше процесс вручную.

      Мы вручную добавим содержимое вашего файла id_rsa.pub в конец файла ~/.ssh/authorized_keys на удалённой машине.

      Для отображения содержимого файла id_rsa.pub введите следующую команду на вашей локальной машине:

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

      Вывод

      ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCqql6MzstZYh1TmWWv11q5O3pISj2ZFl9HgH1JLknLLx44+tXfJ7mIrKNxOOwxIxvcBF8PXSYvobFYEZjGIVCEAjrUzLiIxbyCoxVyle7Q+bqgZ8SeeM8wzytsY+dVGcBxF6N4JS+zVk5eMcV385gG3Y6ON3EG112n6d+SMXY0OEBIcO6x+PnUSGHrSgpBgX7Ks1r7xqFa7heJLLt2wWwkARptX7udSq05paBhcpB0pHtA1Rfz3K2B+ZVIpSDfki9UVKzT8JUmwW6NNzSgxUfQHGwnW7kj4jp4AT0VZk3ADw497M2G/12N0PPB5CnhHf7ovgy6nL1ikrygTKRFmNZISvAcywB9GVqNAVE+ZHDSCuURNsAInVzgYo9xgJDW8wUw2o8U77+xiFxgI5QSZX3Iq7YLMgeksaO4rBJEa54k8m5wEiEE1nUhLuJ0X/vh2xPff6SQ1BL/zkOhvJCACK6Vb15mDOeCSq54Cr7kvS46itMosi/uS66+PujOO+xt/2FWYepz6ZlN70bRly57Q06J+ZJoc9FfBCbCyYH7U/ASsmY095ywPsBo1XQ9PqhnN1/YOorJ068foQDNVpm146mUpILVxmq41Cj55YKHEazXGsdBIbXWhcrRf4G2fJLRcGUr9q8/lERo9oxRm5JFX6TCmj6kmiFqv+Ow9gI0x8GvaQ== demo@test

      Зайдите на вашу удалённую машину любым доступным для вас способом.

      Далее нам необходимо убедиться, что директория ~/.ssh существует. Следующая команда создаст директорию, если её не существует или не сделает ничего, если директория была создана ранее:

      Теперь вы можете создать или отредактировать файл authorized_keys внутри этой директории. Вы можете добавить содержимое файла id_rsa.pub в конец файла authorized_keys, при необходимости создав его, следующей командой:

      • echo строка_публичного_ключа >> ~/.ssh/authorized_keys

      В команде выше замените строка_публичного_ключа на вывод команды cat ~/.ssh/id_rsa.pub, которую вы выполнили на своей локальной машине. Строка должна начинаться с ssh-rsa AAAA....

      Далее убедимся, что директория ~/.ssh и файл authorized_keys имеют подходящие права доступа:

      Эта команда удаляет права доступа для "group" и "other" для директории ~/.ssh/.

      Если вы используете аккаунт root для настройки ключей для аккаунта пользователя, важно, чтобы директория ~/.ssh принадлежала этому самому пользователю, а не пользователю root:

      • chown -R sammy:sammy ~/.ssh

      В нашем руководстве мы используем пользователя с именем sammy, вам же следует использовать имя своего пользователя в команде выше.

      Теперь мы можем попробовать аутентифицироваться на нашем Ubuntu сервере без пароля.

      Шаг 3 - Аутентификация на сервере Ubuntu с использованием ключей SSH

      Если вы успешно проделали описанные выше шаги по переносу публичного ключа, вы должны быть способны зайти на свой удалённый хост без использования пароля.

      Процесс входа выглядит так же:

      Если вы заходите на удалённый хост по SSH в первый раз, вы можете увидеть вывод следующего вида:

      Вывод

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      Это означает, что ваш локальный компьютер не узнал удалённый хост. Напечатайте "yes" и нажмите ENTER для продолжения.

      Если при создании пары ключей вы не задали ключевую фразу (passphrase), вы будете залогинены автоматически. Если вы задали ключевую фразу, вам будет предложено её ввести (обратите внимание, что вводимые символы не будут отображаться на экране в целях безопасности). После аутентификации откроется новая сессия оболочки (shell session) на удалённом хосте от имени используемого вами удалённого аккаунта пользователя.

      Если аутентификация по ключу прошла успешно, рекомендуем ознакомиться с тем, как далее повысить безопасность вашего сервера путём отключения входа по паролю.

      Шаг 4 - Отключение аутентификации по паролю на вашем сервере

      Если вам удалось войти в ваш удалённый аккаунт на удалённом хосте по SSH без ввода пароля, вы успешно настроили аутентификацию по ключу SSH для вашего аккаунта. Однако возможность входить на сервер с использованием пароля всё есть активна, что означает, что ваш сервер уязвим для атак с перебором пароля (brute-force attacks).

      Перед тем как следовать дальнейшим инструкциям, убедитесь, что вы настроили аутентификацию по ключу SSH для вашего пользователя root или для пользователя с привилегиями sudo на вашем сервере. После завершения описанных далее процедур вход по паролю станет недоступен, поэтому очень важно убедиться, что у вас остаётся доступ к вашему серверу.

      Как только вы убедитесь, что аккаунт вашего удалённого пользователя имеет привилегии администратора, войдите на сервер с использованием аутентификации по ключу SSH, используя либо аккаунт root, либо аккаунт пользователя с привилегиями sudo. Далее откройте конфигурационный файл демона SSH:

      • sudo nano /etc/ssh/sshd_config

      Внутри файла найдите директиву PasswordAuthentication. Она может быть закомментирована. Раскомментируйте её при необходимости и установите её значение в "no". Это отключит возможность входа на сервер по паролю.

      /etc/ssh/sshd_config

      ...
      PasswordAuthentication no
      ...
      

      Сохраните и закройте файл нажав CTRL + X, затем Y для подтверждения сохранения файла, а далее ENTER для выхода из текстового редактора nano. Для применения внесённых изменений нам необходимо перезапустить сервис sshd:

      • sudo systemctl restart ssh

      В качестве меры предосторожности откройте новое окно терминала и проверьте, что соединение по SSH работает корректно, перед тем, как закрывать текущую сессию:

      После проверки работоспособности SSH соединения, вы можете закрыть все открытые сессии с сервером.

      Теперь демон SSH на вашем сервере с Ubuntu работает только с ключами SSH. Аутентификация по паролю полностью отключена.

      Заключение

      Теперь на вашем сервере настроен вход по ключам SSH, позволяющий заходить на сервер без использования пароля.

      Если вы хотите узнать больше о том, как работать с SSH, рекомендуем наше руководство по работе с SSH.



      Source link

      How to Set Up SSH Keys on Debian 9


      Introduction

      SSH, or secure shell, is an encrypted protocol used to administer and communicate with servers. When working with a Debian server, chances are you will spend most of your time in a terminal session connected to your server through SSH.

      In this guide, we’ll focus on setting up SSH keys for a vanilla Debian 9 installation. SSH keys provide an easy, secure way of logging into your server and are recommended for all users.

      Step 1 — Create the RSA Key Pair

      The first step is to create a key pair on the client machine (usually your computer):

      By default ssh-keygen will create a 2048-bit RSA key pair, which is secure enough for most use cases (you may optionally pass in the -b 4096 flag to create a larger 4096-bit key).

      After entering the command, you should see the following output:

      Output

      Generating public/private rsa key pair. Enter file in which to save the key (/your_home/.ssh/id_rsa):

      Press enter to save the key pair into the .ssh/ subdirectory in your home directory, or specify an alternate path.

      If you had previously generated an SSH key pair, you may see the following prompt:

      Output

      /home/your_home/.ssh/id_rsa already exists. Overwrite (y/n)?

      If you choose to overwrite the key on disk, you will not be able to authenticate using the previous key anymore. Be very careful when selecting yes, as this is a destructive process that cannot be reversed.

      You should then see the following prompt:

      Output

      Enter passphrase (empty for no passphrase):

      Here you optionally may enter a secure passphrase, which is highly recommended. A passphrase adds an additional layer of security to prevent unauthorized users from logging in. To learn more about security, consult our tutorial on How To Configure SSH Key-Based Authentication on a Linux Server.

      You should then see the following output:

      Output

      Your identification has been saved in /your_home/.ssh/id_rsa. Your public key has been saved in /your_home/.ssh/id_rsa.pub. The key fingerprint is: a9:49:2e:2a:5e:33:3e:a9:de:4e:77:11:58:b6:90:26 username@remote_host The key's randomart image is: +--[ RSA 2048]----+ | ..o | | E o= . | | o. o | | .. | | ..S | | o o. | | =o.+. | |. =++.. | |o=++. | +-----------------+

      You now have a public and private key that you can use to authenticate. The next step is to place the public key on your server so that you can use SSH-key-based authentication to log in.

      Step 2 — Copy the Public Key to Debian Server

      The quickest way to copy your public key to the Debian host is to use a utility called ssh-copy-id. Due to its simplicity, this method is highly recommended if available. If you do not have ssh-copy-id available to you on your client machine, you may use one of the two alternate methods provided in this section (copying via password-based SSH, or manually copying the key).

      Copying Public Key Using ssh-copy-id

      The ssh-copy-id tool is included by default in many operating systems, so you may have it available on your local system. For this method to work, you must already have password-based SSH access to your server.

      To use the utility, you simply need to specify the remote host that you would like to connect to and the user account that you have password SSH access to. This is the account to which your public SSH key will be copied.

      The syntax is:

      • ssh-copy-id username@remote_host

      You may see the following message:

      Output

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      This means that your local computer does not recognize the remote host. This will happen the first time you connect to a new host. Type "yes" and press ENTER to continue.

      Next, the utility will scan your local account for the id_rsa.pub key that we created earlier. When it finds the key, it will prompt you for the password of the remote user's account:

      Output

      /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys username@203.0.113.1's password:

      Type in the password (your typing will not be displayed for security purposes) and press ENTER. The utility will connect to the account on the remote host using the password you provided. It will then copy the contents of your ~/.ssh/id_rsa.pub key into a file in the remote account's home ~/.ssh directory called authorized_keys.

      You should see the following output:

      Output

      Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'username@203.0.113.1'" and check to make sure that only the key(s) you wanted were added.

      At this point, your id_rsa.pub key has been uploaded to the remote account. You can continue on to Step 3.

      Copying Public Key Using SSH

      If you do not have ssh-copy-id available, but you have password-based SSH access to an account on your server, you can upload your keys using a conventional SSH method.

      We can do this by using the cat command to read the contents of the public SSH key on our local computer and piping that through an SSH connection to the remote server.

      On the other side, we can make sure that the ~/.ssh directory exists and has the correct permissions under the account we’re using.

      We can then output the content we piped over into a file called authorized_keys within this directory. We’ll use the >> redirect symbol to append the content instead of overwriting it. This will let us add keys without destroying previously added keys.

      The full command looks like this:

      • cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod -R go= ~/.ssh && cat >> ~/.ssh/authorized_keys"

      You may see the following message:

      Output

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      This means that your local computer does not recognize the remote host. This will happen the first time you connect to a new host. Type "yes" and press ENTER to continue.

      Afterwards, you should be prompted to enter the remote user account password:

      Output

      username@203.0.113.1's password:

      After entering your password, the content of your id_rsa.pub key will be copied to the end of the authorized_keys file of the remote user's account. Continue on to Step 3 if this was successful.

      Copying Public Key Manually

      If you do not have password-based SSH access to your server available, you will have to complete the above process manually.

      We will manually append the content of your id_rsa.pub file to the ~/.ssh/authorized_keys file on your remote machine.

      To display the content of your id_rsa.pub key, type this into your local computer:

      You will see the key's content, which should look something like this:

      Output

      ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCqql6MzstZYh1TmWWv11q5O3pISj2ZFl9HgH1JLknLLx44+tXfJ7mIrKNxOOwxIxvcBF8PXSYvobFYEZjGIVCEAjrUzLiIxbyCoxVyle7Q+bqgZ8SeeM8wzytsY+dVGcBxF6N4JS+zVk5eMcV385gG3Y6ON3EG112n6d+SMXY0OEBIcO6x+PnUSGHrSgpBgX7Ks1r7xqFa7heJLLt2wWwkARptX7udSq05paBhcpB0pHtA1Rfz3K2B+ZVIpSDfki9UVKzT8JUmwW6NNzSgxUfQHGwnW7kj4jp4AT0VZk3ADw497M2G/12N0PPB5CnhHf7ovgy6nL1ikrygTKRFmNZISvAcywB9GVqNAVE+ZHDSCuURNsAInVzgYo9xgJDW8wUw2o8U77+xiFxgI5QSZX3Iq7YLMgeksaO4rBJEa54k8m5wEiEE1nUhLuJ0X/vh2xPff6SQ1BL/zkOhvJCACK6Vb15mDOeCSq54Cr7kvS46itMosi/uS66+PujOO+xt/2FWYepz6ZlN70bRly57Q06J+ZJoc9FfBCbCyYH7U/ASsmY095ywPsBo1XQ9PqhnN1/YOorJ068foQDNVpm146mUpILVxmq41Cj55YKHEazXGsdBIbXWhcrRf4G2fJLRcGUr9q8/lERo9oxRm5JFX6TCmj6kmiFqv+Ow9gI0x8GvaQ== demo@test

      Access your remote host using whichever method you have available.

      Once you have access to your account on the remote server, you should make sure the ~/.ssh directory exists. This command will create the directory if necessary, or do nothing if it already exists:

      Now, you can create or modify the authorized_keys file within this directory. You can add the contents of your id_rsa.pub file to the end of the authorized_keys file, creating it if necessary, using this command:

      • echo public_key_string >> ~/.ssh/authorized_keys

      In the above command, substitute the public_key_string with the output from the cat ~/.ssh/id_rsa.pub command that you executed on your local system. It should start with ssh-rsa AAAA....

      Finally, we’ll ensure that the ~/.ssh directory and authorized_keys file have the appropriate permissions set:

      This recursively removes all “group” and “other” permissions for the ~/.ssh/ directory.

      If you’re using the root account to set up keys for a user account, it’s also important that the ~/.ssh directory belongs to the user and not to root:

      • chown -R sammy:sammy ~/.ssh

      In this tutorial our user is named sammy but you should substitute the appropriate username into the above command.

      We can now attempt passwordless authentication with our Debian server.

      Step 3 — Authenticate to Debian Server Using SSH Keys

      If you have successfully completed one of the procedures above, you should be able to log into the remote host without the remote account's password.

      The basic process is the same:

      If this is your first time connecting to this host (if you used the last method above), you may see something like this:

      Output

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      This means that your local computer does not recognize the remote host. Type "yes" and then press ENTER to continue.

      If you did not supply a passphrase for your private key, you will be logged in immediately. If you supplied a passphrase for the private key when you created the key, you will be prompted to enter it now (note that your keystrokes will not display in the terminal session for security). After authenticating, a new shell session should open for you with the configured account on the Debian server.

      If key-based authentication was successful, continue on to learn how to further secure your system by disabling password authentication.

      Step 4 — Disable Password Authentication on your Server

      If you were able to log into your account using SSH without a password, you have successfully configured SSH-key-based authentication to your account. However, your password-based authentication mechanism is still active, meaning that your server is still exposed to brute-force attacks.

      Before completing the steps in this section, make sure that you either have SSH-key-based authentication configured for the root account on this server, or preferably, that you have SSH-key-based authentication configured for a non-root account on this server with sudo privileges. This step will lock down password-based logins, so ensuring that you will still be able to get administrative access is crucial.

      Once you've confirmed that your remote account has administrative privileges, log into your remote server with SSH keys, either as root or with an account with sudo privileges. Then, open up the SSH daemon's configuration file:

      • sudo nano /etc/ssh/sshd_config

      Inside the file, search for a directive called PasswordAuthentication. This may be commented out. Uncomment the line and set the value to "no". This will disable your ability to log in via SSH using account passwords:

      /etc/ssh/sshd_config

      ...
      PasswordAuthentication no
      ...
      

      Save and close the file when you are finished by pressing CTRL + X, then Y to confirm saving the file, and finally ENTER to exit nano. To actually implement these changes, we need to restart the sshd service:

      • sudo systemctl restart ssh

      As a precaution, open up a new terminal window and test that the SSH service is functioning correctly before closing this session:

      Once you have verified your SSH service, you can safely close all current server sessions.

      The SSH daemon on your Debian server now only responds to SSH keys. Password-based authentication has successfully been disabled.

      Conclusion

      You should now have SSH-key-based authentication configured on your server, allowing you to sign in without providing an account password.

      If you'd like to learn more about working with SSH, take a look at our SSH Essentials Guide.



      Source link