Research on the principle of OpenSSH password and public key authentication

Configuring secure command line services on remote systems using OpenSSH

Objectives:

  • 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.

1. Use SSH to access the remote command line

1.1 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

introduce:

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.

1.1.1 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

1.1.2 log in and execute temporary commands:

1.1.3 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

1.2 login principle

1.2.1 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:

Process:

  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.

1.2.1.1 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.

1.2.1.2 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.

1.2.2 ⭐⭐ Key authentication (public key authentication)

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

1.2.2.1 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.

Example:

$ 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/lab_rsa.pub is a key pair.

1.2.2.2 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/id_rsa.pub
    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..   ..      |
    +----[SHA256]-----+
    
  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 id_ecdsa.pub 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 0.0.0.0 		 // Listening port. If the port is specified, you can only hear the login application of the listening port.
#ListenAddress ::


PubkeyAuthentication yes 	  //Public key authentication is enabled by default. It is strongly recommended to enable it
PermitRootLogin no 			  //⭐⭐⭐⭐⭐ It is strongly recommended to close it (hackers are scanning the face all the time. Is there a port open for root login)
AuthorizedKeysFile  .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, password authentication will be used, and the use of password authentication may lead to man in the middle hijacking attack. Therefore, it is recommended to turn off password authentication in the general formal production environment.
.......
custom sshd Configuration of

/etc/ssh/sshd_config

Port 22  //Port number
AddressFamily inet  //IP protocol type inet inet6 any
ListenAddress 172.25.250.11   // Interface
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
SyslogFacility AUTHPRIV
PermitRootLogin no  //Turn off root remote login
PubkeyAuthentication yes //Enable public key authentication
AuthorizedKeysFile  .ssh/authorized_keys
PasswordAuthentication no  //Turn off password authentication
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
UsePAM yes
X11Forwarding yes
PrintMotd no
ClientAliveInterval 60
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
Subsystem sftp	/usr/libexec/openssh/sftp-server

After setting, restart the sshd service

$ systemctl restart sshd

Added by arctushar on Sun, 05 Dec 2021 09:45:43 +0200