Monday, August 24, 2020

Short note about MySQL INDEX, KEY


MySQL KEY = INDEX - helps to find data faster via using indexing in needed columns

PRIMARY KEY (PRI) - repetitions in this column (or group of columns) are not allowed, NULL values are not allowed

UNIQUE KEY (UNI - one column) - repetitions in this column are not allowed, NULL values are allowed

UNIQUE KEY (MUL - multiple columns) - repetitions allowed in one column bit not in both at he same time, NULL values are allowed

INDEX=KEY - repetitions allowed, NULL values allowed

FOREIGN KEY = only value existing in other table can be added to this column

Friday, July 17, 2020

Dynamic routing - quick overview (RIP, OSPF)

Three types of dynamic routing protocols:
  1. distance vector (RIP, EIGRP) - works like signpost:
    1. Distance - how far away (metrics)
    2. Vector - which direction (interface and IP address of the next hop)
  2. link-state (OSPF) - works like GPS system and have complete notion of entire network:
    1. Link - interface of the router
    2. State - description of the interface and how this interface is connected to the neighbour
  3. path-vector routing (BGP)

RIP

RIP is Routing Information Protocol.
RIP uses hop count (number of routers you have to pass to get to the destination) as metric
RIP routers copy their routing table to their directly connected neighbors every 30 seconds and neighbor updates own routing table with new routes along with interface on which to route and metric to this route. 
If interface goes down on some router with locally connected interface, then this router can receive routing table with route to this down network and will update it's own routing table with this wrong route and after that every update for that route will increase metric by 1 going to infinity. 
To prevent that issue (so called "counting to infinity") RIP uses maximum hop count of 16.
Also RIP uses split horizon setting to prevent advertising back to the router you learnt from. 
Also if interface goes down - owner router of that interface will send immediate triggered update with metric of 16 (this process called "route poisoning"). So route poisoning overrides split horizon rule.
To prevent this router (whose interface went down) from receiving this route from somebody else - neighbor router in response of received route poison will send poison reverse. So reverse poison overrides split horizon rule.
After route route poisoning and reverse poisoning done, hold-down timer starts (default is 180 seconds) - we wait for better metric for that route if time is gone - route is removed from routing tables of two neighbor routers (which sent route poison and reverse poison).

(config) # router rip
(config-router) # version 2
(config-router) # no auto-summary
(config-router) # network 10.10.10.0
# show ip route
# show ip route rip
R 10.10.10.0/24 [120/1] via 12.12.12.12, 00:00:23 GigabitEthernet0/0

Notes:
  1. version 2 - classless (172.16.1.0 and 172.16.2.0 are seen like to different networks, not like 172.16.0.0 class network)
  2. no auto-summary -bu default RIPv2 makes auto-summary of routes
  3. R - RIP protocol
  4. [120/1] - administrative distance is 120, metric is 1
  5. via 12.12.12.12 - neighbor IP address
  6. 00:00:23 - time elapsed since last update
  7.  GigabitEthernet0/0 - local outgoing interface to the learnt network

OSPF

OSPF is Open Shortest Path First (SPF is algorithm suggested by Edsger W. Dijkstra). 
OSPF uses area notion and by default we use only area 0 (also called backbone area). To move from none-backbone area (for example from area 4 to 5) we need to route packet through backbone area and naturally all non-backbone areas must be connected to the backbone area. Non-backbone areas are called regular area.
If routers are connected to the same switch and not point-to-point then DR (Designated Router) and BDR (Backup Designated Router) election is done. DR and BDR is not property of the entire router but property of the interface of the router in the distinct mutli-access segment. Interfaces of all other routers are shown as DROTHER. Election process is per multi-access segment not per area. With point-to-point link "show ospf neighbor" command just shows "FULL/-" on both routers. Router with the highest Router ID becomes DR and the next router with highest Router ID becomes BDR. We can manually assign priorities (with "ip ospf priority 200" interface command) to the routers to change election results (by default priority is 1 and Router ID is used for elections). 
OSPF operates by sending LSA (Link-State Advertisements) to DR and BDR. Then DR sends LSA to all DROTHER routers. BDR only accepts LSAs and becomes DR if current DR becomes non-operative.
All information from LSAs is analyzed and saved in LSDB (Link-State DataBase). 
Routers only have notion of the entire network in the same area.
Routers in the backbone area are called backbone routers. Routers between 2 areas are called ABR (Area Border Routers).
OSPF router connected to the network using another routing protocol called ASBR (Autonomous System Border Router).
In OSPF route summarisation is done only on ABR and ASBR.
After enabling OSPF router starts to send OSPF hello packets. If hello packet is sent and received, then two routers become neighbors. Some fields of the hello packet must match otherwise routers can't become neighbors:
  1. Hello/Dead Interval - send hello packets each "hello interval seconds" and if response is not received in "dead interval seconds" then router considered "dead"
  2. Area ID - LSA and hello-packets are sent within the same zone
  3. Authentication password - MD5 or clear text passwords can be used
  4. Stub area and flag - OSPF has different area types. Area type must be identical or routers won't become neighbors
Also below fields are also in hello packet:
  1. Router ID - unique ID of the router is the highest IP on any active interface. In order to be independent of physical interfaces states (if interface goes down - Router ID changes) it is better to use loop-back interface (have another subnet for purpose of assigning loop-back addresses from this subnet). 
  2. Neighbors - all neighbor routers of the router sending hello packet are in the hello packet
  3. Router Priority - used to choose DR and BDR
  4. DR / BDR IP - the same meaning as the field's name
After becoming neighbors routers begin to build their LSDB.
OSPF use cost as metric. Cost is reference-bandwidth / interface-bandwidth (example: if reference-bandwidth is 100Mbps and for: 100Mbps interface cost=100/100=1 , for 10Mbps cost=100/10=10). The lower the cost the better the path. If paths have the same cost their added to the LSDB and load-balancing is used.

(config) # router ospf 1
(config-router) # default-information originate always
(config-router) # network 10.10.10.0 0.0.0.255 area 0
(config-router) # network 11.11.11.0 0.0.0.255 area 1
# show ip route
# show ip ospf neighbor
# show ip protocols
# clear ip ospf process
# show ip route ospf
O 10.10.10.0/24 [110/2] via 12.12.12.12, 00:00:23 GigabitEthernet0/0

Notes:
  1. router ospf 1 - enable OSPF and specify local PID. PID can be different on each router. Also hello-packets will be sent through all alive interfaces of that router. To disable this behaviour - execute "passive-interface" command on the interface not connected to the other routers. If interface is passive and it's network is added to the OSPF process, then network of this interface is advertised in OSPF only through non-passive interfaces.
  2. default-information originate always - advertise default route into OSPF. Default route learnt from OSPF is shown as "O*E2" in the output of the "show ip route" command.
  3.  network 10.10.10.0 0.0.0.255 area 0 - OSPF uses wildcard masks (reverse subnet mask). This command saves specified network in the local LSDB of the router and makes interface part of the OSPF advertisement process
  4. network 11.11.11.0 0.0.0.255 area 1 - OSPF ABR have OSPF process with more than one areas. Route learnt from other area (to which the router is not belonging to) is shown as O IA (OSPF Inter-Area)
  5. show ip ospf neighbor - FULL state shows that routers became neighbors
  6. show ip protocols - shows interface status (passive or non-passive) and local Router ID
  7. clear ip ospf process - this command used to stop and start OSPF process in order to for example accept newly assigned local Router ID (also we can use "router-id x.y.z.w" to assign Router ID manually)
  8.  [110/2] - administrative distance is 110, cost (metric) is 2. Cost (same as with RIP) is counted as sum of costs from source router to the destination (if needed we can manually change cost of an interface with command "ip ospf cost 50" executed in the "config-if")

Monday, June 8, 2020

Asterisk "Re-transmission timeout" errors

To avoid Re-transmission timeout errors on public sip trunks:
  1. on the firewall forward udp ports 5060, 10001-20000 to the internal ip address of your pbx
  2. on the firewall turn off any sip alg or sip transformations in the firewall
  3. either disable or set firewall udp timers to 3 minutes or more
  4. make sure your pbx has a static ip address and in the freepbx sip settings set NAT to yes
  5. turn on NAT on in your firewall
  6. if you have a static public ip address use it with your sip provider instead of registration

Asterisk AMI & AstDB (initial steps + Python connect)

First time AMI setup

vi /etc/asterisk/manager.conf minimal configuration required:
[general]
enabled = yes ;AMI
webenabled = no ;AJAM
httptimeout=120
port = 5038
bindaddr = 0.0.0.0
tlsenable=no
[admin]
secret=My$ecr3t
read=all
write=all

Test over telnet:

Wait till connected:
telnet 127.0.0.1 5038

Send below commands:
Action: Login
Username: admin
Secret: My$ecr3t
Events: off

"Enter" twice to get:
Response: Success
Message: Authentication accepted

To logoff:
Action: logoff

AstDB

To view needed permissions:
CLI> manager show commands

To write into astdb:
Action: DBPut
Family: TEST
Key: WhatEverYouWant

DBDel and DBGet are working in the same manner as DBPut above.

Python to AstDB connect

import sqlite3 # it's standard library

Learn name of the table and its structure:
connector = sqlite3.connect("/var/lib/asterisk/astdb.sqlite3")
cursor = connector.cursor()
cursor.execute("select sql from sqlite_master where type = 'table'")
print(cursor.fetchall())

cursor.close()
con.close()

VMware vCD (vCloud Director) first steps


vCloud Director — platform for managing virtual infrastructure in IaaS. 
Main notions are:
  1. Virtual datacenter (VDC) — pool of resources (CPU, RAM, HDD). This is environment where you will create virtual machines (VM), containers (vApp), networks
  2. vApp – is a container and VM placed inside vApp. vApp gives ability to group VMs. This grouping can be based on VMs purpose (mail servers, accounting etc.). vApp helps to manage this groups. Also you can use vApp templates. It's helpful when you have many VMs of the same functionalities
  3. Virtual machines (VM) — in vCloud Director you can create VM from the template or install from needed OS ISO
  4. Catalogs – thees are directories where you can store templates (vApp, VM, ISO) 
  5. Org VDC Networks – this is networks of your virtual Data Center. This networks are  accessible for all vApp and VM. Network can be isolated (without Internet access) and routed (with Internet access)
  6. vApp network - this network works only inside selected vApp and by default this network will not be accessible by VMs from other vApp.
There are two types of vCD GUI - with Adobe Flash and without of using Flash. We'll use GUI without Flash and vCD version 9.7

Adding organizational VDC network

Click on the name of needed data center. In "Networking" section select "Networks", then "ADD":
  1. Select isolated or routed network:
    1. To add routed network you must have "Edge connection" - VMware Edge gateway used to connect your VDC to the external world. Besides that all settings are identical for both isolated and routed networks
  2. Specify descriptive name for that network
  3. Specify IP address of a gateway for that network in CIDR (ex.:10.10.10.1/24)
  4. Share - if want to share this network with other VDC in your organisation
  5. Add static pools if needed (this addresses will be automatically assigned to the VMs connected to that network)
  6. Add DNS to be assigned for VM's in that network (ex.: 8.8.8.8 and 8.8.4.4)
  7. Click "FINISH"
  8. If you get : "VDC does not have any network pool associated with it." error, then your couldn't add a network
If you have Edge gateway, then you can setup DNAT / SNAT / DHCP / Firewall / VPN / Load Balancer of that gateway. Some cloud providers use dedicated VM as gateway and doesn't add any Edge gateway to the VDC. 

Adding vApp and VM

In vCD addition of VM begins from vApp addition:
  1. Add vApp from template (with installed OS)
  2. Add vApp with empty VM
  3. Add empty vApp and add VM later
Click on the name of needed data center. In "Compute" section select "vApps", then "NEW VAPP":
  1. Specify name of the vApp
  2. Click "CREATE" (to add empty vApp) or "ADD VIRTUAL MACHINE"
  3. Select needed template or create custom image
  4. Go through all suggested steps
To customize VM hardware or any other allowed parameters (VM must be powered off in order to change parameters):
  1. Compute > Virtual Machines
  2. Select VM added in vApp (or setup new VM if empty vApp addedd)
  3. Click on VM name
  4. Change all needed parameters
  5. Most used VM network types:
    1. e1000 - emulated Intel 82545EM Gigabit Ethernet, supported by most OS
    2. VMXNET family - VMware Tools must be installed in order to use this type:
      1. VMXNET first version
      2. VMXNET2 - adds Jumbo Frames and other enhancements
      3. VMXNET3 - virtualized NIC 10Gb, more stable than e1000 and uses less CPU resources
  6. Click "SAVE"
To add previously added VM to needed vApp:
  1. Compute > Virtual Machines
  2. Left click on 3 dots on the left of needed VM name
  3. Move to...
  4. Select needed vApp
  5. Select storage-policy and network
  6. "Done"
To change template's default password:
  1. Compute > Virtual Machines
  2. Click on VM name
  3. Guest OS Customization
  4. Check-box below:
    1. Enable guest customization
    2. Allow local administrator password 
    3. Require Administrator to change password on first login
  5. Uncheck-box:
    1. Auto generate password
    2. Change SID
  6. Specify password at the "Specify password"
  7. "SAVE"
Connecting to VM:
  1. Compute > Virtual Machines
  2. Left click on 3 dots on the left of needed VM name
  3. If connecting after "guest customization":
    1. Power On and Force Recustomization
  4. Select "Launch VM Remote Console":
    1. In order to connect to VM, register on https://my.vmware.com/ and download VMRC (VMware Remote Console)
    2. Ctrl + Alt to escape console screen

Tuesday, May 19, 2020

DNS record types needed for MTA server



Types of needed DNS resords (as example I'll use mysubd.webredirect.org):
  • A record points mysubd.webredirect.org to a hard coded IP address
  • MX record - point mysubd.webredirect.org to a mail server. These type of records are special for just mail servers, they can co-exist with A records, and their only use is for routing mail to a different location. All mail implementations check for this record first before attempting to route an e-mail message. If a MX record does not exist for a host, an e-mail delivery would be attempted directly to the IP that the hostname resolves to.
  • PTR record - used to perform a Reverse DNS lookup (match IP address t)
  • FCrDNS (Forward-Confirmed rDNS) - if you have A record for your subdomain (mail.mysubd.webredirect.org) and also PTR record pointing to the same subdomain-name, then you can say that you have reached FCrDNS
  • SPF record - advertise which machines are allowed to send mail on behalf of my domain
  • DKIM - is an email authentication technique that allows the receiver to check that an email was indeed sent and authorized by the owner of that domain.
  • DMARC - technical specification. Mail server decides itself which mail is good or bad using DMARC record. DMARC allows instructing a destination mail server what to do with senders that fail SPF and DKIM tests. Most notably it allows instructing them to reject such senders.


  • Adding DNS records

    Check that server IP address is not is a spammers list:
    https://mxtoolbox.com/blacklists.aspx
    https://www.senderscore.org/

    If you don't have your own url registered to DNS hosting, then register on https://www.dynu.com  (below are for Linux DNS but approach is general to all flavours of DNS).

    Add subdomains and needed records:

    A record:
    1. mail.mysubd.webredirect.org IN  A yourIPaddress
    2. Check:
      1. host mail.mysubd.webredirect.org
      2. dig -t A mail.mysubd.webredirect.org +short
    MX record:
    1. mysubd.webredirect.org. IN MX 10 mail.mysubd.webredirect.org.
    2. Check:
      1. dig -t MX mysubd.webredirect.org +short
    PTR record:
    1. yourIPaddress IN PTR mail.mysubd.webredirect.org
    2. But usually this must be set up on your ISP side
    3. Check:
      1. host yourIPaddress
    SPF record:
    1. not all servers understand SPF record (it's deprecated) so it's good to use both TXT and SPF records. Below I allow sending mail only from servers in my own subdomain:
      1. mysubd.webredirect.org.  IN TXT  "v=spf1 +mx -all"
      2. mysubd.webredirect.org.  IN SPF  "v=spf1 +mx -all"
      3. Options described:
        1. v=spf1 > use SPF v1
        2. + > allow
        3. mx > all servers in mysubd.webredirect.org MX records
        4. - > deny
        5. all > all servers not listed in SPF record
      4. Check:
        1. https://mxtoolbox.com/spf.aspx
    DKIM (create keys of length 1024 - longer keys are generally create problems because of not being supported by many hosts):
    1. create a directory to hold the keys:  mkdir -p /etc/mail/dkim
    2. Generate the keypair and extract the public key out of the private key
      1. openssl genrsa -out /etc/mail/dkim/mysubd.webredirect.org.key 1024
      2. openssl rsa -in /etc/mail/dkim/mysubd.webredirect.org.key -pubout -out /etc/mail/dkim/mysubd.webredirect.org.pub
    3. Add DKIM record:
      1. 20200514._domainkey.mysubd.webredirect.org. IN TXT "v=DKIM1;k=rsa;p=addContentOfPublicKeyHere;"
      2. ; is delimiter between parameters
      3. 20200514 - selector (I used just YYYY.MM.DD of cert generation but you can use anything you want)
    4. Check:
      1. https://dkimcore.org/tools/
    DMARC record:
    1. _dmarc.mysubd.webredirect.org.   IN TXT    "v=DMARC1;p=none;pct=100;rua=mailto:postmaster@mysubd.webredirect.org;"
      1. p > what to do (none - only for reporting / quarantine - adds to spam / reject - rejects mail)
      2. pct > percentage of mail to be filtered
      3. rua > daily report mail
    2. Check:
      1. https://dmarcian.com/dmarc-inspector/

    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,