In this short note, I have put together ways to increase the security of an ssh server. The most basic and simple to perform techniques are described, and more complex ones are only indicated for interested readers.

Basic Techniques

All actions are carried out in configuration file sshd daemon -- /etc/ssh/sshd_config . Below I will provide part of my configuration file with comments.

### Network ### # We use a non-standard port (>1024) port 5679 # We use only IPv4 connections # inet = IPv4, inet6 = IPv6, any = both AddressFamily inet # You can only accept connections from certain IP addresses #ListenAddress 0.0. 0.0 # We use the second version of the protocol, because the first is subject to # known Protocol 2 vulnerabilities # Disable graphics redirection (X server) until # you explicitly need it X11Forwarding no # Disable Disable TCPKeepAlive and use ClientAliveInterval instead # to prevent attacks like TCP Spoofing TCPKeepAlive no # Kick the user after 10min (600 sec) of inactivity ClientAliveInterval 600 ClientAliveCountMax 3 ### Key configuration files ### # HostKeys for protocol version 2 HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_dsa_key # Use an unprivileged process to # process incoming from the client traffic # sandbox - openSSH >= 5.9 ("yes" - for lower versions) UsePrivilegeSeparation sandbox # When these values ​​change, it requires deletion old key# /etc/ssh/ssh_host_rsa_key(,.pub), and create a new one by # restarting sshd. # # Key lifetime, i.e. How long will it take for it to be generated? new key# in case the previous one was used. KeyRegenerationInterval 1h # key strength ServerKeyBits 2048 # Allow authorization using a public key PubkeyAuthentication yes # Storage location of trusted keys in the user directory AuthorizedKeysFile .ssh/authorized_keys ### Logging ### # Prefix for syslog SyslogFacility AUTH # message detail level for sshd itself LogLevel INFO ### Authentication ### # list of allowed users AllowUsers ivan # limit the time for entering the password for the ssh key LoginGraceTime 30s # prohibit remote login under the root account PermitRootLogin no # Enable explicit checking of the rights of files and directories with ssh keys StrictModes yes # How many times to ask for a password if you enter it incorrectly MaxAuthTries 3 # Prohibit login with an empty password PermitEmptyPasswords no # Prohibit login with a password in principle # (Use a public/private key instead) PasswordAuthentication no # Disable the use of "challenge-response" authorization, # because . it is useless when using keys ChallengeResponseAuthentication no # Since we do not use a password, we do not need (PAM, login(1)) UsePAM no UseLogin no # Allow the client to send only a certain set environment variables# RH BZ#CVE-2014-2532 # ShellShock exploit 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

These are the parameters that are configured in the sshd configuration file. After changing the settings, you need to restart the sshd service.

Comments

  • When using key authentication, a key is required previously generate on the client machine and copy the public key to the server. Example:
client $ ssh-keygen client $ cat ~/.ssh/id_rsa.pub | ssh -p 5679 [email protected]"cat >> ~/.ssh/authorized_keys"
  • The file /var/log/auth.log will contain messages from sshd. In case this file is missing, you need to configure your logging system. example for syslog and syslon-ng. I'm using syslog-ng and needed to add the following lines to the /etc/syslog-ng/syslog-ng.conf file:
destination authlog ( file("/var/log/auth.log"); ); log ( source(src); destination(authlog); );

and restart the syslog-ng service.

  • If you use a non-standard port, you may need to configure your firewall (iptables, firewalld, etc).
    Example settings for iptables:
root# iptables -A INPUT -p tcp -m state --state NEW,ESTABLISHED --dport 5679 -j ACCEPT root# service iptables save root# iptables -L -n Chain INPUT (policy ACCEPT) target prot opt ​​source destination ACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0 ACCEPT tcp - - 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:80 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/ 0 state NEW,ESTABLISHED tcp dpt:5679 ...

If that's not enough

It's just basic settings. Additionally, you can configure

  • firewall (iptables)

As soon as a service “lights up” on a public network, it instantly becomes a target for attack. One of the problems is an attempt to gain access using passwords (brute force). And SSH in this case is no exception.

Analysis of the authentication log file /var/log/auth.log or analogues shows that an attempt to guess a password is usually made from several IPs at once and is extended over time.

SSH Bruteforce Protection

You can protect yourself from this in different ways:

  • Using SSH daemon configuration options
  • Packet filter
  • Special Applications
  • Port knocking

The simplest and effective way- this is to change the default port 22, for example, to 2002, if this does not interfere with other tasks. We make an entry in /etc/ssh/sshd_config:

After this, attempts to guess passwords practically stop. There are times when you cannot change the port. Alternatively, you can restrict access via SSH certain users(specifically root) or group. In sshd_config a number of parameters are responsible for this: AllowUsers, AllowGroups, DenyUsers and DenyGroups. It’s convenient that you can specify an IP or subnet with your login. For example, let's allow access to the user admin and user, the latter from only one IP:

Another effective option for protection against brute force is the use of certificates for authentication. And with the help special parameter match, you can create a conditional block in which you can override the parameters of the global section. For example, we will prohibit login via SSH using a password for the root user, allowing everyone else:

# Allow everyone access using a password
PasswordAuthentication yes
# root will only use the certificate
match user root
PasswordAuthentication no
KbdInteractiveAuthentication no

Using TCP Wrapper, we can also restrict access to any service only from certain IPs; to do this, you just need to write it in the /etc/hosts.allow or /etc/hosts.deny file the right rule. Let's allow access in /etc/hosts.allow only from the required subnet:

sshd:192.168.1.0/24:allow

Or in /etc/hosts.deny:

sshd: ALL: deny
sshd: ALL EXCEPT 192.168.1.0/24: allow

The packet filter allows you to very precisely set connection parameters, discarding unnecessary packets. With its help, it is easy to limit access to port 22 to only certain addresses. Simple example:

iptables -A INPUT -s !192.168.0.1 -p tcp -m tcp --dport 22 ↵
-j REJECT -reject-with icmp-port-unreachable

Filtering packets by ports and IP addresses is not very effective if the Administrator is not tied to a workplace. In this case they will help special utilities: Fail2ban, Sshguard. Fail2ban was originally developed for SSH security. Although today it is already a framework that can be easily customized for any application. The operating principle is very simple. The daemon periodically checks the logs for records of any suspicious activity. The suspicious IP address is then blocked using iptables or TCP Wrapper. After the time specified in the settings, the blocking is usually removed so as not to accidentally block a legitimate node. When a rule is triggered, an event is written to the log /var/log/fail2ban.log, and an email can be sent.

One process can control several services at once, and the package comes with ready-made settings for popular Linux applications. By default, only SSH is protected.

On Ubuntu and Debian it is installed with the command:

$ sudo apt-get install fail2ban

All settings are made in several files located in the /etc/fail2ban directory. fail2ban.conf stores the launch parameters of the daemon itself, jail.conf describes the controlled services (inside the SSH section).

Enabled = true
port = 22
filter = sshd
logpath = /var/log/auth.log
maxretry = 3

Filters and actions are written in files located in the filter.d and action.d subdirectories. By default, all files have the .conf extension; it is better not to touch them (including jail.conf). All changes should be made to a file with the .local extension (for example, jail.local), the parameters of which replace the settings from the first one, and will not be lost during the update. To check the operation of the filter, you can use the fail2ban-regex utility.

Several rules for protecting access to the ssh server.

1. Add to the ssh server configuration to listen to one more port, in addition to the standard one. (For ease of remembering, you can use 4 repeating numbers for all your servers).

$ sudo vi /etc/ssh/sshd_config Port 22 Port xxxx

2. We limit calls to port 22 only to trusted IP addresses *for example 8.8.8.8 (you can make several such rules, work/home)

$ sudo vi /etc/sysconfig/iptables -A INPUT -s 8.8.8.8 -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

3. Don’t forget to check if we are using ipv6; if so, then close the unnecessary one

$ sudo vi /etc/sysconfig/ip6tables *filter:INPUT ACCEPT :FORWARD ACCEPT :OUTPUT ACCEPT -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p ipv6-icmp -j ACCEPT -A INPUT - i lo -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT -A INPUT -j REJECT --reject-with icmp6-adm-prohibited -A FORWARD -j REJECT --reject-with icmp6-adm-prohibited COMMIT

In order to use ssh only on a specific address, it is enough in the configuration file sshd_config specify the parameter ListenAddress(for example ListenAddress 74.125.200.100). In this case, ssh will only be available on this address and will not work via ipv6

4. Use the ssh configuration file on the client side.

Location: ~/.ssh/config

# fix Write failed: broken pipe ServerAliveInterval 120 TCPKeepAlive no # to use short names Host dev-vps # ip address or public Domain name host Hostname 127.0.0.3 # Under which user to log in User developer # Key file for authorization (if used) IdentityFile ~/.ssh/id_rsa.dev

And another example of using a configuration file:
{<1>}

Host ssh-server-1 Hostname 1.2.3.4 User dev Port 1234 Host ssh-server-2 User root # Hostname 192.168.10.20 # nc without -q0 if RHEL based & with -q0 debian based IdentityFile ~/.ssh/id_rsa.work -pc ProxyCommand ssh -q0 ssh-server-1 nc -q0 192.168.10.20 22

And now, when connecting to ssh-server-1, we will immediately jump to the host we need. (Convenient to use, for example, when different keys on servers)

And hipster proxy option:

{<2>}

Download the ngrok client to the server, which is located behind the firewall. We launch the binary and indicate which port we need to forward

SSH is a secure protocol for transferring data (commands, files, video signals, etc.) between computers.

It is enabled by default on VPS and dedicated servers of most hosting providers, as it allows you to easily and securely manage a remote machine. By the way, you can inexpensively rent a VPS server on the Well-Web service. Since SSH is enabled on all VPS, to avoid problems when using Secure Shell, proper SSH protection is necessary.

Disable access from root

First of all, it is recommended to deactivate the ability to remotely connect to the machine under account superuser (root). To do this, you need to find the sshd_config file, which is usually (but not always) located in the /etc/ssh/ directory, and open it.

In it you will need to find the PermitRootLogin item and replace its value with “no”, that is, you should get the following entry:

PermitRootLogin no

Naturally, this will not prevent hacking, but it will still make it somewhat more difficult.

To minimize the possibility of hacking, it is recommended to use authorization using keys instead of login and password authorization. This can be done in several ways. This, by the way, is also a good SSH protection against brute force.

Changing the default port

Since hacking a server via SSH usually occurs through password search (brute force), it would be rational to change the standard port 22 to some other one. This is very easy to do. First of all, you need to open the already mentioned sshd_config file and add one line there:

Port port_number

The entry would look, for example, like this:

Port 3048

This will significantly reduce the number of people wishing to gain unauthorized access to the server. Before changing the port number, be sure to make sure that it will not interfere with other applications. You also need to select a port that is not yet in use so that programs do not conflict because of it.

IP access restriction

Another method of protection that will reduce the likelihood of unauthorized connection to almost zero is setting authorization restrictions. SSH can be configured in such a way that only remote machines with specific IP addresses can log in to the server. To do this, in the sshd_config file in the AllowUser line, you need to add @IP_number to the name of each user. The entry could, for example, look like this:

AllowUsers [email protected], [email protected]

Before using this method, it is recommended to make sure that there are no situations in which you may need to log into the server from a machine whose IP address is not provided by the configuration.

Secure Password

And of course, you should use a password that is resistant to brute force. Long and with as many different symbols as possible, preferably with krakozyabrs. This is a must have.

OpenSSH allows you to perform remote connection to the server, manipulate files and manage the system. Today we want to talk about best methods, which will increase the security of a system based on OpenSSH.

Configuration files

  • /etc/ssh/sshd_config- OpenSSH server configuration file;
  • /etc/ssh/ssh_config- OpenSSH client configuration file;
  • ~/.ssh/- directory in which user SSH settings are stored;
  • ~/.ssh/authorized_keys or ~/.ssh/authorized_keys- a list of keys (RSA or DSA) that are used to connect to user accounts;
  • /etc/nologin- if this file exists in the system, then sshd will prohibit all users except root from connecting to the system;
  • /etc/hosts.allow and /etc/hosts.deny- interdiction system (part of security). Works similar to ACL;
  • Default SSH port - 22

Not needed - turn it off

If your server does not require remote SSH connections, be sure to disable it. On systems like CentOS/RHEL this is done like this:

Chkconfig sshd off yum erase openssh-server

Use SSH version 2

The first version of the SSH protocol has security problems that are addressed in the second version. Therefore, use the second version. Make sure that the Protocol 2 option is specified in the /etc/ssh/sshd_config file.

Limit SSH access

By default, all system users have the ability to connect to the system via SSH. We recommend limiting SSH access for security reasons. For example, to allow SSH for root, merion and networks users:

AllowUsers root merion networks

On the other hand, you can allow access to all users except those specified:

DenyUsers root merion networks

Inactivity time

It is important to indicate the time during which the inactive session will be terminated (completed). This can be done with the following options:

ClientAliveInterval 300 ClientAliveCountMax 0

In this setting, we specified the inactivity time to be 300 seconds (5 minutes).

About .rhosts files

The fact is that this file contains a list of hosts and users. If in this file contains a combination of host and user, then this user will be able to connect to the system via SSH without asking for a password. We recommend disabling this “wonderful” feature:

IgnoreRhosts yes

No host-based authentication!

So-called Host-Based Authentication Allows a user from a specific host to connect to the server. Disable:

HostbasedAuthentication no

Direct connection via root

PermitRootLogin no

Make a banner

For everyone who connects, make a banner in which you can threaten attackers who are trying to commit unauthorized access. The Banner parameter is responsible for setting up the banner.

Port 22 only from the inside!

Make access to system port 22 only through a chain of firewall rules. It is best to leave access only from within the LAN. For example, in Iptables you can give access to 192.168.11.0/24:

A RH-Firewall-1-INPUT -s 192.168.11.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT

Where to listen

By default, SSH listens for connections on all available interfaces. We recommend changing the default port and specifying the IP address on which to wait for connection. For example, we will specify port 962 and IP address 192.168.11.24

Port 962 ListenAddress 192.168.11.24

Cryptographically strong passwords

Use strong passwords. There are many tools on the Internet that will generate a crypto-strong password online, free of charge and without SMS :)

Prohibit empty passwords

There are users without passwords. Their access to SSH must also be denied using the option:

Port 962 PermitEmptyPasswords no

Analyze logs

Set event logging to INFO or DEBUG mode - this will allow you to have expanded control over the system:

LogLevel INFO

Was this article useful to you?

Please tell me why?

We are sorry that the article was not useful for you: (Please, if it is not difficult, indicate why? We will be very grateful for a detailed answer. Thank you for helping us become better!