Powered by Blogger.

Installation CSF Firewall on CentOS 5 and 6

The ConfigServer Security & Firewall is a popular open source Stateful Packet Inspection (SPI) firewall, Login/Intrusion Detection and Security application, compatible with most Linux servers.

CSF can be fully configured to block/restrict ports you don't want open. CSF includes the Login Failure Daemon (LFD), which will scan log files and monitor failed login attempts, such as login attempts for FTP and E-Mail accounts, and it will block the IP according to the rules you have setup. CSF also offers Connection Limiting, Real Time Block Lists and Port Scan tracking and much more.

CSF can be easily managed from within its GUI, which is fully compatible with DirectAdmin, CPanel, and WebMin/Virtualmin.

In order to avoid any conflicts in operation it is important to remove your current firewall. If you are using a different software firewall be sure to follow that programs uninstall directions before continuing. After completing the uninstallation routine continue with the CSF installation procedure outlined below.

Note: This guide assumes you are familiar with SSH and basic command line navigation. These instructions apply primarily to customers who haveVirtual Private Servers or Dedicated servers. If you do not have root-level access you will not be able to make these changes.

1. Installation

1.1 Install Dependencies

Begin by installing the required dependencies for the CSF Firewall:

CentOS, RHEL 5 and 6

yum install perl-libwww-perl
Alternatively, libwww can be installed using CPAN:
perl -MCPAN -e 'install Bundle::LWP'

CentOS, RHEL 7

yum -y install wget perl unzip net-tools perl-libwww-perl perl-LWP-Protocol-https perl-GDGraph -y

1.2 Install CSF Firewall

Download the CSF archive to the /tmp folder of your server by using wget, unpack the archive by issuing the TARcommand and finally install CSF by starting the ./install.sh setup script.
cd /tmp
wget https://download.configserver.com/csf.tgz
tar zxvf csf.tgz cd csf ./install.sh
The plugins for DirectAdmin or cPanel are installed automatically.

You can now remove the installation files:
rm -rf /tmp/csf
rm /tmp/csf.tgz

1.3 Install Webmin Module (optional)

  1. Install csf as above
  2. Login to Webmin
  3. Install the csf webmin module by navigating to:
    Webmin > Webmin Configuration > Webmin Modules
  4. Select "From local file" and enter: /usr/local/csf/csfwebmin.tgz
  5. Install the module

2. Test IPtables configuration

This test is recommended to double check that the correct iptables modules are installed. The test can be invoked by issuing the command below, or by going to the "test iptables" section, which can be found at the bottom of the CSF Graphic interface. If not all modules are installed, you need to work on getting them installed. This procedure is outside the scope of this article and may require a kernel change on your dedicated server. Those operating an OpenVZ based Virtual Private Server will need to contact their host to get this setup correctly.
$ /etc/csf/csftest.pl
Testing ip_tables/iptable_filter...OK
Testing ipt_LOG...OK
Testing ipt_multiport/xt_multiport...OK
Testing ipt_REJECT...OK
Testing ipt_state/xt_state...OK
Testing ipt_limit/xt_limit...OK
Testing ipt_recent...OK
Testing xt_connlimit...OK
Testing ipt_owner/xt_owner...OK
Testing iptable_nat/ipt_REDIRECT...OK
Testing iptable_nat/ipt_DNAT...OK
RESULT: csf should function on this server

3. Configuration

The configuration of your CSF Firewall installation can be maintained by editing the various config files CSF ships with. On Red Hat Enterprise Linux (RHEL) based distributions these can be found in the following location:/etc/csf/
The configuration files include:
  • csf.conf - the main configuration file, it has helpful comments explaining what each option does
  • csf.allow - a list of IP's and CIDR addresses that should always be allowed through the firewall
  • csf.deny - a list of IP's and CIDR addresses that should never be allowed through the firewall
  • csf.ignore - a list of IP's and CIDR addresses that lfd should ignore and not block if detected
  • csf.*ignore - various ignore files that list files, users, IP's that lfd should ignore. See each file for their specific purpose
If you modify any of the files listed above, you will need to restart csf to have them take effect. If you use the command line options to add or deny IP addresses, then csf automatically does this for you.
However, for the average user it is far quicker to make use of its Graphic Interface (GUI), which can be accessed from within your DirectAdmin, CPanel or Webmin/Virtualmin Control Panel.

3.1 Enabling CSF Firewall

The CSF firewall can be fully enabled by setting:
This can be done by accessing the GUI, or by editing the main configuration file, found at /etc/csf/csf.conf.

Please ensure your configuration is correct. The wrong settings may lock you out of your server permanently!


Below you will find a basic explanation for the recommended opened TCP_IN ports for INCOMING connections to your DirectAdmin based web server. These ports can be opened from the GUI or the csf.conf file.
FTP access *
SSH Access
25, 587
SMTP for EXIM to receive e-mail
DNS (Named), The port for your nameservers. Both TCP and UDP ports should be opened here.
80, 443
Apache traffic, http and https
110, 993
POP e-mail access
143, 995
IMAP email access
MySQL. You should not open this port if you don't want to allow remote MySQL access, as most MySQL scripts are accessed locally
DirectAdmin Access
cPanel Access over an encrypted SSL connection
cPanel Access over an unencrypted connection
cPanel WHM Access over an encrypted SSL connection
cPanel WHM Access over an unencrypted connection
Webmin Access
* FTP requires a random high port number if the client is in PORT mode. When using ProFTP you may need to add a port range into your /etc/proftpd.conf file to allow ftp connections, eg: PassivePorts 35000 35999 and then open that port range in your CSF firewall. Ranges can be defined in CSF by using a colon eg: 35000:35999
TCP_IN and TCP_OUT / UDP_IN and UDP_OUT is a comma separated list of:
# Allow incoming TCP ports
TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995,2222,35000:35999"
# Allow outgoing TCP ports
TCP_OUT = "20,21,22,25,53,80,110,113,443"
# Allow incoming UDP ports
UDP_IN = "20,21,53"
# Allow outgoing UDP ports
UDP_OUT = "20,21,53,113,123"


Allowing ping is usually a good option for diagnostic purposes.
Set ICMP_IN to 1 to allow incoming ping requests to your server. Set to 0 refuses such requests. If you are hosting any public services, it is recommended to allow ICMP requests, as these can be used to determine whether or not your service is available. ICMP_IN_LIMIT Sets the number of ICMP (ping) requests allowed from one IP address within a specified amount of time. There is usually no need to change the default value (1/s)
Set ICMP_OUT to 1 to allow outgoing ping from your server. Set to 0 refuses such requests. ICMP_OUT_LIMIT Sets the number of outgoing ICMP (ping) requests within a specified amount of time. There is usually no need to change the default value (0)

3.4 Port flood protection

This setting provides protection against port flood attacks, such as denial of service (DoS) attacks. You may specify the amount of allowed connections on each port within time period of your liking. Enabling this feature is recommended, as it may possibly prevent an attacker forcing your services down. You should pay attention to what limits you set, as too restrictive settings will drop connections from normal clients. Then again, too permissive settings may allow an attacker to succeed in a flood attack.
PORTFLOOD is a comma separated list of:
port;protocol;hit count*;interval seconds
So, a setting of PORTFLOOD = "22;tcp;5;300,80;tcp;20;5" means:
  1. 1. If more than 5 connections to tcp port 22 within 300 seconds, then block that IP address from port 22 for at least 300 seconds after the last packet is seen, i.e. there must be a "quiet" period of 300 seconds before the block is lifted
  2. 2. If more than 20 connections to tcp port 80 within 5 seconds, then block that IP address from port 80 for at least 5 seconds after the last packet is seen, i.e. there must be a "quiet" period of 5 seconds before the block is lifted
You may add more ports by separating them by commas like described as follows:port1;protocol1;connection_count1;time1,port2;protocol2;connection_count2;time2

3.5 Port knocking

Port knocking allows clients to establish connections a server with no ports open. The server allows clients connect to the main ports only after a successful port knock sequence. You may find this useful if you offer services which are available to only limited audience.
The feature requires that you list a random selection of unused ports (at least 3) with a timeout. The ports you choose must not be in use and not appear in TCP_IN (UDP_IN for udp packets). The port to be opened must also not appear in TCP_IN (UDP_IN for udp packets).
PORTKNOCKING is a comma separated list of:
So, a setting of PORTKNOCKING = "22;TCP;20;100;200;300;400" means:
Open Port 22 TCP for 20 seconds to the connecting IP address to new connections once ports 100, 200, 300 and 400 have been accessed (i.e. knocked with a SYN packet) each knock being less than 20 seconds apart.
Access to port 22 remains active after 20 seconds until the connection is dropped, however new connections will not be allowed.

3.6 Syslog and RESTRICT_SYSLOG

When enabled, this option logs lfd (Login Failure Daemon) messages to syslog as well as to /var/log/lfd.log.
Unfortunately, it is trivial for end-users and scripts run by end-users to spoof log lines that appear identical to any log line reported in logs maintained by syslog/rsyslog. You can identify these logs by looking in /etc/syslog.conf oretc/rsyslog.conf
This means that anyone on the server can maliciously trigger applications that monitor these logs, such as lfd does for the following options:
A malicious user could use this issue to trigger confusing emails regarding both successful and failed login attempts, kernel log lines (including iptables log lines) etc. Unfortunately, there is very little that can be done about this as syslog/rsyslog has no security framework. Some attempt was made in newer versions of rsyslog, but this version is not available in the current versions used by RedHat/CentOS v6. It also has to be enabled and can have adverse effects on utilities that expect a certain format for the log lines.
To mitigate spoofing attempts we recommend the following, if you are willing to accept the consequences of spoofed log lines:
  1. Go through the options above ensuring that only those that you need are enabled.
  2. Ensure that DENY_IP_LIMIT and DENY_TEMP_IP_LIMIT are set reasonably low (for example, 200). This will limit attempts to block large numbers of IP addresses.
  3. Ensure that administrator/support IP addresses are listed in /etc/csf/csf.allow and perhaps /etc/csf/csf.ignore. This will prevent malicious blocking from denying you access to the server.
  4. To confirm successful logins to SSH, use the "last" utility from the root shell, e.g.: last -da
  5. Regularly check the server and user data for exploits, old vulnerable applications and out of date OS applications.
  6. Consider carefully any application that you use that centralises actions and syslog/rsyslog logs and the implications of spoofed log lines.
  7. Consider the implications of this overall issue on applications and scripts other than csf/lfd that use the affected log files.
  8. Ultimately, you could consider restricting access to all configured syslog/rsyslog unix sockets. This can be used via file permissions and ownership of the sockets (e.g. /dev/log) but there are several caveats: file permissions and ownership have to be reapplied whenever syslog/rsyslog is restarted; restricting logging will break/limit some applications ability to log to syslog/rsyslog, for example crond.
  9. Do not enable syslog/rsyslog reception via UDP/TCP ports.

3.7 Connection limit protection CONNLIMIT

This feature can be used to limit the number concurrent of active connections from an IP address to each port. When properly configured, this may prevent abuses on the server, such as DoS attacks.
CONNLIMIT is a comma separated list of:
So, a setting of CONNLIMIT = "22;5,80;20" means:
  1. Only allow up to 5 concurrent new connections to port 22 per IP address
  2. Only allow up to 20 concurrent new connections to port 80 per IP address

3.8 Port/IP address redirection

CSF can be configured to redirect connections to an IP/port to another IP/port. Note: After redirection, the source address of the client will be the server's IP address.
nat tables
  ipt_DNAT iptables module
  ipt_SNAT iptables module
  ipt_REDIRECT iptables module
The following are the allowed redirection formats:
DNAT (redirect from one IP address to a different one):
IPx|*|IPy|*|tcp/udp          - To IPx redirects to IPy
IPx|portA|IPy|portB|tcp/udp  - To IPx to portA redirects to IPy portB

DNAT examples:|*||*|tcp|666||25|tcp

REDIRECT (redirect from port to a different one):
IPx|portA|*|portB|tcp/udp    - To IPx to portA redirects to portB
*|portA|*|portB|tcp/udp      - To portA redirects to portB

REDIRECT examples:
Where a port is specified it cannot be a range, only a single port.
All redirections to another IP address will always appear on the destination server with the source of this server, not the originating IP address.
This feature is not intended to be used for routing, NAT, VPN, etc tasks


Offers protection against SYN flood attacks. This slows down the initialization of every connection, so you should enable this only if you know that your server is under attack.

3.10 Messenger Service

Enabling this feature allows CSF to send a more informative message to the client when a block is applied. This feature has both pros and cons. On one hand, enabling it provides more information to the client, and thus may cause less frustration for instance in case of failed logins. On the other hand, this provides more information, which might make it easier for an attacker to attack your server.


DENY_IP_LIMIT sets the number of blocked IP addresses CSF keeps track of. It is recommended to limit the number of denied IP addresses as having too many blocks may slow down the server performance. DENY_TEMP_IP_LIMIT has the same function, but for temporary IP address blocks.

3.12 Advanced Allow/Deny Filters

In /etc/csf.allow and /etc/csf.deny you can add more complex port and ip filters using the following format (you must specify a port AND an IP address):
Broken down:
tcp/udp  : EITHER tcp OR udp OR icmp protocol
in/out   : EITHER incoming OR outgoing connections
s/d=port : EITHER source OR destination port number (or ICMP type)
           (use a _ for a port range, e.g. 2000_3000)
s/d=ip   : EITHER source OR destination IP address
u/g=UID  : EITHER UID or GID of source packet, implies outgoing connections,
           s/d=IP value is ignored
Note: ICMP filtering uses the "port" for s/d=port to set the ICMP type. Whether you use s or d is not relevant as either simply uses the iptables --icmp-type option. Use "iptables -p icmp -h" for a list of valid ICMP types. Only one type per filter is supported.
# TCP connections inbound to port 3306 from IP

# TCP connections outbound to port 22 on IP

Note| If omitted, the default protocol is set to "tcp", the default connection
direction is set to "in", so|

# TCP connections inbound to port 22 from IP

# TCP connections outbound to port 80 from UID 99

# ICMP connections inbound for type ping from

# TCP connections inbound to port 22 from Dynamic DNS address
# www.configserver.com (for use in csf.dyndns only)

4. Login Failure Daemon (LFD)

To complement the ConfigServer Firewall, a daemon process that runs all the time and periodically (every X seconds) scans the latest log file entries for login attempts against your server that continually fail within a short period of time. Such attempts are often called "Brute-force attacks" and the daemon process responds very quickly to such patterns and blocks offending IP's quickly.
There are an array of extensive checks that lfd can perform to help alert the server administrator of changes to the server, potential problems and possible compromises.
lfd can monitor the most commonly abused protocols, SSHD, POP3, IMAP, FTP and HTTP password protection. Unlike other applications, lfd is a daemon process that monitors logs continuously and so can react within seconds of detecting such attempts. It also monitors across protocols, so if attempts are made on different protocols in a short space of time, all those attempts will be counted against the threshold.

4.1 E-Mail Alerts

You can specify an email address to report errors from the Login Failure Daemon.

4.2 Login Tracking

Login tracking is an extension of lfd, it keeps track of POP3 and IMAP logins and limits them to X connections per hour per account per IP address. It uses iptables to block offenders to the appropriate protocol port only and flushes them every hour and starts counting logins afresh. All of these blocks are temporary and can be cleared manually by restarting csf.
There are two settings, one of POP3 and one for IMAP logins. It's generally not a good idea to track IMAP logins as many clients login each time to perform a protocol transaction (there's no need for them to repeatedly login, but you can't avoid bad client programming!). So, if you do have a need to have some limit to IMAP logins, it is probably best to set the login limit quite high.

4.3 Process Tracking

This option enables tracking of user and nobody processes and examines them for suspicious executables or open network ports. Its purpose is to identify potential exploit processes that are running on the server, even if they are obfuscated to appear as system services. If a suspicious process is found an alert email is sent with relevant information. Processes may be excluded from process tracking by editing the csf.pignore file.

For example, to disable Process tracking for Spamassassin and ClamAV enter the following in the csf.pignore file. This file can also be edited from the CSF gui:
cmd:spamd child

4.4 Directory Watching

Directory Watching enables lfd to check /tmp and /dev/shm and other pertinent directories for suspicious files, i.e. script exploits.

5. IP Block Lists

This feature allows csf/lfd to periodically download lists of IP addresses and CIDRs from pubished block or black lists. Blocklists are controlled by the file: /etc/csf/csf.blocklists
IP Block lists can also be configured by going to the lfd blocklists button, which can be found near the bottom of the included GUI.
Enable a blocklist by uncommenting the line starting with the rule name to use it, then restart csf and then lfd.
Each block list must be listed per line as: NAME|INTERVAL|MAX|URL
List name with all uppercase alphabetic characters with no spaces and a maximum of 9 characters - this will be used as the iptables chain name
Refresh interval to download the list, must be a minimum of 3600 seconds (an hour), but 86400 (a day) should be more than enough
This is the maximum number of IP addresses to use from the list a value of 0 means all IPs are used
The URL to download the list from
Pre-configured blocklists, which can be enabled simply by uncommenting them, include:
  • Spamhaus
  • DShield
  • TOR
  • BOGON - Blocking bogon addresses (addresses that should not be possible) is usually a good decision. To enable, set the number of seconds between refreshes. I recommend enabling this option and setting the refresh at 86400 (1 day). If you do so, be sure to add your private network adapters to the skip list.
  • Project Honeypot
  • BruteForceBlocker
  • Emerging Threats - Russian Business Networks List
  • OpenBL.org 30 day List
  • Autoshun Shun List
  • MaxMind GeoIP Anonymous Proxies
Some of these lists are very long (thousands of IP addresses) and could cause serious network and/or performance issues, so setting a value for the MAX field should be considered.
Each URL is scanned for an IPv4/CIDR address per line and if found is blocked.

6. Country Code Lists and Settings

With the options displayed below, you can block or allow entire countries from accessing your server. To do so, enter the country codes in a comma separated list. Even though this generates a lot of additional rules, it's valuable to some sysadmins.
These lists are never 100% accurate and some ISP's (e.g. AOL) use non-geographic IP address designations for their clients. Some of the CIDR lists are huge and each one requires a rule within the incoming iptables chain. This can result in significant performance overheads and could render the server inaccessible in some circumstances. Due to the resource constraints on VPS servers this feature should not be used on such systems unless you choose very small CC zones
cc_allow and cc_deny are comma separated lists of CC's, e.g. "US,GB,DE":
CC_DENY = ""
An alternative to CC_ALLOW is to only allow access from the following countries but still filter based on the port and packets rules. All other connections are dropped:
The option below allows access from the following countries to specific ports listed in CC_ALLOW_PORTS_TCP andCC_ALLOW_PORTS_UDP
Note: The rules for this feature are inserted after the allow and deny rules to still allow blocking of IP addresses. All listed ports should be removed from TCP_IN/UDP_IN to block access from elsewhere. This option uses the same format as TCP_IN/UDP_IN
This Country Code list will prevent lfd from blocking IP address hits for the listed CC's
This option denies access from the following countries to specific ports listed in CC_DENY_PORTS_TCP andCC_DENY_PORTS_UDP
Note: The rules for this feature are inserted after the allow and deny rules to still allow blocking of IP addresses. All listed ports should be removed from TCP_IN/UDP_IN to block access from elsewhere. This option uses the same format as TCP_IN/UDP_IN

7. Using the Command Line

Here are the some of the most common commands you will be using:
Manually Deny an IP address:
Manually Allow an IP address:
Reload all firewall rules:
csf -r
Update CSF:
csf -u
Start the CSF service:
csf -e
Restart the CSF service:
# CentOS 5 and 6
service csf restart

# CentOS 7
systemctl restart csf.service
For a complete overview of all command line options enter csf or csf -h on the command line and you will receive a list with all available options:
$ csf --help
csf: v5.17 (DirectAdmin)
ConfigServer Security & Firewall
(c)2006-2013, Way to the Web Limited (http://www.configserver.com)
Usage: /usr/sbin/csf [option] [value]
Option              Meaning
-h, --help          Show this message
-l, --status        List/Show iptables configuration
-l6, --status6      List/Show ip6tables configuration
-s, --start         Start firewall rules
-f, --stop          Flush/Stop firewall rules (Note: lfd may restart csf)
-r, --restart       Restart firewall rules
-q, --startq        Quick restart (csf restarted by lfd)
-sf, --startf       Force CLI restart regardless of LF_QUICKSTART setting
-a, --add ip        Allow an IP and add to /etc/csf.allow
-ar, --addrm ip     Remove an IP from /etc/csf.allow and delete rule
-d, --deny ip       Deny an IP and add to /etc/csf.deny
-dr, --denyrm ip    Unblock an IP and remove from /etc/csf.deny
-df, --denyf        Remove and unblock all entries in /etc/csf.deny
-g, --grep ip       Search the iptables rules for an IP match (incl. CIDR)
-t, --temp          Displays the current list of temp IP entries and their TTL
-tr, --temprm ip    Remove an IPs from the temp IP ban and allow list
-td, --tempdeny ip ttl [-p port] [-d direction]
                    Add an IP to the temp IP ban list. ttl is how long to
                    blocks for (default:seconds, can use one suffix of h/m/d).
                    Optional port. Optional direction of block can be one of:
                    in, out or inout (default:in)
-ta, --tempallow ip ttl [-p port] [-d direction]
                    Add an IP to the temp IP allow list (default:inout)
-tf, --tempf        Flush all IPs from the temp IP entries
-cp, --cping        PING all members in an lfd Cluster
-cd, --cdeny ip     Deny an IP in a Cluster and add to /etc/csf.deny
-ca, --callow ip    Allow an IP in a Cluster and add to /etc/csf.allow
-cr, --crm ip       Unblock an IP in a Cluster and remove from /etc/csf.deny
-cc, --cconfig [name] [value]
                    Change configuration option [name] to [value] in a Cluster
-cf, --cfile [file] Send [file] in a Cluster to /etc/csf/
-crs, --crestart    Cluster restart csf and lfd
-w, --watch ip      Log SYN packets for an IP across iptables chains
-m, --mail [addr]   Display Server Check in HTML or email to [addr] if present
-lr, --logrun       Initiate Log Scanner report via lfd
-c, --check         Check for updates to csf but do not upgrade
-u, --update        Check for updates to csf and upgrade if available
-uf                 Force an update of csf
-x, --disable       Disable csf and lfd
-e, --enable        Enable csf and lfd if previously disabled
-v, --version       Show csf version

8. Further Considerations

Please ensure to follow the recommendations outlined on the "Check Server Security" page from within the CSF GUI. It is also wise to double check that all required IPtables modules are properly loaded by going to the "Test Iptables Page" at the bottom of the CSF GUI. If they are not properly loaded, and you are on a Virtual Private Server (VPS), contact your host to fix this.
CSF assumes your php.ini file is located in /usr/local/lib/php.ini
If your php.ini file was installed in a different location, you can create a symlink to the correct location. This may be helpful if you want to make use of CSFs security suggestions on the "Check Server Security" page.
ln -s  /path/to/your/actual/php.ini /usr/local/lib/php.ini
Don't ever run iptables -F while using CSF, unless you want to lock yourself out.

9. Uninstallation

On cPanel servers:
cd /etc/csf
sh uninstall.sh
On DirectAdmin servers:
cd /etc/csf
sh uninstall.directadmin.sh
On generic linux servers:
cd /etc/csf
sh uninstall.generic.sh

    Blogger Comment
    Facebook Comment