Thursday, May 14, 2020

Mail server on CentOS7 (Postfix, Dovecot, Rspamd without DB)

MTA (Mail Transport Agent) - send mail over SMTP protocol - Postfix, OpenSMTPD software (post office)
MUA (Mail User Agent) - e-mail agent - Outlook, Thunderbird etc. (user of mailbox)
MDA (Mail Delivery Agent) - sends mails to MUA using POP3 / IMAP protocols - Dovecot software (mailbox)

For DNS records use https://it-tuff.blogspot.com/2020/05/dns-record-types-and-meaning-types-of.html

mail.mysubd.webredirect.org - A / MX record
vi /etc/hostname
mail.mysubd.webredirect.org
hostnamectl

yum install postfix
yum install dovecot

Adding user for mail management:
groupadd -g 5000 vmail
useradd -s /usr/sbin/nologin -u 5000 -g 5000 vmail

Add user postfix and dovecot to group vmail:
usermod -aG vmail postfix
usermod -aG vmail

Add the folder the mails will be stored in and give rights to user vmail:
mkdir -p /var/mail/vhosts/mysubd.webredirect.org
chown -R vmail:vmail /var/mail/vhosts
chmod -R 775 /var/mail/vhosts

Create dovecot log file:
touch /var/log/dovecot
chgrp vmail /var/log/dovecot
chmod 660 /var/log/dovecot

Virtual mailboxes:
/etc/postfix/vmailbox will be used for that job
Make hash of this file:
postmap /etc/postfix/vmailbox

Virtual aliases:
vi /etc/postfix/virtual # below example redirects all mails to mysubd.webredirect.org to the catch-all@mysubd.webredirect.org
@mysubd.webredirect.org catch-all@mysubd.webredirect.org
postmap /etc/postfix/virtual

Virtual domains (if more than one domain is going to be supported then add a domain per line in the below file):
vi /etc/postfix/virtual_domains
mysubd.webredirect.org

SSL certificate - choose one of below - either self signed certificate or Let's Encrypt certificate.

Self signed certificate:
mkdir /etc/dovecot/ssl
cd /etc/dovecot/ssl
openssl req -new -newkey rsa:3072 -nodes -keyout mailserver.key -days 9999 -x509 -out mailserver.crt
country name > LT
common name > mail.mysubd.webredirect.org

Let's Encrypt certificate:
allow 80 port:
iptables -R INPUT 1 -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
install ACME (Automated Certificate Management Environment) protocol used to automate interactions between CA and users of certs:
yum install certbot
Generate certificate using certbot internal webservice (--standalone option) for communication with CA:
certbot certonly --standalone -d mail.mysubd.webredirect.org
Add default crontab entry for automatic renewal of certificates (each cert is valid for only 90 days):
echo "0 0,12 * * * root python -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew -q" | sudo tee -a /etc/crontab > /dev/null
cat /etc/crontab
Certs are added to /etc/letsencrypt/live/mail.mysubd.webredirect.org directory:
public key is fullchain.pem (goes to smtpd_tls_cert_file)
private key is privkey.pem (goes to smtpd_tls_key_file)

/etc/postfix/main.cf
smtpd_banner = $myhostname ESMTP
biff = no
append_dot_mydomain = no
recipient_delimiter = +
readme_directory = no
#CHANGETHIS
myhostname = mail.mysubd.webredirect.org
#CHANGETHIS
mydomain = mysubd.webredirect.org
myorigin = $mydomain
inet_interfaces = all
# add additional domains to the list below if needed
mydestination = localhost, $myhostname
mynetworks = 127.0.0.0/8
##VIRTUAL DOMAIN##
virtual_mailbox_domains = /etc/postfix/virtual_domains
virtual_mailbox_base = /var/mail/vhosts
virtual_mailbox_maps = hash:/etc/postfix/vmailbox
virtual_alias_maps = hash:/etc/postfix/virtual
virtual_minimum_uid = 100
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
virtual_transport = virtual
dovecot_destination_recipient_limit = 1
mailbox_size_limit = 0
##SASL##
smtpd_sasl_auth_enable = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $mydomain
broken_sasl_auth_clients = yes
##TLS##
smtpd_use_tls=yes
smtpd_tls_security_level = may
smtpd_tls_auth_only = no
smtpd_tls_cert_file=/etc/dovecot/ssl/mailserver.crt
smtpd_tls_key_file=/etc/dovecot/ssl/mailserver.key
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_tls_received_header = yes
tls_random_source = dev:/dev/urandom
smtpd_tls_security_level = may
smtp_tls_security_level = may
##restrictions##
smtpd_helo_required=yes
strict_rfc821_envelopes = yes
disable_vrfy_command = yes
smtpd_delay_reject = yes
##limit rate##
anvil_rate_time_unit = 60s
smtpd_client_connection_rate_limit = 5
smtpd_client_connection_count_limit = 5
smtpd_error_sleep_time = 5s
smtpd_soft_error_limit = 2
smtpd_hard_error_limit = 3
##################
smtpd_helo_restrictions= reject_non_fqdn_hostname,
  reject_invalid_helo_hostname,
  reject_unknown_helo_hostname
smtpd_client_restrictions = permit_mynetworks,
  permit_sasl_authenticated,
  reject_unknown_client_hostname,
  reject_unauth_pipelining,
  reject_rbl_client zen.spamhaus.org
smtpd_sender_restrictions = reject_non_fqdn_sender,
  reject_unknown_sender_domain
smtpd_recipient_restrictions = permit_mynetworks,
  permit_sasl_authenticated,
  reject_invalid_hostname,
  reject_non_fqdn_hostname,
  reject_non_fqdn_sender,
  reject_non_fqdn_recipient,
  reject_unauth_destination,
  reject_unauth_pipelining,
  reject_rbl_client zen.spamhaus.org,
  reject_rbl_client cbl.abuseat.org,
  reject_rbl_client dul.dnsbl.sorbs.net
smtpd_recipient_limit = 250
broken_sasl_auth_clients = yes
#message_size_limit = 120480000
##remove IP header##
# requires postfix-pcre (apt-get install postfix-pcre)
#header_checks has the following content:
#/^\s*(Received: from)[^\n]*(.*)/ REPLACE $1 [127.0.0.1] (localhost [127.0.0.1])$2
#
#smtp_header_checks = pcre:/etc/postfix/header_checks

/etc/dovecot/dovecot.conf
auth_mechanisms = plain login
disable_plaintext_auth = no
log_path = /var/log/dovecot
mail_location = maildir:/var/mail/vhosts/%d/%n
passdb {
  args = /var/mail/vhosts/%d/shadow
  driver = passwd-file
}
protocols = imap pop3
service auth {
  unix_listener /var/spool/postfix/private/auth {
    group = vmail
    mode = 0660
    user = postfix
  }
  unix_listener auth-master {
    group = vmail
    mode = 0600
    user = vmail
  }
}
ssl_cert = </etc/dovecot/ssl/mailserver.crt
ssl_key = </etc/dovecot/ssl/mailserver.key
userdb {
  args = /var/mail/vhosts/%d/passwd
  driver = passwd-file
}
protocol lda {
  auth_socket_path = /var/run/dovecot/auth-master
  #CHANGETHIS
  hostname = mail.mysubd.webredirect.org
  mail_plugin_dir = /usr/libexec/dovecot
  mail_plugins = sieve
  #CHANGETHIS
  postmaster_address = postmaster@mysubd.webredirect.org
}

/etc/postfix/master.cf
dovecot   unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail:vmail argv=/usr/libexec/dovecot/deliver -f ${sender} -d ${recipient}

Script to add users:
vi add_mail.sh
#!/bin/bash
USAGE="Usage: $0 EMAIL PASSWORD [BASEDIR]";
#
if [ ! -n "$2" ]
then
  echo $USAGE;
  exit 1;
fi
#
USERNAME=$(echo "$1" | cut -f1 -d@);
DOMAIN=$(echo "$1" | cut -f2 -d@);
ADDRESS=$1;
PASSWD=$2;
#
if [ -n "$3" ]
then
  if [ ! -d "$3" ]
  then
    echo $USAGE;
    echo "BASEDIR must be a valid directory!";
    echo "I would have tried, $(postconf | grep ^virtual_mailbox_base | cut -f3 -d' ')";
    exit 2;
  else
    BASEDIR="$3";
  fi
else
  BASEDIR="$(postconf | grep ^virtual_mailbox_base | cut -f3 -d' ')";
fi
#
if [ -f /etc/postfix/vmailbox ]
then
#
  echo "Adding Postfix user configuration..."
  echo $ADDRESS $DOMAIN/$USERNAME/ >> /etc/postfix/vmailbox
  postmap /etc/postfix/vmailbox
#
  if [ $? -eq 0 ]
  then
    echo "Adding Dovecot user configuration..."
    echo $ADDRESS::5000:5000::$BASEDIR/$DOMAIN/$ADDRESS>> $BASEDIR/$DOMAIN/passwd
    echo $ADDRESS":"$(doveadm pw -p $PASSWD) >> $BASEDIR/$DOMAIN/shadow
    chown vmail:vmail $BASEDIR/$DOMAIN/passwd && chmod 775 $BASEDIR/$DOMAIN/passwd
    chown vmail:vmail $BASEDIR/$DOMAIN/shadow && chmod 775 $BASEDIR/$DOMAIN/shadow
    systemctl restart postfix
  fi
#
fi

Add previously configured postmaster mail user

Add a new mail user:
./add_mail.sh user@mysubd.webredirect.org Z123456z

systemctl enable postfix
systemctl start postfix
systemctl enable dovecot
systemctl start dovecot
systemctl status dovecot
systemctl status postfix


Check that postfix setting made properly:
postfix check

Check mail queue:
mailq

Force mails from queue to be sent:
postfix flush

To check non-default settings:
postconf -n
dovecot -n

iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 993 -j ACCEPT
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 25 -j ACCEPT

To check all available settings of Postfix (you can use grep to filter output):
postconf

yum install mailx

echo "This is message body" | mailx -s "This is Subject" -r "user<user@mysubd.webredirect.org>"  -a "attachment_file_name" somebody@gmail.com

Also if you just want to send mail once then postfix configuration is too simple (uncomment or add below lines in /etc/postfix/main.cf and then systemctl restart postfix):
inet_interfaces = all
inet_protocols = all
mynetworks=127.0.0./8

To check mail in console use mail (-u key shows mail for specified user):
mail -u root
mail -u admin

25 —  SMTP over STARTTLS;
80 —  HTTP for Postfixadmin and Roundcube;
110 — POP3 через STARTTLS;
143 —IMAP через STARTTLS;
443 — HTTPS for Postfixadmin and Roundcube;
465 — secured SMTP over SSL/TLS;
587 — secured SMTP over STARTTLS;
993 — secured IMAP over SSL/TLS;
995 — secured POP3 over SSL/TLS.

Mail client configuration:
SMTP, IMAP and POP3 server: mail.mysubd.webredirect.org
SMTP Port: 25 (or 587, or 8080. In some networks, port 25 and 587 outgoing are blocked)
IMAP Port: 143
POP3 Port: 110
Security type: SSL/TLS

username: user@mysubd.webredirect.org
(NOT just “user”)

You will receive a warning message for the first time you connect to each, SMTP, IMAP and POP3, because you are using a self-signed certificate.


For SMTPS support uncomment below lines in /etc/postfix/master.cf
smtps     inet  n       -       n       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
  -o smtpd_sasl_type=dovecot
  -o smtpd_sasl_path=private/auth

systemctl restart postfix

Test:
ss -l4n

iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 465 -j ACCEPT

To enable port 587 (submission) uncomment below in master.cf:
submission inet n       -       n       -       -       smtpd

systemctl restart postfix

Test:
ss -l4n

iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 587 -j ACCEPT

To disable port 25 comment below in master.cf:
#smtp      inet  n       -       n       -       -       smtpd

systemctl restart postfix

Test:
ss -l4n


TO TEST MAIL SERVER SETTINGS QUALITY USE: 


Rspamd
yum install epel-release
yum install luajit
curl https://rspamd.com/rpm-stable/centos-7/rspamd.repo > /etc/yum.repos.d/rspamd.repo
rpm --import https://rspamd.com/rpm-stable/gpg.key 
yum update 
yum install redis
systemctl start redis
systemctl status redis

yum install rspamd

vi /etc/postfix/main.cf
# Milter (Mail fILTER) setup
smtpd_milters = inet:localhost:11332
milter_default_action = accept
milter_protocol = 6

systemctl restart postfix
systemctl enable rspamd 
systemctl start rspamd

Check that rspamd ports are up (especially 11332 used for rspamd_proxy - postfix milter)

To configure Rspamd:
rspamadm configwizard
add controller pass
add redis 
add redis pass

systemctl restart redis
systemctl status redis
systemctl restart rspamd

vi /var/log/rspamd/rspamd.log

cat /etc/rspamd/local.d/redis.conf
password = "d123456D";
write_servers = "127.0.0.1:6379";
read_servers = "127.0.0.1:6379";

systemctl restart redis
systemctl status redis
systemctl restart rspamd

vi /etc/rspamd/local.d/dkim_signing.conf
allow_username_mismatch = true;
domain {
             mysubd.webredirect.org {
                         path = "/etc/mail/dkim/mysubd.webredirect.org.key";
                         selector = "20200514";
                         }
}

systemctl restart rspamd
systemctl status rspamd


Outlook ports 993 and 465 (both SSL) + outgoing server needs authentication

Script to delete user:
del_mail.sh

#!/bin/bash
USAGE="Usage: $0 EMAIL [BASEDIR]";
#
if [ ! -n "$1" ]
then
  echo $USAGE;
  exit 1;
fi
#
USERNAME=$(echo "$1" | cut -f1 -d@);
DOMAIN=$(echo "$1" | cut -f2 -d@);
ADDRESS=$1;
#
if [ -n "$2" ]
then
  if [ ! -d "$2" ]
  then
    echo $USAGE;
    echo "BASEDIR must be a valid directory!";
    echo "I would have tried, $(postconf | grep ^virtual_mailbox_base | cut -f3 -d' ')";
    exit 2;
  else
    BASEDIR="$2";
  fi
else
  BASEDIR="$(postconf | grep ^virtual_mailbox_base | cut -f3 -d' ')";
fi
#
echo $BASEDIR
if [ -f /etc/postfix/vmailbox ]
then
#
  echo "Removing Postfix user configuration..."
  sed -i "/$USERNAME/d" /etc/postfix/vmailbox
  postmap /etc/postfix/vmailbox
#
  if [ $? -eq 0 ]
  then
    echo "Removing Dovecot user configuration..."
    sed -i "/$USERNAME/d" $BASEDIR/$DOMAIN/passwd
    sed -i "/$USERNAME/d" $BASEDIR/$DOMAIN/shadow
    systemctl restart postfix
    echo "Removing user mail directory..."
    rm -rf $BASEDIR/$DOMAIN/$USERNAME
  fi
#
fi

To check rspamd work:
 rspamd_stats --log /var/log/rspamd
Ham - is normal mail
Spam - sent to everyone, not wanted by anyone, sent out frequently, 
Junk - sent to specific group, can be interesting for some and irritating for the others, sent out not so frequently, 

No comments:

Post a Comment