How-To: Secure Ubuntu server (fail2ban)

Fail2ban scan the log files of the server and bans IPs that show the malicious signs. Like for exemple too many password failures, seeking for exploits, etc.. It work as a service and create rules that automatically alter iptables configuration. All based on a predefined number of unsuccessful login attempts. This will allow the server to respond to illegitimate access attempts without manual intervention.

 

Install

 

Fail2ban is in package list of Ubuntu. To install it from a command prompt do like this (update first).

 

xxxx@xxxx:~$ sudo apt-get update
xxxx@xxxx:~$ sudo apt-get install fail2ban

 

Configure

 

Configuration files are in the /etc/fail2ban directory.

 

First stop the service

 

xxxx@xxxx:~$ sudo service fail2ban stop

Duplicate the config file jail.conf to keep default options inside (this file can be overwriten when update applied). Put all the specific settings in jail.local

 

xx:~$ sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Now we can modify the jail.local file to adjust to our server case

 

The base

 

Setup the base consist to add one or more source @ip to ignore, the bann time and the number of retry allowed. To do this we need to modify the variables:

 

  1. ignoreip = @ip to ignore (separated by a space).
  2. bantime (in second) = parameter for banned client (default 10 minutes).
  3. findtime (in second) =  a window of time to find a specific number of tries (see below).
  4. maxretry = number of tries before being banned. By default ban a client after 5 tries in 10 minutes (findtime variable).

 

In our case we add the @ip  192.168.0.15 to the list to ignore, change the bantime to 1800 sec (1/2 hour). To do this we edit the /etc/fail2ban/jail.local file like this

 

# The DEFAULT allows a global definition of the options. They can be overridden
# in each jail afterwards.

[DEFAULT]

#
# MISCELLANEOUS OPTIONS
#

# "ignoreip" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not
# ban a host which matches an address in this list. Several addresses can be
# defined using space separator.
ignoreip = 127.0.0.1/8 192.168.0.15

# External command that will take an tagged arguments to ignore, e.g. <ip>,
# and return true if the IP is to be ignored. False otherwise.
#
# ignorecommand = /path/to/command <ip>
ignorecommand =

# "bantime" is the number of seconds that a host is banned.
bantime  = 1800

# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime  = 600

# "maxretry" is the number of failures before a host get banned.
maxretry = 5

 

Email alerts

 

Configure email alerts with the variable destemail, sendername, and mta. To use it you need the Ubuntu package sendmail!

 

#
# ACTIONS
#

# Some options used for actions

# Destination email address used solely for the interpolations in
# jail.{conf,local,d/*} configuration files.
destemail = sysadmin@imtase.com

# Sender email address used solely for some actions
sender = sysadmin@imtase.com

# E-mail action. Since 0.8.1 Fail2Ban uses sendmail MTA for the
# mailing. Change mta configuration parameter to mail if you want to
# revert to conventional 'mail'.
mta = sendmail

we need to adjust the action parameter too.

 

# Choose default action.  To change, just override value of 'action' with the
# interpolation to the chosen action shortcut (e.g.  action_mw, action_mwl, etc) in jail.local
# globally (section [DEFAULT]) or per specific section
action = %(action_mwl)s

 

SSH

 

To activate a service juste need a line enabled = true in the appropriate section. Exemple with [ssh]

 

#
# SSH servers
#

[sshd]
enable  = true
port    = ssh
logpath = %(sshd_log)s

We can no restart fail2ban

 

xxxx@xxxx:~$ sudo service fail2ban start

If you go want deeper in fail2ban I suggest this excellent post from Linode

 

Fail2ban Client

 

use the command fail2ban-client with one of these command to action/check information:

 

  1. start: Starts the server and jails.
  2. reload: Reloads configuration files.
  3. reload JAIL: Replaces JAIL with the name of a Fail2ban jail; this will reload the jail.
  4. stop: Stop the server.
  5. status: Show the status of the server, and enable jails.
  6. status JAIL: Show the status of the jail, including any currently-banned IPs.

 

Replace JAIL by the service you want to check, exemple with ssh

 

xxxx@xxxx:~$ sudo fail2ban-client status
Status
|- Number of jail: 1
`- Jail list: sshd
xxxx@xxxx:~$ sudo fail2ban-client status sshd
Status for the jail: sshd
|- Filter
| |- Currently failed: 0
| |- Total failed: 0
| `- File list: /var/log/auth.log
`- Actions
 |- Currently banned: 0
 |- Total banned: 0
 `- Banned IP list:

 

NMAP

 

Install and use the port scanning NMAP

 

xxxx@xxxx:~$ sudo apt-get install nmap

To scan the port of the server you can use the command

 

xxxx@xxxx:~$ nmap -sV -p 1-65535 localhost

-sV   = service identification
-p     = list of port to scan (range separate by -)

 

Can pass hostnames, IP addresses, networks, etc. (localhost, www.my.com, range like 192.168.1.1/24 or 192.168.1.1-50, host like 192.168.1.1/32)

 

 

You have now made your Ubuntu Server more secure, in part 3 we will see the usage of DPI (Deep Packet Inspection)

 

How-To: Secure Ubuntu server (part 1)

Increase the security and usability of your Ubuntu server is very important and do at the same times you install it is the best way. There are few configuration/install that you should take early on as part of the basic setup.

 

Install

 

The install of Ubuntu Server is easy and not need a detailed how-to for this, the only point you need to take care is the manual partitioning of your hard drive (depend of your case). Suggest to follow ubuntuserverguide documentation or this one from ubuntu. The second thing to take care is to use a strong password scheme (Upper/Lower/Number/Special) who stay easy to remember (not have to write), to write (your fingers will say thanks)

 

Ubuntu Root Login

 

Never use directly the user root and prefer to create a new user (in our case we will use an account named admin with sudo power) and use a strong password scheme (Upper,  Lower, Number, Special) who stay easy to remember for not have to write it.

As root, run this command to add your new user to the sudo group

 

xxxx@xxxx:~$ usermod -aG sudo admin

 

 

Set up public key authentication for your new user. Setting this up will increase the security of your server by requiring a private SSH key to log in.

 

Generate The Key Pair for SSH

 

If you haven’t an SSH key pair already you can create it by following this process. To generate a new key pair, enter the following command (use the option -b 4096 for higher security) in your terminal.

 

xxxx@xxx:~$ ssh-keygen -b 4096

Assuming your local user is “admin”, you will see the following output:

 

admin@xxx:~$ ssh-keygen -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/admin/.ssh/id_rsa):

Hit return to accept

 

Created directory '/Users/admin/.ssh'
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

Securing your keys with passphrases is more secure, but in this case you need to use it each time you connect. The choice depend of the level of security you want.

 

At the end you will have an output like this

 

Your identification has been saved in /home/admin/.ssh/id_rsa.
Your public key has been saved in /home/admin/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:XXXXXXXXXXXXXXXXXXX5GcBMBXXXXXXXXXXM admin@xxx
The key's randomart image is:
+---[RSA 4096]----+
|XXXX             |
|XX               |
|X X XX XXX       |
|XXX X XXX        |
|X XXXX X  XX     |
| XX XX           |
|   X             |
| X               |
|                 |
+----[SHA256]-----+

You have now 2 files in the directory /home/admin/.ssh/ a private key id_rsa and a public key id_rsa.pub

 

Remember that the private key id_rsa should not be given to anyone who should not have the right to access to your server!

 

Rename the Public Key

 

if you generate the keys directly on the server rename the public key id_rsa.pub in authorized_keys like this

 

admin@xxx:~/.ssh$ sudo mv id_rsa.pub authorized_keys

And retrieve the private key id_rsa on your computer (not let it on the server!)

 

Putty case

 

Putty users, you need to load the private key id_rsa in PuTTYgen then save the private key for have it in .ppk format

 

Disabling Password Authentication

 

If you were able to login to your account using SSH with the private key then you have successfully configured SSH key-based authentication to your account. We can now remove the authentication with password only in the ssh config file (not hesitate to change also the port number 22 if you want).

 

admin@xxx:~/.ssh$ sudo vim /etc/ssh/sshd_config

Search for a directive called PasswordAuthentication. This may be commented out. Uncomment the line and set the value to “no“. This will disable your ability to log in through SSH using account passwords.

 

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
PasswordAuthentication no

Save and close the file when you are finished. To actually implement the changes we just made, you must restart the service.

 

admin@xxx:~/.ssh$ sudo service ssh restart

 

Basic Firewall

 

The default firewall configuration tool for Ubuntu is ufw. It’s an interface to iptables.

 

Allow an application or a TCP/UDP port

 

To add an application you can use the command below to list all application

 

admin@xxx:~/$ sudo ufw app list

You will have this in Output

 

Available applications:
 OpenSSH

To allow OpenSSH (ssh) use this command

 

admin@xxx:~/$ sudo ufw allow OpenSSH

You can also use directly the TCP or UDP port number

 

in standard case of port 22

 

admin@xxx:~/$ sudo ufw allow ssh

in case you change the port use this (where XX is the port number).  keep always the port number below 1024 as these are privileged ports that can only be opened by root or processes running as root. A good link to find an available tcp port under 1024 : wikipedia

 

admin@xxx:~/$ sudo ufw allow XX

when you want specify a specific protocole add the proto tcp (exemple for TCP only)

 

Activate ufw

 

To enable ufw, use this command:

 

 admin@xxx:~/$ sudo ufw enable
 Command may disrupt existing ssh connections. Proceed with operation (y|n)?

Answer “y” to the question for proceed

 

To list the active rules you can use the command

admin@xxx:~/$ sudo ufw status

The output will be something like this

 

Status: active

To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)

More commands on ufw in this excellent post of DigitalOcean : UFW Setup

 

You have now the base for a Secure Ubuntu Server, in part 2 we will see the usage of Fail2Ban to scan logs and ban suspicious hosts and scan open Ports with Nmap