Mail-csf
Postfix
CSF setting to catch SASL LOGIN authentication failed on CentOS
# vi /etc/csf/csf.conf
Find CUSTOM1_LOG and edit the content to:
CUSTOM1_LOG = "/var/log/maillog"
Add the regex to catch the failed attempts against SASL
# vi /usr/local/csf/bin/regex.custom.pm
Add the below regex between "Do not edit before this point" and "Do not edit beyond this point":
if (($lgfile eq $config{CUSTOM1_LOG}) and ($line =~ /^\S+\s+\d+\s+\S+ \S+ postfix\/smtpd\[\d+\]: warning:.*\[(\d+\.\d+\.\d+\.\d+)\]: SASL [A-Z]*? authentication failed/)) {
return ("Failed SASL login from",$1,"mysaslmatch","3","25","3600");
}
--------------------------------OR--------------------------------------------
if (($lgfile eq $config{CUSTOM1_LOG}) and ($line =~ /^\S+\s+\d+\s+\S+ \S+ postfix\/smtpd\[\d+\]: warning:.*\[(\d+\.\d+\.\d+\.\d+)\]: SASL [A-Z]*? authentication failed/)) {
return ("Failed SASL login from",$1,"mysaslmatch","3","25,465,587","3600");
}
--------------------------------------------X--------------------------------------------------
Restart CSF:
csf -r
service lfd restart
systemctl restart lfd
This is not working on CentOS 6.8
I'v added the code in regex.custom and changed to CUSTOM2_LOG because in CUSTOM1_LOG was some panel log in csf.conf.
Here's a asample from maillog:
Sep 29 14:56:46 vpsxxx postfix/smtpd[20536]: warning: static-***.net[100.*.*.*]: SASL LOGIN authentication failed: UGFzc3dvcmQ6
---------------------------------------OR----------------------------------------
BEST
LFD mail example
As said, not all attackes are being picked up by the LFD mechanism. We can work around it with regular expressions. This is not very easy to do, but with these examples you can come a long way. As a first example we want to block these attempts:
Feb 16 08:13:32 mail02 postfix/submission/smtpd[4312]: warning: unknown[83.219.76.26]: SASL PLAIN authentication failed:
First step is to look in which log the brute force attempts occurs. This log should be added to the bottom of the /etc/csf/csf.conf. In our case the mail.log.
CUSTOM1_LOG = "/var/log/mail.log"
You might notice that above this setting, other services are already looking at the exact same log. This does not matter. Just add this one as a custom log as well.
Next add your regular expression to the /usr/local/csf/bin/regex.custom.pm file.
# Permanently block an IP address that has 10 failed SASL login attempts
if (($globlogs{CUSTOM1_LOG} {$lgfile}) and ($line =~ /^\S+\s+\d+\s+\S+ \S+ postfix\/submission\/smtpd\[\d+\]: warning:.*\[(\d+\.\d+\.\d+\.\d+)\]: SASL [A-Z]*? authentication failed/)) {
return ("Failed SASL login from",$1,"mysaslmatch","5","25,465,587","1");
}
This will permanently block an IP that has 10 failed SASL login attempts.
Restart CSF and LFD.
# csf -r
# systemctl restart csf lfd
---------------------------------------OR----------------------------------------
Re: CSF custom regex / Fail2ban regex
Finally I managed to get both the CSF regex & fail2ban regex to work and the spam being minimized a lot. Hope this will help someone.
For CSF
========
1. Set the value of CUSTOM2_LOG in CSF to /var/log/maillog.
2. Set the following in /etc/csf/regex.custom.pm. You may also test your regex pattern at https://regex101.com.
Quote
if (($lgfile eq $config{CUSTOM2_LOG}) and ($line =~ /^.*postfix\/smtpd\[.*\]: NOQUEUE: reject: RCPT from (\S+)\[(\S+)\]: 450 4.1.1 <(\S+)>.*$/)) {
#It will block permanently anyone with more than 1 matches.
return ("450 4.1.1 spammer do not delete - $3",$2,"SMTP","1","25,587,465","1");
}
3. Restart CSF & LFD.
Quote
service lfd restart
csf -r
4. Check the CSF log file /etc/csf/csf.deny.
For fail2ban
========
1. In /etc/fail2ban/jail.conf, [postfix-tcpwrapper] section, set the following.
Quote
enabled = true
filter = postfix
action = hostsdeny[file=/etc/hosts.deny]
logpath = /var/log/maillog
bantime = 604800
ignoreip = 127.0.0.1/8
findtime = 300
maxretry = 3
You may adjust the value of bantime & maxretry with your own desire value.
2. Set the regex in /etc/fail2ban/filter.d/postfix.conf.
Quote
failregex = reject: RCPT from .*\[<HOST>\]: 450 4.1.1
reject: RCPT from .*\[<HOST>\]: 454 4.7.1
reject: RCPT from (.*)\[<HOST>\]: 554
3. You may test run the regex checking with the command as below.
Quote
fail2ban-regex /var/log/maillog /etc/fail2ban/filter.d/postfix.conf
4. Restart fail2ban service. (service fail2ban restart)
5. Check the file /etc/hosts.deny see if any IP being banned.
#Postfix SMTP AUTH (Plesk) if (($config{LF_SMTPAUTH}) and ($globlogs{SMTPAUTH_LOG}{$lgfile}) and ($line =~ /^(\S+|\S+\s+\d+\s+\S+) \S+ postfix\/smtpd(?:\[\d+\])?: warning: \S+\[(\S+)\]: SASL (?:(?i)LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed/)) { $ip = $2; $ip =~ s/^::ffff://; if (checkip(\$ip)) {return ("Failed SMTP AUTH login from","$ip","smtpauth")} else {return} }
--------------------------------------------------------------------------------------------------------------
----
Configure Firewall Exceptions for Postfix
In this section I show how to prevent the timeout errors if you are using CSF ConfigServer Firewall or ufw firewall.
CSF ConfigServer Firewall Exception
Open your CSF ConfigServer Firewall configuration
sudo nano /etc/csf/csf.conf
TESTING = "1"
Make sure port 587 is in TCP_IN and TCP_OUT
# Allow incoming TCP ports TCP_IN = "20,21,25,53,80,110,143,443,465,587,993,995,3000,3389,5800,5900,7575,8000,9090,10000,20000" # Allow outgoing TCP ports TCP_OUT = "20,21,25,53,80,110,113,443,587,993,995,3005"
Use Ctrl+W and enter SMTP_BLOCK to find this section.
Make your configuration match the one below to fix timeout errors.
If you have SMTP_PORTS include 587 it will be blocking the attempt causing the timeout
############################################################################### # SECTION:SMTP Settings ############################################################################### # Block outgoing SMTP except for root, exim and mailman (forces scripts/users # to use the exim/sendmail binary instead of sockets access). This replaces the # protection as WHM > Tweak Settings > SMTP Tweaks # # This option uses the iptables ipt_owner/xt_owner module and must be loaded # for it to work. It may not be available on some VPS platforms # # Note: Run /etc/csf/csftest.pl to check whether this option will function on # this server SMTP_BLOCK = "1" # If SMTP_BLOCK is enabled but you want to allow local connections to port 25 # on the server (e.g. for webmail or web scripts) then enable this option to # allow outgoing SMTP connections to the loopback device SMTP_ALLOWLOCAL = "1" # This option redirects outgoing SMTP connections destined for remote servers # for non-bypass users to the local SMTP server to force local relaying of # email. Such email may require authentication (SMTP AUTH) SMTP_REDIRECT = "0" # This is a comma separated list of the ports to block. You should list all # ports that exim is configured to listen on SMTP_PORTS = "25,587,465" # Always allow the following comma separated users and groups to bypass # SMTP_BLOCK # # Note: root (UID:0) is always allowed SMTP_ALLOWUSER = "" SMTP_ALLOWGROUP = "mail,mailman"
Ctrl+X, Y and Enter to Save and Exit.
Restart CSF
sudo csf -r sudo service csf restart
UFW Firewall Exception
If you are using ufw (Universal Firewall) you can create an exception for the postfix SMTP relay like this
sudo ufw allow 587/tcp
-------------------------------XXX-----------------------------\\
Additional Step if SMTP_BLOCK is enabled
Then ONLY if you enabled SMTP_BLOCK = "1" in /etc/csf/csf.conf, would you need either remove ports 465 and 587 from the SMTP_PORTS list or leave them in place and instead add nginx user to SMTP_ALLOWGROUP comma separated list. You should not need to do this as SMTP Blocking is disabled by default SMTP_BLOCK = "0"
Code:
SMTP_PORTS = "25,465,587" SMTP_ALLOWGROUP = "mail,mailman,nginx"
Then restart CSF firewall
Code:
csf -r
-------------------------------------XXX--------------------------------------
Initial Settings-Mail
To get started with securing your VPS or dedicated server with ConfigServer Firewall, go to the csf – ConfigServer Firewall section in the Webmin Module
Click Firewall Configuration to set all of these options
The firewall is only enabled when TESTING is set to 0, it is safe to do so since you whitelisted your IP address above using WhatIsMyIPAddress and/or Dynamic DNS
RESTRICT_SYSLOG = 0
Under Initial Settings make these changes
RESTRICT_SYSLOG = 3
Under IPv4 Port Settings
Choose TCP ports, the defaults will handle most systems but do include any additional ports from the netstat output. Remember to add port 10000 for Webmin and a custom SSH port (I’ve used 69) which you will configure later.
TCP_IN 20,21,22,25,53,80,110,143,443,465,587,993,995,69,8080,10000 TCP_OUT 20,21,22,25,53,80,110,113,443,587,993,995
Make UDP blank, generally you do not need UDP for anything on a web server unless it is streaming video or music.
UDP_IN UDP_OUT
Under IPv6 Port Settings make them match the IPv4 Port settings
TCP_IN 20,21,22,25,53,80,110,143,443,465,587,993,995,69,8080,10000 TCP_OUT 20,21,22,25,53,80,110,113,443,587,993,995
Same for UDP
UDP_IN UDP_OUT
Under General Settings
Necessary to log failed attempts, makes sure syslog service is running
SYSLOG_CHECK = 3600
SMTP Settings
Under SMTP Settings you need to know if you allow external users from remote IPs to send emails, if you only send emails using your local user set these options to block all other users except root and mailman. If you want to allow other non-local users leave SMTP_BLOCK=0 like if you are using Google’s servers as an SMTP relay to send your emails.
SMTP_BLOCK = 1 SMTP_ALLOWLOCAL = 1
To allow extra SMTP users set them in SMTP_ALLOWUSER and GROUP
SMTP_ALLOWUSER = webmaster,postmaster SMTP_ALLOWGROUP = mail
Reporting Settings
Under Reporting Settings leave the LF_ALERT_TO and LF_ALERT_FROM if you have postfix configured to autoforward to you regular email address.
Do set X_ARF to get detailed reports of intrusion alerts.
X_ARF = 1
Global Lists/DYNDNS/Blocklists
Under Global Lists/DYNDNS/Blocklists you can set custom IP lists to ignore including dynamic DNS addresses. If you set your dynamic DNS address to be ignored set these options to check the IP of the dynamic DNS address every 10 minutes and ignore the IP in the firewall rules.
DYDNS = 600 DYNDNS_IGNORE = 1
Under Country Codes Lists and Settings you can set custom countries to block. If you want to block Russia and China these country codes can be added to CC_DENY.
CC_DENY = RU,CN
Login Failure Blocking and Alerts
Under Login Failure Blocking and Alerts you can block users attempting to brute force your services like SSH, FTP, SMTP and others. The PERM setting set to 1 makes the ban permanent.
For the Login Failure daemon to permanently block failed IPs set LF_TRIGGER_PERM to 1 so it blocks that IP for all login failures which you enable in the LF_ settings that follow.
LF_TRIGGER_PERM = 1
If you are concerned about locking yourself or other friendly users out then set the LF TRIGGER to a value like 60 so that the IP is unlocked after 1 minute
LF_TRIGGER_PERM = 60
Set this option to only block users on the port they are attacking. This prevents innocent users whose machines are compromised from getting access to your services.
LF_SELECT = 1
The rest of the options are set to block the users on the specific port after a number of failed connections. You can decrease the limit for SSH from 5 to 3 like this
LF_SSHD = 3
Same goes for FTP and SMTP
LF_FTPD = 3 LF_SMTPAUTH = 3
Block Webmin failed attempts
LF_WEBMIN = 3
You can also block users requesting 404 or 403 pages from Apache – beware this can cause false positives from bots you want to crawl your site.
LF_APACHE_404 = 200 LF_APACHE_403 = 200
Under Distributed Attacks you can prevent botnets from making multiple failed attempts from different IP addresses, here the minimum amount of unique IP addresses allowed to login with the same credentials is 2
LF_DISTATTACK = 1 LF_DISTATTACK_UNIQ = 2
You should do the same with FTP, be careful with the unique IP setting if multiple users share the same account – here it is set to 3 IPs to share the same account. Make them permanent too.
LF_DISFTP = 1 LF_DISTFTP_UNIQ = 3 LF_DISTFTP_PERM = 1
Repeate the same for SMTP, again if multiple users share the same account take care with the UNIQ setting – again 3 IPs share this account.
LF_DISTSMTP = 1 LF_DISTSMTP_UNIQ = 3 LF_DISTSMTP_PERM = 1
Process Tracking
Under Process Tracking you can check rogue processes. It is usually easier to disable it by setting PT_LIMIT to disable process tracking as the amount of emails can be quite annoying. However, if you do want to use it then leave PT_LIMIT’s default value and add processes to ignore as shown for /opt/csf/pignore.
PT_LIMIT = 0
To disable any SSH attacks disconnect users who leave sessions open
PT_SSHDHUNG = 1
Note: from this point onwards no configuration is done in Webmin and is done in your SSH session.
Alternatively you can add the services to exclude from process tracking in /opt/csf/csf.pignore to stop the excessive and annoying Process Tracking Emails, this is done in SSH
nano /opt/csf/pignore
Add the services you wish to ignore there
exe:/usr/bin/dbus-daemon exe:/usr/sbin/mysqld exe:/usr/bin/nginx exe:/usr/lib/postfix/smtp exe:/usr/lib/dovecot/auth
Additional ConfigServer Firewall Setup
Use CSF Blocklists from dshield and spamhaus
sudo nano /etc/csf/csf.blocklists
Uncomment these lines by removing the hashtag # symbol, Spamhaus and Dshield block lists in CSF should not result in any false positives.
DSHIELD|86400|0|http://www.dshield.org/block.txt SPAMDROP|86400|0|http://www.spamhaus.org/drop/drop.lasso
Restart CSF
csf -r
Allowing the CloudFlare IPs should not be necessary! I use Flexible and strict SSL with CloudFlare and have not needed to do this but they do recommend it. If for some reason you need to allow the CloudFlare IPs on CSF go back in Webmin and click Firewall Allow IPs and paste this list and click Change
You can also consider adding this list to /etc/csf/csf.ignore
199.27.128.0/21; 199.27.128.0/21 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/12 172.64.0.0/13
If you set the CloudFlare allow IPs, click Return
Secure SSH for CSF
Open the SSH configuration
sudo nano /etc/ssh/sshd_config
Change the port and add UseDNS no so log files for SSH failed logins show the IP and not the domain name.
You must remember to add the port you choose here in TCP_IN for IPv4
# What ports, IPs and protocols we listen for Port 69UseDNS no
Restart SSH daemon
sudo service ssh restart
Secure MySQL
There is security risk
sudo nano /etc/mysql/my.cnf
Under [mysqld] add this
[mysqld] # # * Basic Settings # local-infile = 0 user = mysql
Restart MySQL
sudo service mysql restart
Monitor Critical System Files for Changes
ConfigServer lfd lets you monitor critical system files for changes by checking md5 sums periodically and will alert you of changes. This provides a basic Intrustion Detection System alternative to Snort, Tripwire and others.
Add the files you want to monitor here
sudo nano /etc/csf/csf.dirwatch
I have used root authorized keys and some other important files which would indicate a security breach.
CSF lfd ignores files owned by root by default but if you specify them here they will be monitored by ldf
/root/.ssh/authorized_keys /etc/ssh/sshd_config /etc/shadow
In the ConfigServer Webmin module find this setting under Directory Watching & Integrity and set it to 600 (every 10 minutes)
LF_DIRWATCH_FILE=600
Restart the CSF service in Webmin or SSH
lfd will check files ever 10 minutes for changes and send you an email alert
Time: Sat Dec 5 23:20:13 2015 +0000 File: /root/.ssh/authorized_keys has changed Output: -rw------- 1 root root 404 2015-12-05 23:19:32.727340313 +0000 /root/.ssh/authorized_keys
These CSF settings should keep you pretty safe from attacks and intrusions, my VPS is actually using less resources since activating this ConfigServer Firewall configuration
-----------------------------XXX--------------------------
Some useful tweak settings on CSF Configuration File
IP Limit in Permanent “Deny” File
DENY_IP_LIMIT = “200”
A higher number here will obviously screen out more IP addresses in csf.deny.
IP Limit in Temporary “Deny” File
DENY_TEMP_IP_LIMIT = “100”
Similar to DENY_IP_LIMIT, the DENY_TEMP_IP_LIMIT represents the maximum number of IPs that can be stored in the temporary ban list.
SMTP Blocking
SMTP_BLOCK = “0”
When set to “1″, SMTP_BLOCK does not completely block outbound SMTP, but it does block it for most users. This will prevent malicious scripts and compromised users from making outbound connections from unauthorized mail clients on the server. SMTP_BLOCK doesn’t stop those scripts from running, but it does stop them from functioning. Mail sent through the proper channels will still be delivered normally.
Allowing SMTP on localhost
SMTP_ALLOWLOCAL = “1”
Custom Mail Port Designation
SMTP_PORTS = “25,465,587”
Allowing SMTP Access to Users/Groups
SMTP_ALLOWUSER = “”
SMTP_ALLOWGROUP = “mail,mailman”
SYN Flood Protection
SYNFLOOD = “0”
SYNFLOOD_RATE = “100/s”
SYNFLOOD_BURST = “150”
Per the documentation, you should only enable SYN flood protection (SYNFLOOD= “1″) if you are currently under a SYN flood attack.
Concurrent Connections Limit
CONNLIMIT = “22;5,80;20”
PORTFLOOD = “22;tcp;5;300,80;tcp;20;5
These options allow you to add customized DoS protection. CONNLIMIT handles the number of concurrent connections, and in this example, we’re limiting port 22 to 5 connections and port 80 to 20 connections.
Dropping v. Rejecting Packets
DROP = “DROP”
This configuration allows you to either DROP or REJECT packets. REJECT tells the sender that the packet has been blocked by the firewall. DROP just drops the packet and does not send a response. I like DROP better for regular use, but REJECT might be more helpful if you need to diagnose a connectivity issue.
Logging Dropped Connections
DROP_LOGGING = “1”
This option logs dropped connections to syslog. I don’t see any reason to turn this off unless your hard drive is getting full.
SPAMHAUSE Blocklist
LF_SPAMHAUS = “0”
This option enables the SPAMHAUS blocklist. Specify the number of seconds between refreshes. Recommended setting is 86400 (1 day).
Blocking TOR Exit IP Addresses
LF_TOR = “0”
Enabling this option will block TOR exit IP addresses. If you are not familiar with TOR, it is a completely anonymous proxy network. This could block some legitimate users who are trying to protect their anonymity, so I would recommend only turning this on if you are already under attack from a TOR exit address.
Blocking Bogon Addresses
LF_BOGON = “0”
LF_BOGON_URL = “http://www.cymru.com/Documents/bogon-bn-agg.txt”
LF_BOGON_SKIP = “”
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.
Country-Specific Access to Your Server
CC_DENY = “”
CC_ALLOW = “”
With these options, you can block or allow entire countries from accessing your server. To do so, enter the country codes in a comma separated list.
CC_ALLOW_FILTER = “”
Alternatively, you can set your server to exclusively accept traffic from a list of country codes. All other countries not listed will have their traffic dropped.
Blocking Login Failures
LF_TRIGGER = “0”
This enables blocking of login failures (per service). There are a lot of great customization options in this section.
Scanning Directories for Malicious Files
LF_DIRWATCH = “300”
This feature scans /tmp and /dev/shm for potentially malicious files and alerts you to their presence based on the interval you designate. You can also have CSF automatically quarantine malicious files with this option:
LF_DIRWATCH_DISABLE = “0”
Distributed Attack Protection
LF_DISTATTACK = “0”
By enabling this option, you activate additional protection against distributed attacks.
Blocking Based on Abusive Email Usage
LT_POP3D = “0”
LT_IMAPD = “0”
If a user checks email too many times per hour (more than the non-zero value specified), the user’s IP address is blocked.
Blocking IP Addresses Based on Number of Connections
CT_LIMIT = “0”
This feature tracks connections and blocks the IP if the number of connections is too high. Use caution because if you enable this option and set this value too low, it will block legitimate traffic.
Application-Level Protection
PT_LIMIT = “60”
This feature provides application level protection against malicious scripts that take a long time to execute.
Blocking Port Scanners
PS_INTERVAL = “300”
PS_LIMIT = “10”
——————————->
--------