Skip to main content

Securing Webservers - FirewallD Deployment on CentOS7

TST, Hong Kong

Installation

yum install firewalld
systemctl start firewalld
firewall-cmd --state

After you install firewalld, you can enable the service and reboot your server. Keep in mind that enabling firewalld will cause the service to start up at boot. It is best practice to create your firewall rules and take the opportunity to test them before configuring this behavior in order to avoid potential issues.

Setup

Before enabling your firewall you need to check what ports are in use on your server - s. SS Command:

ss -4 state listening

Netid Recv-Q Send-Q Local Address:Port
tcp 0 128 *:http
tcp 0 128 *:https

This will list all processes that are actively listening on ports on your system - make a note and let's open them up in FirewallD (where needed).

Services

FirewallD offers service presets that you can use to allow all necessary traffic for those services to work correctly:

firewall-cmd --get-services


RH-Satellite-6 amanda-client amanda-k5-client amqp amqps apcupsd audit bacula bacula-client bb bgp bitcoin bitcoin-rpc bitcoin-testnet bitcoin-testnet-rpc bittorrent-lsd ceph ceph-mon cfengine cockpit condor-collector ctdb dhcp dhcpv6 dhcpv6-client distcc dns dns-over-tls docker-registry docker-swarm dropbox-lansync elasticsearch etcd-client etcd-server finger freeipa-4 freeipa-ldap freeipa-ldaps freeipa-replication freeipa-trust ftp ganglia-client ganglia-master git grafana gre high-availability http https imap imaps ipp ipp-client ipsec irc ircs iscsi-target isns jenkins kadmin kdeconnect kerberos kibana klogin kpasswd kprop kshell kube-apiserver ldap ldaps libvirt libvirt-tls lightning-network llmnr managesieve matrix mdns memcache minidlna mongodb mosh mountd mqtt mqtt-tls ms-wbt mssql murmur mysql nfs nfs3 nmea-0183 nrpe ntp nut openvpn ovirt-imageio ovirt-storageconsole ovirt-vmconsole plex pmcd pmproxy pmwebapi pmwebapis pop3 pop3s postgresql privoxy prometheus proxy-dhcp ptp pulseaudio puppetmaster quassel radius rdp redis redis-sentinel rpc-bind rsh rsyncd rtsp salt-master samba samba-client samba-dc sane sip sips slp smtp smtp-submission smtps snmp snmptrap spideroak-lansync spotify-sync squid ssdp ssh steam-streaming svdrp svn syncthing syncthing-gui synergy syslog syslog-tls telnet tentacle tftp tftp-client tile38 tinc tor-socks transmission-client upnp-client vdsm vnc-server wbem-http wbem-https wsman wsmans xdmcp xmpp-bosh xmpp-client xmpp-local xmpp-server zabbix-agent zabbix-server

You can find out what ports are opened by a service inside the definition files in /usr/lib/firewalld/services/ - e.g.:

cat /usr/lib/firewalld/services/zabbix-server.xml

<?xml version="1.0" encoding="utf-8"?>
<service>
<short>Zabbix Server</short>
<description>Zabbix is a mature and effortless enterprise-class open source monitoring solution for network monitoring and application monitoring of millions of metrics.</description>
<port protocol="tcp" port="10051"/>
</service>

We can add all releavant service presets with:

firewall-cmd --permanent --zone=public --add-service=https --add-service=http
firewall-cmd --zone=public --add-service=ssh --add-service=git --add-service=smtp --add-service=smtps --add-service=imap --add-service=imaps --add-service=pop3 --add-service=pop3s --add-service=dhcp --permanent

Note: To add services while your firewall is not yet started use the offline commands: firewall-offline-cmd --zone=public --add-service=https

Ports

To add specialized ports run:

firewall-cmd --permanent --zone=public --add-port=587/tcp
firewall-cmd --permanent --zone=public --add-port=8080/tcp
firewall-cmd --permanent --zone=public --add-port=4505-4506/tcp
firewall-cmd --reload

Note: To add ports while your firewall is not yet started use the offline commands: firewall-offline-cmd --zone=public --add-port=587/tcp

Docker

To actively reject traffic to a specific port:

firewall-cmd --permanent --add-rich-rule='rule family=ipv4 port port="9200" protocol="tcp" reject'
firewall-cmd --reload

BUT Docker will override this! Make sure to bind all ports that you don't want to be open to the internet to localhost!

Example docker-compose.yml:

ports:
- '127.0.0.1:9200:9200'
- '127.0.0.1:9300:9300'

Enable FirewallD

CAREFUL

Verify that everything is set up correctly:

firewall-cmd --zone=public --list-all

public
target: default
icmp-block-inversion: no
interfaces:
sources:
services: dhcpv6-client git http https salt-master ssh zabbix-agent zabbix-server
ports: 2222/tcp 8080/tcp
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
systemctl enable --now firewalld
systemctl status firewalld
sudo reboot

Prevent Bruteforce SSH attacks

Reject new incoming ipv4 connections when more than 2 attempts per minute are made. It will also log a message about this:

firewall-cmd --add-rich-rule='rule family="ipv4" service name="ssh" log prefix="SSH Bruteforce:" level="warning" limit value="2/m" accept limit value="2/m"' --permanent

If you have both ipv4 and ipv6 configured you’ll probably want the more generic version:

firewall-cmd --add-rich-rule='rule service name="ssh" log prefix="SSH Bruteforce:" level="warning" limit value="2/m" accept limit value="2/m"' --permanent

Create a Blacklist

firewall-cmd --permanent --new-ipset=blacklist --type=hash:net --option=family=inet --option=hashsize=4096 --option=maxelem=200000
  • –permanent = use to make changes to the permanent configuration
  • –new-ipset = name of the new IP/net blacklist
  • –type = storage hash type, "net" is for subnets, while "ip" for individual ip addresses
  • –option=family = IPv4 or IPv6 network, inet is for IPv4
  • –option=hashsize = the initial hash size of the list
  • –option=maxelem = max number of elements

Download net blocks:

wget https://www.ipdeny.com/ipblocks/data/aggregated/ru-aggregated.zone

Populate the blacklist:

firewall-cmd --permanent --ipset=blacklist --add-entries-from-file=./ru-aggregated.zone

To add individual IP addresses or net blocks by yourself:

firewall-cmd --permanent --ipset=blacklist --add-entry=4.46.116.112
firewall-cmd --ipset=blacklist --add-entry=4.46.116.112

Redirect the blacklist to the drop zone

firewall-cmd --permanent --zone=drop --add-source=ipset:blacklist
firewall-cmd --reload

Block and Enable ICMP

firewall-cmd --zone=public --query-icmp-block=echo-reply

If you get "no", that means there isn’t any icmp block applied, let’s enable (block) icmp.

firewall-cmd --zone=public --add-icmp-block=echo-reply

Lockdown Rules

It’s possible to change the firewalld rules by any local applications, which have the root privileges. To avoid making changes to firewalld rules, we have to put a lock-down in ‘firewalld.conf‘ file. This mostly used to protect the firewalld from any unwanted rules changes by any applications.

nano /etc/firewalld/firewalld.conf
Lockdown=yes
firewall-cmd --reload
firewall-cmd --query-lockdown

To On/Off lockdown mode, use the following combination.

firewall-cmd --lockdown-on
firewall-cmd --lockdown-off

How to Reset when things go Wrong

Delete your Zone Settings:

rm -rf /etc/firewalld/zones

Using the below set of commands you will set accept rule for all types of connections.

iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT

This will confirm, iptables gonna accept all requests for all types of connections.

Using below set of commands, delete your currently configured rules from iptables.

iptables -F INPUT
iptables -F OUTPUT
iptables -F FORWARD

Or you can do it in single command:

iptables -F

That’s it! Your iptables are reset to default settings i.e. accept all!

fail2ban-firewalld

Configure fail2ban (see below) to block hosts via firewalld.

yum install epel-release
yum install fail2ban fail2ban-systemd

If you have SELinux installed, then update the SELinux policies:

yum update -y selinux-policy*

fail2ban

fail2ban is a daemon to ban hosts that cause multiple authentication errors.

fail2ban will monitor the SystemD journal to look for failed authentication attempts for whichever jails have been enabled. After the number of failed attempts specified it will add a firewall rule to block that specific IP address for an amount of time configured.

Start by installing the package on your system - Debian, Ubuntu or on Centos through EPEL.

The jail.conf file will enable Fail2ban for SSH by default for Debian and Ubuntu, but not CentOS. All other protocols and configurations (HTTP, FTP, etc.) are commented out. If you want to change this, create a jail.local for editing:

cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Once installed the next step is to configure a jail (a service you want to monitor and ban at whatever thresholds you’ve set). By default IPs are banned for 1 hour. The best practice is to override the system defaults using _.local files instead of directly modifying the _.config files:

  • Ignoreip is used to set the list of IPs which will not be banned. The list of IP addresses should be given with a space separator. This parameter is used to set your personal IP address (if you access the server from a fixed IP).
  • Bantime parameter is used to set the duration of seconds for which a host needs to be banned.
  • Findtime is the parameter which is used to check if a host must be banned or not. When the host generates maxrety in its last findtime, it is banned.
  • Maxretry is the parameter used to set the limit for the number of retry's by a host, upon exceeding this limit, the host is banned.
# cat /etc/fail2ban/jail.local

[DEFAULT]
# "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

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

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

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

If you scroll further down to the jail section add your SSH port to the [sshd] settings port = ssh,ftps,12345. I will add the same setting in an separate file (s. below) - I have to check if this is necessary. Might be enough to add it here.

After 5 attempts within the last hour the IP will be blocked for 1 day.

The next step is to configure a jail. In this tutorial sshd is shown but the steps are more or less the same for other services. Create a configuration file inside /etc/fail2ban/jail.d:

# cat /etc/fail2ban/jail.d/sshd.local
[sshd]
enabled = true
# To use more aggressive sshd modes set filter parameter "mode" in jail.local:
# normal (default), ddos, extra or aggressive (combines all).
# See "tests/files/logs/sshd" or "filter.d/sshd.conf" for usage example and details.
#mode = normal
port = ssh,ftps,12345
maxretry = 3
bantime = 86400
logpath = %(sshd_log)s
backend = %(sshd_backend)s

Next enable and start the fail2ban service.

systemctl enable --now fail2ban
systemctl status fail2ban

to check the status of fail2ban and make sure the jail is enabled enter:

fail2ban-client status

Status
|- Number of jail: 1
`- Jail list: sshd
fail2ban-client status sshd
Status for the jail: sshd
|- Filter
| |- Currently failed: 0
| |- Total failed: 6
| `- File list: /var/log/auth.log
`- Actions
|- Currently banned: 3
|- Total banned: 3
`- Banned IP list: 78.46.122.33 195.211.138.111 56.89.126.122
tail -f /var/log/fail2ban.log

Check IP address geo location and add country ban lists where necessary whois ip-addrss | grep -i country.

Unbanning an IP Address

In order to remove an IP address from the banned list, parameter IPADDRESS is set to appropriate IP which needs unbanning. The name "sshd" is the name of the jail, in this case the "sshd" jail that we configured above. The following command does the job.

fail2ban-client set sshd unbanip IPADDRESS