OpenSSH SSH protocol implementation

OpenSSH is an implementation of the SSH protocol. Generally used by scp or sftp for remote login, backup, remote file transfer and other functions. SSH is the perfect guarantee of the confidentiality and integrity of data transmission between two networks or systems. Still, its biggest advantage is the use of public key encryption for server authentication. There are rumors of OpenSSH zero-day vulnerabilities from time to time. This article describes how to set up your Linux or Unix-like system to improve the security of sshd.

OpenSSH default settings

TCP port – 22

OpenSSH service configuration file – sshd_config (located in /etc/ssh/)

1, based on the public key login

The OpenSSH service supports a variety of authentication methods. It is recommended to use public key encryption verification. First, create a key pair on your local computer using the following ssh-keygen command:

1024-bit or lower DSA and RSA encryption is weak, please do not use it. When considering ssh client backwards compatibility, use the RSA key instead of the ECDSA key. All ssh keys use either ED25519 or RSA, not other types.

$ssh-keygen -tkey_type -bbits -C"comment"

Example:

$ssh-keygen -ted25519 -C"Login to production cluster at xyz corp"

or

$ssh-keygen -trsa -b4096 -f ~/.ssh/id_rsa_aws_$(date +%Y-%m-%d) -C"AWS key for abc corp clients"

Next, install the public key using the ssh-copy-id command:

$ssh-copy-id -i /path/to/public-key-file user@host

or

$ssh-copy-id user@remote-server-ip-or-dns-name

Example:

$ssh-copy-id vivek@rhel7-aws-server

When prompted for a username and password, verify that the login based on the ssh public key is working:

$ssh vivek@rhel7-aws-server

2, disable root user login

Before disabling the root user login, verify that the normal user can log in as root. For example, allow user vivek to log in as root using the sudo command.

How to add user vivek to a sudo group on a Debian/Ubuntu system

Allow users in the sudo group to execute any command. Add the user vivek to the sudo group:

$sudo adduser vivek sudo

Use the id command to verify the user group.

$id vivek

How to add user vivek to the sudo group in the CentOS/RHEL system

Allow users in the wheel group to execute all commands on CentOS/RHEL and Fedora systems. Add the user vivek to the wheel group using the usermod command:

$sudo usermod -aG wheel vivek

$id vivek

Test sudo permissions and disable ssh root login

Test and make sure that user vivek can log in as root and execute the following command:

$sudo -i

$sudo /etc/init.d/sshd status

$sudo systemctl status httpd

Add the following to the sshd_config file to disable root login:

PermitRootLogin no

ChallengeResponseAuthentication no

PasswordAuthentication no

UsePAM no

3, disable password login

All password logins should be disabled, leaving only the public key login. Add the following to the sshd_config file:

AuthenticationMethods publickey

PubkeyAuthentication yes

Older versions of sshd users on CentOS 6.x/RHEL 6.x systems can use the following settings:

PubkeyAuthentication yes

4, limit user ssh access

By default, all system users can log in with a password or public key. But sometimes you need to create a UNIX/Linux user for the FTP or email service. However, these users can also log in to the system using ssh. They will get full access to the system tools, including compilers and scripting languages ​​such as Perl, Python (which can do a lot of crazy things by opening network ports). Allow users root, vivek, and jerry to log in to the system via SSH by adding the following to the sshd_config file:

AllowUsers vivek jerry

Of course, you can also add the following to the sshd_config file to achieve the effect of denying only a subset of users to log in to the system via SSH.

DenyUsers root saroj anjali foo

You can also disable or allow users to log in via sshd by configuring Linux PAM. You can also allow or disallow a list of user groups to log in to the system via ssh.

5, disable the empty password

You need to explicitly disable the empty password account remote login system and update the following contents of the sshd_config file:

PermitEmptyPasswords no

6, use a strong password for the ssh user or key

The importance of using strong passwords and phrases for keys is not overemphasized. Violent hacking works because users use dictionary-based passwords. You can force users to avoid dictionary passwords and use John's Ripper tool to detect weak passwords. Here's a random password generator (put it under your ~/.bashrc):

Genpasswd(){

Locall=$1

["$l" == ""] && l=20

Tr -dcA-Za-z0-9_ < /dev/urandom | head -c${l} | xargs

run:

Genpasswd16

Output:

uw8CnDVMwC6vOKgW

7. Configure a firewall for port 22 of SSH.

You need to update the iptables/ufw/firewall-cmd or pf firewall configuration to configure the firewall for TCP port 22 of ssh. In general, the OpenSSH service should only allow local or other remote address access.

Netfilter (Iptables) configuration

Update /etc/sysconfig/iptables (Redhat and its derived system-specific files) The implementation only accepts connections from 192.168.1.0/24 and 202.54.1.5/29, enter:

-ARH-Firewall-1-INPUT -s192.168.1.0/24 -mstate --state NEW -ptcp --dport22 -jACCEPT

-ARH-Firewall-1-INPUT -s202.54.1.5/29 -mstate --state NEW -ptcp --dport22 -jACCEPT

If you are using IPv6 at the same time, you can edit /etc/sysconfig/ip6tables (Redhat and its derived system-specific files) and type:

-ARH-Firewall-1-INPUT -sipv6network::/ipv6mask -mtcp -ptcp --dport22 -jACCEPT

Replace ipv6network::/ipv6mask with the actual IPv6 network segment.

UFW under Debian/Ubuntu Linux

UFW is an acronym for Uncomplicated FireWall, which is primarily used to manage Linux firewalls to provide a user-friendly interface. Enter the following command to allow the system to only allow network segment 202.54.1.5/29 to access port 22:

$sudo ufw allow from202.54.1.5/29toany port22

*BSD PF firewall configuration

If you use the PF firewall /etc/pf.conf configuration is as follows:

Passinon$ext_ifinetprototcpfrom{192.168.1.0/24,202.54.1.5/29}to$ssh_server_ip port ssh flagsS/SA synproxy state

8. Modify the SSH port and bind the IP address.

Ssh defaults to listening to all available NICs in the system. Modifying and binding the ssh port helps avoid violent scripting connections (many brute force scripts only try port 22). Update the following contents of the file sshd_config to bind port 300 to IP 192.168.1.5 and 202.54.1.5:

Port300

ListenAddress192.168.1.5

ListenAddress202.54.1.5

Active scripting is a good choice when you need to accept connections to dynamic WAN addresses, such as fail2ban or denyhosts.

9, using TCP wrappers (optional)

The TCP wrapper is a host-based access control system that filters network access from the Internet. OpenSSH supports TCP wrappers. You only need to update the following in the file /etc/hosts.allow to make SSH only accept connections from 192.168.1.2 and 172.16.23.12:

Sshd : 192.168.1.2172.16.23.12

10. Block SSH cracking or brute force attacks

Violence is a method of using a large number of (username and password) combinations in a single or distributed network to try to connect to an encryption system. The following software can be used to deal with brute force attacks:

DenyHosts is a Python-based SSH security tool. The tool responds to brute force attacks by monitoring the illegal login logs in the authorization log and blocking the original IP.

How to set up DenyHosts under RHEL / Fedora and CentOS Linux.

Fail2ban is another similar tool used to prevent attacks against SSH.

Sshguard is a tool that uses pf to prevent attacks against SSH and other services.

Security/sshblock Prevents abuse of SSH and attempts to log in.

The IPQ BDB filter can be thought of as a simplified version of fail2ban.

11. Limit the incoming rate of TCP port 22 (optional)

Both netfilter and pf provide a rate limiting option that simply limits the incoming rate of port 22.

Iptables example

The following script will prevent the client from attempting to log in more than 5 times within 60 seconds.

#!/bin/bash

Inet_if=eth1

Ssh_port=22

$IPT -IINPUT -ptcp --dport${ssh_port} -i${inet_if} -mstate --stateNEW -mrecent --set

$IPT -IINPUT -ptcp --dport${ssh_port} -i${inet_if} -mstate --state NEW -mrecent --update --seconds60 --hitcount5

Call the above script in your iptables script. Other configuration options:

$IPT -AINPUT -i${inet_if} -ptcp --dport${ssh_port} -mstate --stateNEW -mlimit --limit3/min --limit-burst3 -jACCEPT

$IPT -AINPUT -i${inet_if} -ptcp --dport${ssh_port} -mstate --stateESTABLISHED -jACCEPT

$IPT -AOUTPUT -o${inet_if} -ptcp --sport${ssh_port} -mstate --stateESTABLISHED -jACCEPT

# another one line example

# $IPT -A INPUT -i ${inet_if} -m state --state NEW,ESTABLISHED,RELATED -p tcp --dport 22 -m limit --limit 5/minute --limit-burst 5-j ACCEPT

See the iptables user manual for additional details.

*BSD PF example

The following script will limit the number of connections per client to 20 and no more than 15 connections in 5 seconds. If the client triggers this rule, it is added to the abusive_ips table and the client is restricted from joining. Finally, the flush keyword kills all connections to the client that triggered the rule.

Sshd_server_ip = "202.54.1.5"

Table Sive

Block inquick from

Pass inon$ext_if proto tcp to$sshd_server_ip port ssh flagsS/SA keep state(max-src-conn20,max-src-conn-rate15/5,overload Flush)

12, use the port to knock the door (optional)

A port knock is a method of opening a connection attempt on a firewall by generating a connection attempt on a set of pre-designated closed ports. Once the specified port connection order is triggered, the firewall rules are dynamically modified to allow the host sending the connection to connect to the specified port. The following is an example of a port knock using iptables:

$IPT -Nstage1

$IPT -Astage1 -mrecent --remove --name knock

$IPT -Astage1 -ptcp --dport3456 -mrecent --set --name knock2

$IPT -Nstage2

$IPT -Astage2 -mrecent --remove --name knock2

$IPT -Astage2 -ptcp --dport2345 -mrecent --set --name heaven

$IPT -Ndoor

$IPT -Adoor -mrecent --rcheck --seconds5 --name knock2 -jstage2

$IPT -Adoor -mrecent --rcheck --seconds5 --name knock -jstage1

$IPT -Adoor -ptcp --dport1234 -mrecent --set --name knock

$IPT -AINPUT -m --state ESTABLISHED,RELATED -jACCEPT

$IPT -AINPUT -ptcp --dport22 -mrecent --rcheck --seconds5 --name heaven -jACCEPT

$IPT -AINPUT -ptcp --syn -jdoor

13, configure the idle timeout logout duration

Users can connect to the server via ssh and configure a timeout interval to avoid unattended ssh sessions. Open sshd_config and make sure to configure the following values:

ClientAliveInterval300

ClientAliveCountMax0

Set an idle timeout in seconds (300 seconds = 5 minutes). Once the idle time exceeds this value, the idle user will be kicked out of the session. See the BASH / TCSH / SSH user for how to automatically log out the idle timeout for more details.

14. Enable warning slogans for ssh users

Update the sshd_config file as follows to set the user's alert slogan:

Banner /etc/issue

`/etc/issue sample file:

The above is a standard example, please consult your team of lawyers for more user agreements and legal details.

15, disable the .rhosts file (to be verified)

It is forbidden to read the user's ~/.rhosts and ~/.shosts files. Update the following in the sshd_config file:

IgnoreRhosts yes

SSH can emulate outdated rsh commands, so unsafe RSH connections should be disabled.

16. Disable host-based authorization (verification required)

Disable host-based authorization and update the following options for the sshd_config file:

HostbasedAuthentication no

17. Patch OpenSSH and operating system

It is recommended that you use tools like yum, apt-get, and freebsd-update to keep your system up to date with the latest security patches.

18, Chroot OpenSSH (lock the user in the home directory)

By default, users can browse directories such as /etc, /bin, and so on. You can use chroot or other proprietary tools such as rssh to protect ssh connections. Starting with version 4.8p1 or 4.9p1, OpenSSH no longer needs to rely on third-party tools such as rssh or complex chroot(1) to lock users into the home directory. You can use the new ChrootDirectory directive to lock users in their home directory, see this blog post.

19. Disable the client's OpenSSH service

OpenSSH services are not required for workstations and laptops. If you do not need to provide ssh remote login and file transfer capabilities, you can disable the sshd service. CentOS / RHEL users can disable or remove openssh-server using the yum command:

$sudo yum erase openssh-server

Debian / Ubuntu users can use the apt command /apt-get command to remove openssh-server:

$sudo apt-get remove openssh-server

It may be necessary to update the iptables script to remove the exception rules for ssh. The CentOS / RHEL / Fedora system can edit the files /etc/sysconfig/iptables and /etc/sysconfig/ip6tables. Finally restart the iptables service:

# service iptables restart

# service ip6tables restart

20. Additional tips from Mozilla

If you are using the 6.7+ version of OpenSSH, you can try the following settings:

Use the following command to get the encryption method supported by OpenSSH:

$ssh -Qcipher

$ssh -Qcipher-auth

$ssh -Qmac

$ssh -Qkex

$ssh -Qkey

How do I test the sshd_config file and restart/reload the SSH service?

Check the validity of the configuration file and the integrity of the key before restarting sshd. Run:

$sudo sshd -t

Extended test mode:

$sudo sshd -T

Finally, restart the sshd service on a Linux or Unix-like system based on the version of the system:

$[sudo systemctl start ssh][38]## Debian/Ubunt Linux##

$[sudo systemctl restart sshd.service][39]## CentOS/RHEL/Fedora Linux##

$doas /etc/rc.d/sshd restart## OpenBSD##

$sudo service sshd restart## FreeBSD##

other suggestion

Enhance SSH security with 2FA – Multi-attribute can be enabled using the OATH Toolkit or DuoSecurity.

Keychain-based authentication – The keychain is a bash script that makes key-based authentication very flexible and convenient. It provides better security than a passwordless key.

Mineral Insulated Cable

Mineral Insulated Cable,Copper Mineral Insulation Cable,Copper Core Copper Sheath Cable,Fire Resistant Cable

Baosheng Science&Technology Innovation Co.,Ltd , https://www.bscables.com