====== Ubuntu - SSH - Configure sshd ======
===== Backup the existing configuration file =====
First, make a backup of your sshd_config file by copying it to your home directory, or by making a read-only copy in /etc/ssh by doing:"
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.factory-defaults
sudo chmod a-w /etc/ssh/sshd_config.factory-defaults
----
===== Edit the sshd config file =====
Issue the following command:
sudo vi /etc/ssh/sshd_config
----
===== Restrict SSH to version 2 =====
…add in this line if not already in the sshd configuration file, otherwise modify it to be:
Protocol 2
SSH protocol version 1 (SSH-1) has man-in-the-middle attacks problems and security vulnerabilities. SSH-1 is obsolete and should be avoided at all cost.
----
===== Restrict SSH Key Size to 2048 or above =====
…add in this line if not already in the sshd configuration file, otherwise modify it to be:
ServerKeyBits 2048
This defines the number of bits in the ephemeral protocol **version 1** server key.
**NOTE**: This is for **version 1** of the protocol, which is no longer relevant, and should have been disabled in the configuration file by setting **Protocol 2**. So in this context, changing the ServerKeyBits is completely meaningless.
The minimum value is 512, and the default is 1024. If you want to create 4096 bit rsa host keys issue a command like this.
ssh-keygen -q -f /etc/ssh/ssh_host_rsa_key -N '' -b 4096 -t rsa
DSA keys are fixed at 1024 bits, and ecdsa keys can be 256, 384, or 521 bits. So this would generated the ecdsa key with the largest number of bits.
ssh-keygen -q -f /etc/ssh/ssh_host_ecdsa_key -N '' -b 521 -t ecdsa
**NOTE**: The **/etc/ssh/moduli** file contains a list of all keys supported.
A recommendation is to remove the smaller groups from the /etc/ssh/moduli file on the server.
When the client asks for a Diffie-Hellman group, sshd searches the moduli file for groups and picks one at random from the set at least as large as what the client requested. If there are no small keys (e.g. 1k, 1.5k) , then sshd will always use larger ones.
===== Dont listen to all addresses =====
Change the following line in the sshd config file from:
ListenAddress 0.0.0.0
to
ListenAddress 192.168.1.2
Allowing connections from only certain IP addresses makes a system a lot more secure.
----
===== Disable SSH root login =====
Change the following line in the sshd config file from:
PermitRootLogin yes
to
PermitRootLogin no
By default, the SSH daemon ships with remote root logins enabled. Normally Ubuntu does not allow direct access to the root user, so this setting is unimportant. If you have set a password on the root account, this setting can be a potential security risk, and should be disabled.
It is safer to login as another user and use sudo.
**NOTE**: Sometimes it is necessary to allow root logins when doing automated tasks such as backups. To disallow normal logins but allow forced commands, you can use:
PermitRootLogin forced-commands-only
----
===== Disable empty passwords when using SSH =====
…add in this line if not already in the /etc/ssh/sshd_config file, otherwise modify it to be:
PermitEmptyPasswords no
You need to explicitly disallow remote login from accounts with empty passwords.
----
===== Log more information about SSH connections =====
Change the following line in the /etc/ssh/sshd_config file from:
LogLevel INFO
to
LogLevel VERBOSE
By default, the OpenSSH server logs to the AUTH facility of syslog, at the INFO level. To record more information - such as failed login attempts - increase the logging level to VERBOSE.
Now all the details of ssh login attempts will be saved in your /var/log/auth.log file.
If you have started using a different port, or if you think your server is well-enough hidden not to need much security, you should increase your logging level and examine your /var/log/auth.log file every so often. If you find a significant number of spurious login attempts, then your computer is under attack and you need more security.
Whatever security precautions you've taken, you might want to set the logging level to VERBOSE for a week, and see how much spurious traffic you get. It can be a sobering experience to see just how much your computer gets attacked.
It's recommended to log more information if you're curious about malicious SSH traffic.
----
===== Configure the SSH Idle Log Out Timeout Interval =====
...add the following lines to the sshd config file:
ClientAliveInterval 900
ClientAliveCountMax 1
You are setting an idle timeout interval in seconds (900 secs = 15 minutes). After this interval has passed, the idle user will be automatically logged out.
PCI-DSS requires that there be a maximum of 1 concurrent SSH session per user.
----
===== Disable SSH support for .rhost files =====
…add in this line if not already in the sshd configuration file, otherwise modify it to be:
IgnoreRhosts yes
SSH can emulate the behavior of the obsolete rsh command. Therefore disable access via rsh. To ensure that SSH does not read the user's ~/.rhosts and ~/.shosts files.
It's recommended to disable rsh access.
----
===== Disable IPV6 access to SSH (Optional) =====
…add in this line if not already in the sshd configuration file, otherwise modify it to be:
AddressFamily inet
Specifically limit traffic to IPv4. This will limit attack vectors.
The options that can be used for this line are:
* inet = IPv4
* inet6 = IPv6
* any = both
It's recommended to limit the system to IPV4 if IPV6 is not used on the system.
----
===== Enable the SSH welcome banner =====
Change the following line in the sshd config file from:
#Banner /etc/issue.net
to
Banner /etc/issue.net
Now, edit /etc/issue.net and place a warning to unauthorized users. An example of what to include is shown here:
***************************************************************************
NOTICE TO USERS
This computer system is the private property of its owner, whether
individual, corporate or government. It is for authorized use only.
Users (authorized or unauthorized) have no explicit or implicit
expectation of privacy.
Any or all uses of this system and all files on this system may be
intercepted, monitored, recorded, copied, audited, inspected, and
disclosed to your employer, to authorized site, government, and law
enforcement personnel, as well as authorized officials of government
agencies, both domestic and foreign.
By using this system, the user consents to such interception, monitoring,
recording, copying, auditing, inspection, and disclosure at the discretion
of such personnel or officials. Unauthorized or improper use of this
system may result in civil and criminal penalties and administrative
or disciplinary action, as appropriate. By continuing to use this system
you indicate your awareness of and consent to these terms and
conditions of use. LOG OFF IMMEDIATELY if you do not agree to the
conditions stated in this warning.
****************************************************************************
Once this is in place, restart sshd and all users will see this warning before they get the login prompt.
The SSH daemon will allow a message to be displayed to users attempting to log in to the SSH server.
To enable login messages, remove the hash sign # from the Banner line.
For legal reasons, it can be useful to display a banner informing people about their legal rights with regards to your server.
This will obviously not dissuade automated SSH attacks, and will potentially worsen Denial-of-Service (DoS) effects, but it may tip off a human attacker that the system is being looked after closely, and that they should move on to some other system on the network.
----
===== Limit SSH access to only certain users =====
Create a group called **sshusers** and only add users to it who require remote access.
Issue the following command:
sudo groupadd sshusers
…and add users to the group who are allowed to access ssh:
sudo usermod -a -G sshusers peter
Alternatively edit the /etc/group file:
sudo vi /etc/group
...and edit the sshusers line as follows:
sshusers:x:1002:john, james, SHAREWIZ\SWAdmin, SHAREWIZ\john.smith
**NOTE**: Besides groups, individual users can also be allowed to access SSH.
As can be seen from the above example, the last few usernames show **Active Directory** logins. Information on **Active Directory** can be found elsewhere on this site.
Edit the /etc/ssh/sshd_config file:
sudo vi /etc/ssh/sshd_config
Add in the following line:
AllowGroups sshusers
By default, SSH will permit every user with a UNIX account to be able to log in.
You can explicitly allow or deny access for certain users or groups.
An alternative to using AllowGroups is to use the AllowUsers and DenyUsers directives to modify the access rights of these users.
Examples:
To allow access to users username1 and username2, add the following:
AllowUsers username1 username2
To limit access to a specific user from a specific IP address, use something like:
AllowUsers username@192.168.0.2 username2
To deny access to specific users, add the following:
DenyUsers username3 username4 username5
**IMPORTANT**: If using Active Directory logins, remember to add in these users to the sshusers group as well. So in **/etc/group**, add in users such as:
SHAREWIZ\john.smith
----
===== Switch off DNS checking on SSH (Optional) =====
To prevent slow SSH connections, disable DNS checking for SSH.
…add in this line if not already in the sshd configuration file, otherwise modify it to be:
useDNS no
This can be re-enabled at a later stage once DNS is configured.
----
===== Lower the SSH Login Grace Time (Optional) =====
Change the following line in the sshd config file from:
LoginGraceTime 120
to
LoginGraceTime 60
By default, OpenSSH gives you two minutes to type a password in once you've connected. You might want to change this if you are worried about attackers, but need to allow passwords.
This doesn't add much security, but also doesn't make it much harder to legitimately use SSH.
----
===== Disable password authentication for SSH (Optional) =====
Security can be tightened by forcing public key authentication and disabling password authentication entirely. While this greatly enhances security and completely defeats brute-force attacks, it will lock you out of the machine if you lose your private key. Use with caution!
On the client, generate a key pair with a strong passphrase using:
sudo ssh-keygen -t rsa -b 4096
which will display:
Generating public/private rsa key pair.
Enter file in which to save the key (/home//.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home//.ssh/id_rsa.
Your public key has been saved in /home//.ssh/id_rsa.pub.
The key fingerprint is:
xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx @
Next, copy the above key to the server you'd like to login to:
ssh-copy-id -i /home//.ssh/id_rsa.pub @
**NOTE**: This puts the public key in /home//.ssh/authorized_keys on the server.
Verify you can login to the server with your new key:
ssh @
which will prompt:
Enter passphrase for key '/home//.ssh/id_rsa':
@
Once you have verified you can login to the server with your new key pair, update **/etc/ssh/sshd_config** on the server to have Password Authentication disabled.
Change the following line in the sshd config file to disable tunnelled clear text passwords from:
#PasswordAuthentication yes
to
PasswordAuthentication no
----
====== Use SFTP instead of FTP with SSH (Optional) ======
Change the following line in the sshd config file from:
Subsystem sftp /usr/lib/openssh/sftp-server
to
Subsystem sftp internal-sftp
Use Privilege Separation by adding the following statement into the config file
UsePrivilegeSeparation sandbox
This creates an unprivileged child process to deal with incoming network traffic.
After successful authentication, another process will be created that has the privilege of the authenticated user. The goal of privilege separation is to prevent privilege escalation by containing any corruption within the unprivileged processes. The argument must be **yes**, **no**, or **sandbox**.
If **UsePrivilegeSeparation** is set to **sandbox** then the pre-authentication unprivileged process is subject to additional restrictions.
Add a stanza like the following to the *bottom* of the same file.
**WARNING**: It must be at the bottom, because Match groups are only terminated by the end of the file (or another Match stanza):
Match User john
ChrootDirectory %h/public_html
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
Suppose you want to give some users the ability to upload and download files from their home directories (or ~/public_html), but not a full shell account. This is simple to achieve with OpenSSH's SFTP component.
Now john can use SFTP to read from and write to his ~/public_html/ directory, but can't use OpenSSH to get a shell, nor even to read files outside of ~/public_html.
If you have many such users, you can change User john to `Group sftponly, and add users to the sftponly group using usermod(8)`. For FTP on such systems, consider vsftpd: it is more security-conscious than other FTP implementations.
----
===== Disable logins for the **root** user, only allow login for the core user and disable password based authentication. =====
permissions: 0600
owner: root:root
# Use most defaults for sshd configuration.
UsePrivilegeSeparation sandbox
Subsystem sftp internal-sftp
PermitRootLogin no
AllowUsers core
PasswordAuthentication no
ChallengeResponseAuthentication no