Research on the principle of OpenSSH password and public key authentication

Keywords: Linux

⭐ Configure and protect SSH

Objective: to configure the secure command line service on the remote system using OpenSSH


  • Log in to the remote system using ssh and run the command
  • Configure key based authentication for user accounts so that they can safely log in to the remote system without a password
  • Restrict direct login as root and disable password based authentication for the OpenSSH service.

H3 - access remote command line Using SSH

H4 - what is OpenSSH?

In practice, remote servers are managed, such as virtual machines. Therefore, you need to log in to the host remotely to manage the server. Moreover, it is impossible to directly operate the physical console, because virtual machines are virtual machines.

In fact, those who log in through the web page follow the vnc protocol.

In the past, telnet was mostly used, but now it is eliminated. Telnet is generally used to judge whether the port is listening. SSH (OpenSSH, open source) is generally used for login


Take the existing experimental environment as an example:

OpenSSH is configured between workstation, servera and serverb, so when logging in through ssh protocol, you can directly use key authentication without using login password. However, there is no OpenSSH key authentication between servera and serverb, so you must use a password to log in to each other.

H4 - login method:

Log in to servera host with student account:

  • Ellipsis: ssh student@servera #The port number is not specified here because the default port of ssh protocol is 22
  • Option writing: SSH servera - L student - P 22 # - L -- login login

H4 - log in and execute a temporary command:

H4 - view login user

When you connect to servera through ssh from the workstation, you can view it through the w command on servera:

This command is actually used to view all online users, whether they are logged in remotely or not, as well as locally logged in users.

⭐ You can also use the following command to view more details:

$ ss -tlna | grep :22

⭐ You can also view the login records through the security log of rsyslog

$ sudo grep sshd /var/log/secure

H4 - login principle

Password connection process

Before understanding the principle of an ssh connection, you need to understand the following key points:

Public key: encryption

Private key: decryption

The default SSH connection method is password authentication:


  1. When the client initiates a connection request, the server sends the latest public key to the client
  2. The client checks the file ~ /. SSH / known in the current home directory_ Whether hosts has the public key of the other party. If yes, step 3. If not, ask whether to add the public key.
  3. Ask the client to enter the password of the account, then encrypt it with the public key of the server and send it to the server
  4. The server uses the corresponding private key to decrypt. If it is correct, it is allowed to log in.

Summary @jayce:

To summarize, the above ssh connection process:
When trying to connect to serverb from servera, serverb will send its latest public key to servera. Servera has received the public key sent. First, in servera: ~ /. SSH / known_ Find out whether the historical public key exists in the hosts file. If so, go directly to the next step. If not, write its contents to servera:~/.ssh/known_hosts file (if there is no such file, it will be created automatically, provided that the sshd service exists.)

After ensuring that the know_hosts of servera has the public key of serverb host, the user attempting to log in will be asked for the password of the remote login account. After the user enters the password, the public key of serverb will be used for encryption. Then send it to serverb

After receiving the encrypted password, serverb tries to decrypt it with the private key, and then checks whether the password is correct. If it is correct, servera will be allowed to connect remotely through ssh.

If you are still unclear about the connection process, you can see the detailed experiment process in [attachment] / Chapter 10 SSH connection process experiment. md.

Server update key:
$ rm -f /etc/ssh ssh_host_* #Delete public and private keys
$ systemctl restart sshd #Will regenerate

The generated key pair is stored in the / etc/ssh directory. What happens when you enter and delete the key pair, and then try to connect to serverb from servera?

Tip: the remote host has been modified, which may be a man in the middle hijacking attack (omitted). Therefore, it is generally necessary to confirm with the administrator when updating the key and connecting remotely.

There are three different key pairs, the difference is that different algorithms are used

Why does this prompt appear?

When servera attempts to connect to serverb remotely via ssh, serverb sends the public key to servera, and servera has previously connected to serverb. All historical public keys exist, but now the public key of serverb has been modified. Therefore, there is a difference in the comparison time between the historical public key and the latest public key on servera, so this prompt will be reported.

Remove the authentication information of a host: SSH keygen - R hostname

SSH keygen - R serverb removes the historical authentication information of serverb

After removal, servera reconnects and serverb can connect normally.

⭐⭐ H 3-key authentication (public key authentication)

At work, key holders are becoming more secure and convenient.

H4 - Introduction:

Taking the experimental environment as an example, there are virtual machine workstation, servera and serverb. The public key authentication between workstation, servera and serverb. Public key authentication eliminates the need to enter a password for ssh connections.


$ ssh -i ./.ssh/lab_rsa student@servera

In fact, you don't need to bring the - i option, because when the server opens the key (or public key) authentication (premise), the key authentication will be taken by default during ssh connection. If the authentication fails, the password authentication will be taken.
Therefore, in fact, the login is generally as follows:

$ssh student@servera

workstation:~/.ssh/lab_rsa and workstation:~/.ssh/ is a key pair.

H4 - ⭐ Key authentication principle

When the client and server trust each other (there is absolutely no middleman)

  1. The client uses the SSH keygen command to generate a key pair: SSH keygen

    $ ssh-keygen # By default, if the - t option is not added to set the algorithm, the sha256 algorithm will be used by default
    # -The t option selects a specific algorithm
    $ ssh-keygen -t ecdsa
     #ubuntu example
     jayce@DESKTOP-JASQLDM:~$ ssh-keygen
    Generating public/private rsa key pair.
    Enter file in which to save the key (/home/jayce/.ssh/id_rsa):#Key pair storage location
    Created directory '/home/jayce/.ssh'.
    Enter passphrase (empty for no passphrase):#Encrypt private key? One more lock can't be used to disclose others (if it's to avoid password authentication, don't encrypt here)
    Enter same passphrase again:
    Your identification has been saved in /home/jayce/.ssh/id_rsa
    Your public key has been saved in /home/jayce/.ssh/
    The key fingerprint is:
    SHA256:IyCSLQHKsHZykIFc7gaQfihunvz+dWOTs8dJxFB9UIQ jayce@DESKTOP-JASQLDM
    The key's randomart image is: # Hash chart
    +---[RSA 3072]----+
    |O++.      ....=o |
    |BBo      .   E . |
    |B=++.     o   .  |
    |o=*o .     o     |
    |o .o  . S .      |
    | o.    . ...     |
    |+ .    . Bo .    |
    | +    . o =+     |
    |  oo..   ..      |
  2. The client sends the public key to the server user@host:~/.ssh/authorized_keys/ ssh-copy-id

    $ ssh-copy-id -i Private key user@host
    #eg: ssh-copy-id -i student@serverb

    After entering the command, the password will be used to complete the copy. (copied to) student@serverb:~/.ssh/authorized_keys/ )

  3. When connecting:

    1. Client initiated connection

    2. After receiving the signal, the server randomly generates a string (regenerated for each connection) and encrypts it with the public key provided by the client, and then returns it to the client

    3. The client decrypts using the private key. And return the decrypted string to the server

      The client only knows the public key, the private key is correct, and the server only knows whether the string is correct. Both only know their own

    4. The server verifies whether the string is generated before. If it is correct, the connection is allowed.

H4 - * * full experiment - key authentication - connect from servera to serverb**

Preparation: initial status: password authentication is required to connect from servera to serverb:

  1. servera, as the client, generates key pairs through SSH keygen:

  2. The SSH copy ID command copies (sends) the public key to the pre connected user @ host through password authentication

    You can verify the following:

  3. Trying to connect:

    The complete connection should be ssh -i id_rsa

⚠️ Common password authentication is that the server sends a public key to the client, while key authentication is that the client generates a key pair and sends a public key to the server

Make SSH connection more secure: customize opensh service configuration

Server: / etc/ssh/sshd_config

Here, please pay attention to a small concept:
As a multi terminal program, SSH has a client and a server. Generally speaking, the server should be a resident process (that is, a daemon in Linux), and sshd here is a daemon. Why? Because the server should always wait to be connected, and can be connected at all times. If it is not a one-way connection and requires frequent interconnection, there should be daemons at each end.

#Port 22					//Customize the port. The default is 22. Modify the design of Selinux and firewall #AddressFamily any 			 // Port types listening in LAN, inet (ipv4), inet (ipv6), any (ipv4 & ipv6) #ListenAddress 		 // Listening port. If the port is specified, you can only hear the login application of the listening port# ListenAddress ::PubkeyAuthentication yes  	  // Whether public key authentication is enabled by default. It is strongly recommended to enable permitrotlogin No 			  // ⭐⭐⭐⭐⭐ It is strongly recommended to close (hackers are scanning every moment to see if there is a port open for root login) authorized keysfile. SSH / authorized_ keys .ssh/authorized_ Keys2 / / the default storage location of the key. If the public key authentication is enabled, it must be enabled. PasswordAuthenticatoin no 	  // Whether to enable password authentication. If both public key authentication and password authentication are enabled, public key authentication will be used first. If the public key authentication fails to log in, password authentication will be used, and the use of password authentication may lead to man in the middle hijacking attack. Therefore, in the general formal production environment, it is recommended to turn off password authentication
custom sshd Configuration of/etc/ssh/sshd_configPort 22  //Port number addressfamily INET / / IP protocol type inet inet6 anyListenAddress / / interface hostkey / etc / SSH / SSH_ host_ rsa_ keyHostKey /etc/ssh/ssh_ host_ ecdsa_ keyHostKey /etc/ssh/ssh_ host_ ed25519_ Keysyslogfacility authprivpermitrotlogin no / / turn off root remote login PubkeyAuthentication yes / / enable public key authentication. Authorized keysfile. SSH / authorized_ Keyspasswordauthentication no / / turn off password authentication challengeresponseauthentication nogssapiauthentication yegssapicleanupcredentials nousepam yesx11forwarding yesprintmotd noclientaliveinterval 60acceptenv Lang LC_ CTYPE LC_ NUMERIC LC_ TIME LC_ COLLATE LC_ MONETARY LC_ MESSAGESAcceptEnv LC_ PAPER LC_ NAME LC_ ADDRESS LC_ TELEPHONE LC_ MEASUREMENTAcceptEnv LC_ IDENTIFICATION LC_ ALL LANGUAGEAcceptEnv XMODIFIERSSubsystem sftp 	/ usr/libexec/openssh/sftp-server

After setting, restart the sshd service

$ systemctl restart sshd

Posted by $kevan on Fri, 03 Dec 2021 02:54:46 -0800