SSH Remote Access and control

Posted by phpBever on Wed, 19 Jan 2022 04:39:24 +0100

1, SSH Remote Management

1.SSH (secure shell) protocol

SSH: secure channel protocol, which mainly realizes remote login and remote replication of character interface

  • Encrypt the data of both communication parties for remote management
  • Security protocol based on application layer and transport layer
  • Encrypted communication through network and port to prevent information disclosure
  • Data transmission is compressed, which can improve the transmission speed

SSH client: putty, xshell, CRT, mobaxtermand finalshell

SSH server: openssh

2.OpenSSH

The ssh server mainly includes two service functions: SSH Remote link and sftp service

effect:
SSHD Service usage ssH Protocols can be used for remote control or to transfer files between computers
 Used before comparison Telnet It is much safer to transfer files in this way;
Telnet Is plaintext transmission
SSH Is encrypted transmission.
  • Service Name: sshd
  • Server main program: / usr/sbin/sshd
  • Server configuration file: / etc/ssh/sshd_config
  • The service uses TCP port 22 by default

ssh_config configuration file: for clients

sshd_config configuration file: for the server

3. ssh is basically used for remote management of Linux system

reason:

telnet, FTP and other transmission methods transmit user authentication information in plaintext, which is inherently unsafe and has the risk of being eavesdropped by the network.

SSH is currently relatively reliable. It is a protocol dedicated to providing security for remote login sessions and other network services. Using SSH protocol can effectively prevent information leakage in the process of remote management. All transmitted data can be encrypted through SSH, and DNS spoofing and IP spoofing can also be prevented

2, SSH Remote Login

1. Method 1:

ssh [remote host user name] @ [remote server host name or IP address] - p port

ssh  root@192.168.118.11

2. Method 2:

ssh -l [remote host username] [remote server hostname or IP address] - p port

ssh  -l  root  192.168.118.11 
-l:Specify login name
-p:Specify the login port [when the port of the server is not the default, you need to specify the login port]
Note:
When logging in to the server for the first time, the system does not save the information of the remote host. Confirming the identity of the host will prompt the user whether to continue the connection. Enter yes Post login; This is the reason why the system will write the remote server information to the user's home directory $HOME/.ssh/known_hosts In the file, you will not be prompted the next time you log in because you save the host information.

3.SSH login to other Linux hosts. Solutions to login prohibition:

reason:

ssh The public key of each computer you have visited will be recorded in~/.ssh/known_hosts 
The next time you visit the same computer, openssh The public key will be checked. If it is different, openssh A warning will be issued to prevent you from being affected DNS hijack Attacks like that

resolvent:

1. Add "- o StrictHostKeyChecking=no" when connecting to the host Using ssh.
2. Methods to completely remove the prompt:

Modify / etc/ssh/ssh_config file (or $HOME/.ssh/config), add the following two lines of configuration:

StrictHostKeyChecking no
UserKnownHostFile  /dev/null

Fault set
Work at ordinary times During the operation, sometimes SSH login is required to other Linux hosts, but sometimes SSH login is prohibited, and the following similar prompts pop up:
The authenticity of host '192.168.10.9 (192.168.10.9)' can't be established.ECDSA key fingerprint is SHA256:AaGpHeEiRuXMy96oezzV6TOej5nJJmZIe/djqR7qCVk.ECDSA key fingerprint is MD5:78:a1:b1:1c:36:76:c7:34:54:87:cc:ea:51:3f:0c:24.Are you sure you want to continue connecting (yes/no) ? yes
Warning: Permanently added '192.168.10.9'(ECDSA) to the list of known hosts.Authentication failed.

3, openssh service configuration and management

1. Service configuration

#ListenAddress listening address
ListenAddress 0.o.o.o
 set up ssHD Server bound IP Address, 0.0.0.0 Means listening to all addresses
 Safety advice:If the host does not need to be from the public network ssh Access, you can change the listening address to the intranet address, and this value can be written as local address IP Address can also be written as all addresses, i.e o.o.0.0 Represents all IP address

#Protocol 2
 Set protocol version to ssH1 or ssH2,SSH1 There are loopholes and defects, select ssH2
 
#UseDNs yes
 Generally speaking, in order to judge that the source of the client is normal and legal, it will be used DNS Check the host name of the client,
However, usually when the intranet is interconnected, the base is set to no,Therefore, the online speed will be faster
 notes:Disable DNS Reverse parsing to improve the response speed of the server

#SyslogFacility AUTHPRIV
 When someone uses ssH When logging into the system, ssH Information will be recorded. The type of information to be recorded is AUTHPRIV,sshd Service logs are stored in:/var/log/secure. 

2. Security tuning

##LoginGraceTime 2m
grace It means how many seconds the system gives to log in. (default 2 minutes,ОIndicates unlimited)
When the user is connected ssH server After that, the screen of entering password will appear, in which.
How long has it not been successfully connected ssHserver Forced disconnection!If there is no unit, the default time is seconds. It can be modified according to the actual situation

##Permitrotlogin yes experiment
 Allow root Login is allowed by default, but it is recommended to set it to no,The real production environment server is not allowed root If the account is logged in directly, only ordinary users are allowed to log in. It needs to be used root The user then switches to root User.
Case list
 Create user zhangsan,lisi
 Query group
grep "wheel" /etc/ group
gpasswd -a zhangsan wheel #zhangsan user has joined the wheel group and started the pam module

##PasswordAuthentication yes
 Password verification is certainly required!So it's written here yes,It can also be set to no,On the real production server, according to different security level requirements, some settings do not require a password to log in, and log in through an authenticated secret key.

##PermitEmptyPasswords no
 Allow users with blank passwords to log in. The default value is no,Login with empty password is not allowed

##PrintLastLog yes
 Displays the last login information!Default to yes152

##MaxAuthTries 6
 Specify the maximum number of authentication allowed per connection. The default value is 6.
If the number of failed authentication exceeds half of this value, the connection will be forcibly disconnected, and an additional failure log message 156 will be generated. By default, 3 times
 verification ssh -o NumberOfPasswordPrompts=8 lisi@192.168.10.9159

#####AllowUsers
 When you want to allow or disable only some users to log in, you can use AllowUsers or DenyUsers to configure
,The usage of the two is similar(Be careful not to use it at the same time).
to configure AllowUsers
 For example, if only zhangsan,wangwu User login,Other( lisi)user
AllowUsers zhangsan@192.168.10.10 wangwu
 Black and white conclusion

#####UsePAM yes
 open PAM modular

ssh defaults to port 22. After the change, you need to turn off the core protection and restart sshd

Port 2222      #Change to high port
setenforce 0
systemctl restart sshd

Change the high-level port: secure and prevent violent cracking

4, openssh server

1. User login control

  • Prohibit root user, empty password user

  • Limit login verification time and retry times

  • AllowUsers,DenyUsers

LoginGraceTime 2m
PermitRootLogin no   prohibit root user
MaxAuthTries 6
AllowUsers ierry  admin@192.168.10.100  
#AllowUsers is not used with DenyUsers

2. Login authentication method

● password verification: check whether the user name and password match
● key pair verification: check whether the customer's private key and the server's public key are valid

[root@localhost ~]# vi letclssh/sshd_config
PasswordAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

3. The sshd service supports two authentication methods

1. Password verification:

Verify the login name and password of the local system user in the server. This method is the easiest to use, but from the perspective of the client, the server being connected may be counterfeited; From the perspective of the server, when encountering the password exhaustive (brute force cracking) attack, the defense ability is relatively weak.
Full bit password complexity port

⒉. Key pair validation:

Matching key information is required to pass the verification. Usually, a pair of key files (public key and private key) are created in the client, and then the public key file is placed in the specified location in the server. During remote login, the system will use public key and private key for encryption / decryption Association verification, which greatly enhances the security of remote management. This method is not easy to be counterfeited, and can avoid interactive login in the shell
Is widely used in.

When both password authentication and key pair authentication are enabled, the server will give priority to key pair authentication. For servers with high security requirements, it is recommended to disable password authentication and only enable key pair authentication; If there are no special requirements, both methods can be enabled

Password free login
SSH agent bash# adds and manages the public key on the client side

ssh-add

3.scp replication: Security replication

scp is short for secure copy, which is used to remotely copy files under Linux, and scp transmission is encrypted.

Will server home Copy the files under to the current local directory
[root@localhost ~]# scp root@192.168.118.12:/home/ceshi ./
root@192.168.118.12's password: 
ceshi                             100%   10     8.3KB/s   00:00    
[root@localhost ~]# ll
 Total consumption 8
-rw-------. 1 root root 1269 12 February 15:32 anaconda-ks.cfg
-rw-r--r--. 1 root root   10 1 December 11:57 ceshi

Copy local files to the server's home Directory
[root@localhost ~]# scp ceshi root@192.168.118.12:/home/
root@192.168.118.12's password: 
ceshi                             100%   10     6.5KB/s   00:00    
[root@localhost ~]# 

4. Secure transmission sftp

sftp is the abbreviation of secure File Transfer Protocol, a secure File Transfer Protocol.

It can provide a secure network encryption method for transmitting files.

SFTP and FTP have almost the same syntax and function. SFTP is a part of SSH. In fact, a secure file information transfer subsystem called SFTP (Secure File Transfer Protocol) is included in the SH package. SFTP itself does not have a separate daemon. It must use the sshd daemon (port number is 22 by default) to complete the corresponding connection and reply operations. Therefore, it is very safe to use SFTP. However, because this transmission mode uses encryption / decryption technology, the transmission efficiency is much lower than ordinary FTP. If you have higher requirements for network security, you can use SFTP instead of FTP

[root@localhost ~]# sftp root@192.168.118.12
root@192.168.118.12's password: 
Connected to 192.168.118.12.
sftp> put ceshi /opt/   upload
Uploading ceshi to /opt/ceshi
ceshi                             100%   10     6.3KB/s   00:00    
sftp> get ce /home/      download

get          #Download File
get  -r      #Download directory

5, Key: the key has priority over the password

1. Build SSH for key pair verification

1. Relationship between public key and private key:
● in asymmetric encryption technology, there are two kinds of keys: private key and public key. The private key is held by the key pair owner and cannot be published. The public key is published by the key pair owner to others.
● the public key is used to encrypt data, and the data encrypted with the public key can only be decrypted with the private key

2. Build SSH principle for key pair verification

Firstly, ssh generates a key pair (public key and private key) at the client through an encryption algorithm, sends the public key to the server, and retains the private key,

If you want to connect to the ssh server with the public key, the client SSH software will send a request to the ssh server for security authentication with the online user key.

After the ssh server receives the request, it will first look for it in the home directory of the user connected to the ssh server The public key of the corresponding user, and then compare it with the public key sent by the connected SSH client. If the two keys are consistent, the ssh server encrypts the "challenge" with the public key and sends it to the SSH client.

When both password authentication and key pair authentication are enabled, the server will give priority to key pair authentication. The verification method can be set according to the actual situation.

vim/etc/ssh/sshd config
PasswordAuthentication yes
#Enable password authentication
PubkeyAuthentication yes
#Enable key pair authentication
Authori zedKeysFile . ssh/authorized keys
#Specifies the public key library file

3. Configure key pair authentication

1. Create a key pair on the client

Via SSH keygen The tool creates a key pair file for the current user. The available encryption algorithms are RSA, ECDSA, DSA, etc. (the "- t" option of SSH keygen command is used to specify the algorithm type).

useradd admin
echo "123123" | passwd --stdin admin
su - admin 
ssh-keygen -t ecdsa

Generating public/private ecdsa key pair.
Enter file in which to save the key (/home/ admin/ .ssh/id_ ecdsa)
#Specify the location of the private key. Press enter to use the default location
Created directory ' /home/admin/ .ssh'. #The generated private key and public key files are stored in the hidden directory of the host directory by default ssh / down
Enter passphrase (empty for no passphrase) : #Set the password for the private key
Enter same passphrase again: #Confirm input
ls -1 ~/ .ssh/id_ecdsa*
#id_ecdsa is the private key file, and the permission is 600 by default; id_ecdsa. Pub is a public key file, which is used to provide SSH server

2. Upload the public key file to the server

scp ~/ .ssh/id_ ecdsa.pub root@192.168.80.10:/opt
 or
 This method can be used directly on the server/home/ zhangsan/ .ssh/Import public key text from directory
cd ~/ . ssh/
ssh-copy-id -i id_ecdsa.pub zhangsan@192.168.80.10

3. Import the public key text in the server

mkdir /home/ zhangsan/ . ssh/
cat /opt/id_ ecdsa.pub  >> /home/ zhangsan/ .ssh/authorized keys
 cat /home/ zhangsan/ . ssh/authorized keys

4. Use key pair authentication on the client

ssh zhangsan@192.168.80.10
Enter passphrase for key ' /home/admin/ .ssh/id_ ecdsa' : #Enter the password for the private key

5. Set ssh proxy function on the client to realize interactive login free;

ssh-agent bash
#Enable ssh proxy function
ssh-add
#Add the key to SSH agent cache
Enter passphrase for /home/admin/ .ssh/id_ ecdsa: 
#Enter the password for the private key
ssh zhangsan@192.168.80.10


6, TCP Wrappers access control

TCP wrappers
In Linux system, many network services provide access control mechanisms for clients, such as Samba, BIND, HTTPD, openSSH and so on
TCP Wrappers "wrap" the TCP service program and listen to the port of the TCP service program instead, adding
A security detection process. External connection requests must pass this layer of security detection before they can access the real service program

[ root@localhost opt]# rpm -q tcp_ wrappers #Generally, the system will be installed by default

 tcp_ wrappers-7.6-77.el7.x86_ _64 #The package provides the executor tcpd and the shared link library file libwrap so.*
TCPWrapper protection mechanism :Usually called by other network service programs libwrap.so.*Link libraries such as sshd
[root@localhost opt]# ldd /usr/sbin/sshd 1 grep "libwrap" 

#Use the 1dd command to view the shared library of the program
libwrap.so.0 => /lib64/libwrap.so.0 (0x00007fc35d8f8000)

TCP Wrappers access control
TCP wrappers_

The TCP service program is "wrapped" and instead of listening to the port of the TCP service program, a security detection process is added. External connection requests must pass this layer of security detection before they can access the real service program.
For most Linux distributions, TCP Wrappers is the default feature. rpm -q tcp_ wrappers
Two implementations of TCP Wrappers protection mechanism

1. Directly use tcpd program to protect other service programs. You need to run tcpd program.

2. Other network service programs call libwrap so.* Link library, no need to run tcpd
Procedure. This method is more widely used and more efficient.
Use the 1dd command to view the libwrap so. * Link library
ldd $ (which ssh)
Syntax format: < service program list >: < client address list >
(1) Service program list service program list can be divided into the following categories

Syntax format: < service program list >: < client address list >
(1) Service program list service program list can be divided into the following categories.
ALL: represents ALL services. Single service program: such as "vsftpd". A list composed of multiple service programs: such as "vsftpd, sshd"

(1) Service program list
ALL: represents ALL services.
Single service program: such as "vsftpd"
A list of multiple service programs, such as "vsftpd, sshd".

(2) Client address list
ALL: represents any client address.
LOCAL: represents the LOCAL address.
Multiple addresses are separated by commas
Wildcards "*" and "?" are allowed. The former represents any length character, and the latter represents only - one character
Network segment address, such as 192.168.80 "Or 192.168.80.0 / 255.255.255.0"
Area address, such as ". benet . com "matches all hosts in the benet. com domain.
Basic principles of access control
First check / etc / hosts Allow file. If a matching policy is found, access is allowed;
Otherwise, continue checking / etc / hosts Deny file. If a matching policy is found, access is denied;
If no matching policy can be found by checking the above two files, access is allowed
"Allow all, reject individual"
Just in / etc/hosts. Add the corresponding rejection policy to the deny file
"Allow individual, reject all"
Except in / etc/hosts. In addition to adding an allow policy in allow, you also need to add an allow policy in / etc/hosts
The deny policy of "ALL:ALL" is set in the deny file.

Example:
If you only want to access the sshd service from the host with IP address 12.0.0.1 or the host in 192.168.80.0/24 network segment, other addresses are rejected.

vi /etc/hosts. allow
sshd:12.0.0.1,192.168.80.*
vi /etc/hosts .deny
sshd: ALL
sshd, htpd: ALL

7, Security level settings

  • Perform security checks on RPM packages that are not security certified
  • Linux user hardening
  • Set password policy 20 bits
  • Setting of user password strength
  • Limit the number of user logins
  • Prohibit ROOT users from logging in remotely
  • Set the number of historical commands saved and the account timeout
  • Set that only the specified user group can use the su command to switch to the root user
  • Manage Linux accounts
  • Important files are locked and cannot be deleted even by root
  • Establish log server day

summary

In short, SSH is a network protocol, which is mainly used for the secure link and interaction between the client and the remote host.
The process of secure link is:
1. When receiving the login request from the client, the remote host first sends its own public key to the client
2. The client encrypts the user name and password with the obtained public key, and then sends it to the remote host
3. The remote host decrypts the received user name and password with its own key, and then verifies whether the user name and password are correct. If they are correct, the login is successful.
2. The client logs in to the remote host "Linux should learn this way" without secret
If you only pass the first step, you need to enter the login password for each login in the future, which is very troublesome. Fortunately, SsH provides public key login (secret free login)
The process of public key login is as follows:
1. The client generates the public key file locally, and then stores the public key on the remote host
2. When the client logs in, the remote host will randomly generate a string and send it to the client
3. The client encrypts the received string with its own key and returns it to the remote host
4. The remote host uses the public key to decrypt the received encrypted string. If the decryption is successful and consistent with the one sent, it will log in directly without secret

Topics: network ssh server