SSH Remote login protocol and TCP wappers

1. SSH services

1.1 basis of SSH

What is an SSH server?

Secure Shell (SSH) is a Secure channel protocol used to implement remote login and remote replication on character interfaces. SSH encrypts the data transmitted between the communication parties, including the user password entered during login. SSH is a secure protocol based on the application layer and transport layer. Compress data to speed up transmission.

SSH client <————– network —————->SSH server

Advantages:

  • Data transmission is encrypted to prevent information leakage
  • Data transmission is compressed to increase transmission speed

Common SSH protocol

Client: Linux Client: SSH, SCP, SFTP, slogin Windows Client: Xshell, MobaXterm,putty, Securecrt, sSHSecureShellClient OpenSSH is an open source software project that implements THE SSH protocol and applies to various UNIX and Linux operating systems. Centos 7 The OpenSSH software package has been installed by default, and the SSHD service is automatically started upon startup. Run the "systemctl start SSHD "command to start the SSHD service. By default, the SSHD service uses port 22 of TCP and the security protocol version is sshv2. The default configuration file of the SSHD service is /etc/ssh/sshd_config. Ssh_config and sshd_config are both configuration files of the SSH server. The difference between the two is that the former is for the client, while the latter is for the server.Copy the code

The SSH server provides two services: SSH remote connection and SFTP

Function: The SSHD service can be used for remote control or to transfer files between computers using the SSH protocol. It is much safer to transfer files over Telnet than before because Telnet uses plaintext and SSH is encrypted.

Service name: SSHD

Server main program: /usr/sbin/sshd

Server configuration file: /etc/ssh/sshd_config

Client configuration file: /etc/ssh/ssh_config

1.2 principle of SSH

1.2.1 Principles of Public Key Transmission

  • The client initiates a link request

  • The server returns its own public key, along with a session ID (this step the client gets the server public key)

  • The client generates a key pair

  • The client calculates a value Res using its own public key xor session ID and encrypts it with the server’s public key

  • The client sends the encrypted value to the server, which decrypts it with the private key to get the Res

  • The server calculates the public key of the client using the decrypted value Res xor session ID (this step the server obtains the public key of the client)

  • The final result: each party holds three secret keys, a pair of public and private keys and the public key of the other party, and all subsequent communications are

    Will be encrypted

SSH Encryption communication mechanism

(1) Symmetric encryption 1. The concept of single-key cryptosystem encryption method, the same key can be used for information encryption and decryption at the same time, this encryption method is called symmetric encryption, because of its high speed, symmetric encryption is usually used when the message sender needs to encrypt a large amount of data

2, commonly used algorithms in symmetric encryption algorithms are: DES, 3DES, TDEA, Blowfish, RC2, RC4, RC5, IDEA, SKIPJACK, etc.

1. The encryption party and the decryption party use the same key; 2, encryption and decryption speed is relatively fast, suitable for the use of long data; 3. The process of key transmission is not secure and easy to crack, and key management is also troublesome;

The advantages and disadvantages of symmetric encryption algorithm are that the algorithm is open, the calculation is small, the encryption speed is fast, and the encryption efficiency is high. The drawback of symmetric encryption algorithms is that before data can be transmitted, the sender and receiver must agree on the secret key, and then enable both parties to keep the secret key. Secondly, if one party’s secret key is leaked, the encrypted information is not secure. In addition, each pair of users needs to use a unique secret key unknown to others every time they use a symmetric encryption algorithm, which makes the number of keys owned by the receiver and sender huge, and key management becomes a burden for both parties

Asymmetric encryption algorithms require two keys: a publickey and a privatekey. The public key and private key are a pair. If the public key is used to encrypt data, only the corresponding private key can be used to decrypt data. Because encryption and decryption use two different keys, the algorithm is called asymmetric encryption.

2. Common algorithm RSA (RSA Algorithm) : The most widely used algorithm DSA (Digital Signature Algorithm) Different from RSA, DSA can only be used for digital signature and cannot encrypt or decrypt data. The security of DSA is similar to that of RSA, but the performance is faster than THAT of RSA. Elliptic Curve Digital Signature Algorithm is a combination of ECC and DSA. Compared with RSA Algorithm, ECC can use smaller secret keys, achieve higher efficiency and provide higher security

SSH generates a key pair (public key and private key) on the client using an encryption algorithm. The public key is sent to the server and the private key is kept. If you want to connect to the SSH server with a public key, the SSH software on the client sends a request to the SSH server for security authentication using the online user key. After receiving the request, the SSH server stores the request in the home directory of the user connected to the SSH server

5. Advantages and disadvantages Compared with symmetric encryption technology, asymmetric encryption technology has better security, but slower performance.

In this experiment, we use the asymmetric encryption algorithm ECDSA for encryption. For the convenience of root user, it can also be configured for other common users

1.2.2 login

# Login method 1: SSH [remote host username]@[Host name or IP address of the remote server] -p port When you remotely connect to another Linux host, for example, the current user is root, and log in to another Linux host as root. You can directly use the SSH IP address and the default port number. If the port number is not the default number, you need to use -p to specify the port number. Example: [root@ky15 ~]# SSH [email protected] # default port 22 root The authenticity of host '192.168.91.101 (192.168.91.101)' can't be established. ECDSA key fingerprint is required SHA256:o72+YjT+8laQRofsv2dFlcx099aeoI92rloek3ZVrUY. ECDSA key fingerprint is MD5:a7:9c:69:35:16:17:21:cb:0e:4f:0d:42:44:16:3a:f7. Are you sure you want to continue connecting (yes/no)? [email protected] 's password: the Last login: Tue Sep 28 22:23:522021 [root@ky15-1 ~]# # SSH -l [remote host username] [Remote server host name or IP address] -p port -l: -l option to specify the login name. -p: indicates the -p option to specify the login port. (If the server port is not the default one, you need to use -p to specify the login port.) Example: [root@ky15 ~]# SSH -l root 192.168.91.101 [email protected]'s password: Last login: Tue Sep 28 22:25:40 2021 from 192.168.91.100 Tue Sep 28 22:25:40 2021 from 192.168.91.100Copy the code

1.3 Server Configuration

1.3.1 Common Configuration Items:

ListenAddress IP LoginGraceTime 2m PermitRootLogin yes ListenAddress IP LoginGraceTime 2m PermitRootLogin yes # default Ubuntu does not allow root remote SSH login StrictModes yes Permission etc. MaxAuthTries 6 # pecon-year the maximum number of authentication # sSH-O Numberofpasswordprompt [email protected] Use attempts permitted per connection. Once the number of failures with this option  reaches half this value, Additional failures are logged. The default is 6. MaxSessions 10 # Maximum session on The same connection PubkeyAuthentication Yes # Key-based authentication PermitEmptyPasswords no # PasswordAuthentication yes # connection based on user name and password GatewayPorts no ClientAliveInterval 10 # Unit: second ClientAliveCountMax 3 # Default 3 UseDNS yes # increase speed no GSSAPIAuthentication Yes # increase speed no MaxStartups # unauthenticated connection maximum Default value 10 Banner /path/file # Whitelist Blacklist AllowUsers user1 user2 user3@ip (Host restriction) DenyUsers user1 user2 user3 AllowGroups g1 g2 DenyGroups g1 g2Copy the code

Best practices of the SSH service

  1. You are advised to use a non-default port
  2. Protocol Version 1 is disabled
  3. Restrict the users that can log in
  4. Set the timeout period of idle sessions
  5. Configure SSH access policies using the firewall
  6. Listen only for specific IP addresses
  7. Password-based authentication, use A strong password policy, such as: tr – dc A – Za – z0-9 _ < / dev/urandom | head – 12 c | xargs
  8. Use key-based authentication
  9. Do not use empty passwords
  10. Prohibit user root from logging in directly
  11. Limit the SSH access frequency and the number of concurrent SSH connections
  12. Analyze logs regularly

1.3.2 Login using a Key Pair without interactive Authentication

Principle:

  • User/Password
  • Based on the secret key

User/Password:

  1. When the client initiates an SSH request, the server sends its public key to the user

  2. The user encrypts the password based on the public key sent by the server

  3. The encrypted information is sent back to the server, which decrypts it with its own private key. If the password is correct, the user logs in successfully

Key-based login mode

  1. Start by generating a pair of keys on the client side (ssh-keygen)

  2. Copy the client’s public key ssh-copy-id to the server

  3. When the client sends a connection request again, including the IP address and user name

  4. When the server gets the request from the client, it looks in authorized_keys () and, if it has a responding IP and user, generates a random string, such as KGC

  5. The server encrypts the public key with the copy from the client and sends it to the client

  6. After receiving the message from the server, the client decrypts it using the private key and sends the decrypted string to the server

  7. After receiving the string from the client, the server compares it with the previous string and allows password-free login if it is the same

[lisi@ky15-1 root]$ ssh-keygen --help unknown option -- - usage: SSH - the keygen [- q] [- b bits] [-t dsa | ecdsa | ed25519 | rsa | rsa1] [lisi @ root ky15-1] $# SSH - the keygen - t ecdsa generated key file Generating public/private ecdsa key pair. Enter file in which to save the key (/home/lisi/.ssh/id_ecdsa): Created directory '/home/lisi/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Passphrases do not match. Try again. Enter passphrase (empty for no passphrase): Enter same passphrase again: Passphrases do not match. Try again. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/lisi/.ssh/id_ecdsa. Your public key has been saved in /home/lisi/.ssh/id_ecdsa.pub. The key fingerprint is: SHA256:hbO1nsVS739lrS+T4lMg4NbYihnyx96e0eYFgqP6eK4 lisi@ky15-1 The key's randomart image is: +---[ECDSA 256]---+ | | | .. | | .o=o . | | . . +*++.. | | o *S.+.+.. .| | +.+o * o. +| | .o .+ o.o+.| | o. . .=o.=.. | | E=o .o.oo ++| +----[SHA256]-----+ [lisi@ky15-1 .ssh]$ cd ~ [lisi@ky15-1 .ssh]$ ssh-copy-id -i id_ecdsa.pub [email protected] # import the public key file to the opposite server [root@ky15 home]# CD zhangsan/ [root@ky15 Zhangsan]#ls -a. .bash_history .bash_profile .cache .mozilla .. .bash_logout .bashrc .config .ssh [root@ky15 zhangsan]#cd .ssh/ [root@ky15 .ssh]#ls authorized_keys [root@ky15 .ssh]#cat  authorized_keys ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKQSA9IyCq51N+pngvuFSwoBsWBlzBPn1/pI73wSB+onDfd9i81aTl+QBysQFrDfWUcx LCKniUOP0BewP5rxD +o= lisi@ky15-1 interactive login [lisi@ky15-1. SSH]$SSH -add Enter passphrase for /home/lisi/.ssh/id_ecdsa: Identity added: /home/lisi/.ssh/id_ecdsa (/home/lisi/.ssh/id_ecdsa) # enter the previous password [lisi@ky15-1. SSH]$SSH [email protected] Last login: Wed Sep 29 00:24:262021 from 192.168.91.101 [zhangsan@ky15 ~]$ssh-keygen -t ecdsa ssh-copy-id -i id_ecdsa.pub [email protected] ssh-add # has nothing to do with user passwords # has nothing to do with IP addresses # Has nothing to do with key pairsCopy the code

1.4 the SSH client

SCP command — Remote secure replication

SFTP command — Secure FTP download

Format: SFTP user@host

[root@ky15-1 .ssh]# SFTP [email protected]


[root@ky15-1 .ssh]# SFTP - oPort = 220 [email protected]
# If fixed port is changed
Copy the code

2.TCP Wrappers

In Linux, many network services provide access control mechanisms for clients, such as Samba, BIND, HTTPD, OpenSSH, and so on. This section describes another defense mechanism, TCP Wrappers (TCP envelopes), that provides additional security as a special line of defense between application services and the network.

TCP Wrappers, which “wrap” TCP server programs to listen on TCP server ports, has been added

A security check process in which an incoming connection request must pass this level of security before being granted access to the real thing

, as shown in Figure 4.3. TCP Wrappers can also log all attempts to access the protected service,

Provides rich security analysis data for administrators.

2.1 Policy Configuration format

The two policy files have opposite functions, but the format of the configuration record is the same, as shown below.

Server list: client address list

The server list, client address list are separated by colons, and multiple items in each list are separated by commas

(1) List of service programs

The list of services can be divided into the following categories.

ALL: indicates ALL services

Single service: for example, “VSFTPD”

A list of multiple services: e.g. “VSFTPD, SSHD”

2) Client address list

The client address list can be divided into the following categories.

  1. ALL: indicates any client address.
  2. LOCAL: indicates the LOCAL address.
  3. Single IP address: for example, 192.168.4.4
  4. Network segment address: such as “192.168.4.0/255.255.255.0”
  5. With “.” Start domain name:.bdqn.com matches all hosts in the bdqn.com domain.
  6. With “.” End network address: for example, 192.168.4. Matches the entire 192.168.4.0/24 network segment
  7. Embed wildcard”“”?” : Indicates a character of any length, while the latter indicates only one character, for example, 10.0.8.2
  8. Matches all IP addresses starting with 10.0.8.2. Do not use “. Mixing of start and end patterns
  9. List of multiple client addresses: for example, 192.168.1., 172.16.16.,.bdqn.com

2.2 Basic Principles of Access Control

Note the blacklist and whitelist of sshd_config
[root@ky15 ~]#vim /etc/ssh/sshd_config 



[root@ky15 ~]#ls /etc/host
host.conf    hostname     hosts        hosts.allow  hosts.deny
[root@ky15 ~]#vim /etc/hosts.allow 
# Configure format service: address (client)
# addSSHD: 192.168.91.101 [root@ky15 ~]#vim /etc/hosts.denySSHD: ALLCopy the code

3. Lightweight automatic o&M tool PSSH

Several automated operation and maintenance tools are provided in EPEL sources

  • PSSH: A python based tool for executing commands on multiple servers, and also for file replication, provided based on SSH

    And SCP multiple parallel tools project: code.google.com/p/parallel-…

  • PDSH: Parallel Remote shell program, is a multithreaded remote shell client, can execute multiple remote in Parallel

    Command on the host. Several different remote shell services can be used, including RSH, Kerberos IV and SSH, projects:

    pdsh.googlecode.com/

  • Mussh: Multihost SSH wrapper, a shell script that allows commands to be executed over SSH on multiple hosts

    To make. Ssh-agent and RSA/DSA keys can be used to reduce the input password, project:

    www.sourceforge.net/projects/mu…

The PSSH command options are as follows:

-h: indicates A host character string in the format of [user@]host[:port] -h file: indicates A host list file in the format of [User@]host[:port] -a: indicates the manual password input mode. -I: indicates the output of information processed internally by each server. -l: indicates the user name used for login. Number of concurrent threads [Optional] -o: output file directory [Optional] -e: error output file [Optional] -t: TIMEOUT TIMEOUT period, 0 unlimited [Optional] -o: SSH option -p: displays information returned by the server. -v: details mode --version: views the versionCopy the code

4selinux

4.1 What is Selinux

SELinux, short for Security Enhanced Linux, is developed by the U.S. National Security Agency (NSA) in collaboration with other Security agencies, such as SCC, to enhance the Security of traditional Linux operating systems. Solve all kinds of permission problems (such as root permission is too high) in traditional Linux autonomous access control (DAC) system.

The SELinux project was made open source under the GPL in 2000, and became increasingly popular when Red Hat included SELinux in its Linux distribution. SELinux is now widely used by many organizations, and almost all Linux kernels above 2.6 integrate SELinux functionality.

For starters, SELinux is a functional module deployed on Linux to enhance system security.

Having said that, it is important for the reader to understand the characteristics of these two access control systems in detail:

  • Discretionary Access Control (DAC)

    Is the default access control mode of Linux, which determines whether a user can access files and directories based on the user’s identity and RWX permissions. However, we also found some problems in the actual use of DAC access control:

    1. If the root permission is too high, the RWX permission does not take effect for the root user. Theft of the root user or misoperations of the root user pose a fatal threat to the Linux system.
    2. Linux default permissions are too simple, with only the identity of the owner, owning group, and others, and only the read, write, and execute permissions, which is not conducive to the segmentation and setting of permissions.
    3. Improper permission allocation will lead to serious consequences, such as setting 777 permission for sensitive files or directories, or setting special permission for sensitive files — SetUID permission, etc.
  • Mandatory Access Control (MAC) is the default policy rule of SELinux to Control the Access of a specific process to file resources on the system. That is, even if you are root, you cannot access a file resource if you use the wrong process.

In this way, SELinux controls not only users and permissions, but also processes. SELinux’s rules policy determines which file resources each process can access and by which processes each file resource can be accessed.

However, with so many processes and so many files on the system, it would be too much work to assign and specify them manually. So SELinux provides a lot of default policy rules that are pretty well set up, and we’ll learn how to view and manage them later.

As an example, suppose a vulnerability is found on Apache that allows a remote user to access sensitive files on the system (such as /etc/shadow). If SELinux is enabled on Linux, then the remote user accessing /etc/shadow via Apache will be blocked by SELinux because the Apache service process does not have permission to access /etc/shadow. It protects the Linux system.

4.2 the selinux role

Traditional Linux system security uses DAC (autonomous access control), while SELinux is a security enhancement module deployed in Linux system, which provides improved security for Linux system by using MAC (forced access control) for process and file resources.

It is important to note that SELinux’s MAC does not completely replace the DAC. On the contrary, it is an additional layer of security for Linux system security. In other words, when using SELinux, the DAC is still used, and will be used first, if access is allowed, Then use the SELinux policy; Conversely, if the DAC rule denies access, there is no need to use the SELinux policy at all.

For example, if a user tries to perform an operation on a file that does not have execute permission (RW -), the traditional DAC rules deny access to the user, thus eliminating the need for the SELinux policy.

SELinux has several advantages over traditional Linux DAC security controls, such as:

  • It uses MAC control, which is considered the strongest access control method.
  • It gives the principal (user or process) minimal access privileges, which means that each principal is given only a limited set of permissions necessary to perform the related tasks. By granting minimal access privileges, a principal can be prevented from adversely affecting other users or processes.
  • In the SELinux management process, each process has its own running area (called a domain), and each process only runs in its own domain and cannot access other processes and files unless special permissions are granted.
  • SELinux can be adjusted to Permissive mode, which allows you to view the impression created after SELinux is executed on your system. In Permissive mode, SELinux still logs perceived security vulnerabilities, but does not block them.

More on SELinux mode Settings will be covered in a later section.

In fact, the most straightforward way to see the benefits of SELinux is to look at what happens when SELinux is not running on a Linux system.

For example, the Web server daemon (HTTD) is listening for what is happening on a port and comes in with a simple request from a Web browser to view the home page. Unconstrained by SELinux, the HTTPD daemon hears the request and can do the following:

  1. Any file or directory can be accessed based on the RWX permissions of the associated owner and group;
  2. Complete activities that pose security concerns, such as allowing file uploads or changing system displays;
  3. You can listen for incoming requests on any port.

But on a selinux-constrained system, the HTTPD daemon is more tightly controlled. Still using the example above, Httped can only listen on ports that SELinux allows it to listen on. SELinux also prevents HTTPD from accessing any files that are not properly set for security context and rejects unsafe activities that are not explicitly enabled in SELinux.

Thus, SELinux essentially limits malicious code activity in Linux systems programmatically.