How Email works

Tharanga Rajapaksha
24 min readMay 17, 2018

--

There are three ways to follow this blog. to know simply what happens with emails you may reffer first part of the blog . The Next part will cover email service components in detailed. third part will describe advance email server configurations.

Simple Email server description

Whenever you send a piece of e-mail, your e-mail client interacts with the SMTP server to handle the sending. The SMTP server on your host may have conversations with other SMTP servers to deliver the e-mail.

Let’s assume that I want to send a piece of e-mail. My e-mail ID is brain, and I have my account on howstuffworks.com. I want to send e-mail to jsmith@mindspring.com. I am using a stand-alone e-mail client like Outlook Express.

When I set up my account at howstuffworks, I told Outlook Express the name of the mail server — mail.howstuffworks.com. When I compose a message and press the Send button, here’s what happens:

  1. Outlook Express connects to the SMTP server at mail.howstuffworks.com using port 25.
  2. Outlook Express has a conversation with the SMTP server, telling the SMTP server the address of the sender and the address of the recipient, as well as the body of the message.
  3. The SMTP server takes the “to” address (jsmith@mindspring.com) and breaks it into two parts: the recipient name (jsmith) and the domain name (mindspring.com). If the “to” address had been another user at howstuffworks.com, the SMTP server would simply hand the message to the POP3 server for howstuffworks.com (using a little program called the delivery agent) . Since the recipient is at another domain, SMTP needs to communicate with that domain.

comment :

MDA (Mail delivery agent ) now handle not only pop3 but also imap. pop3 normally delete mails once it is retrieved from the server. But imap just get a copy when user want to view it.

  1. The SMTP server has a conversation with a Domain Name Server, or DNS (see How Web Servers Work for details). It says, “Can you give me the IP address of the SMTP server for mindspring.com?” The DNS replies with the one or more IP addresses for the SMTP server(s) that Mindspring operates.
  2. The SMTP server at howstuffworks.com connects with the SMTP server at Mindspring using port 25. It has the same simple text conversation that my e-mail client had with the SMTP server for HowStuffWorks, and gives the message to the Mindspring server. The Mindspring server recognizes that the domain name for jsmith is at Mindspring, so it hands the message to Mindspring’s POP3 server, which puts the message in jsmith’s mailbox.

If, for some reason, the SMTP server at HowStuffWorks cannot connect with the SMTP server at Mindspring, then the message goes into a queue. The SMTP server on most machines uses a program called sendmail to do the actual sending, so this queue is called the sendmail queue. Sendmail will periodically try to resend the messages in its queue. For example, it might retry every 15 minutes. After four hours, it will usually send you a piece of mail that tells you there is some sort of problem. After five days, most sendmail configurations give up and return the mail to you undelivered.

The SMTP server understands very simple text commands like HELO, MAIL, RCPT and DATA. The most common commands are:

  • HELO — introduce yourself
  • EHLO — introduce yourself and request extended mode
  • MAIL FROM: — specify the sender
  • RCPT TO: — specify the recipient
  • DATA — specify the body of the message (To, From and Subject should be the first three lines.)
  • RSET — reset
  • QUIT — quit the session
  • HELP — get help on commands
  • VRFY — verify an address
  • EXPN — expand an address
  • VERB — verbose

Advance Email server description

Emil is among better professional communication methods in all around the world. With the corporate demand and the price, configuring a secured, not expensive, reliable and easy to use mail server is a callage. And what each component of a email solution, accomplishing and what are the alternative we have are among most sys admins have in these days.

Understanding mail process

There are mainly two events for a email server. It is better to start to understand the mail process with those two events.

  1. Sending a mail
  2. Receiving a mail

Sending a mail from client 1 to client 2 and client 2 receiving a mail.

Simple Mail Transfer Protocol (SMTP) is an Internet standard for electronic mail (email) transmission. First defined by RFC 821 in 1982.

Although electronic mail servers and other mail transfer agents use SMTP to send and receive mail messages, user-level client mail applications typically use SMTP only for sending messages to a mail server for relaying. For retrieving messages, client applications usually use either IMAP or POP3.

Client authentication

Modern SMTP servers typically require authentication of clients by credentials before allowing access, rather than restricting access by location . This more flexible system is friendly to mobile users and allows them to have a fixed choice of configured outbound SMTP server. SMTP Authentication, often abbreviated SMTP AUTH, is an extension of the SMTP in order to log in using an authentication mechanism.

SMTP connections secured by TLS, known as SMTPS, can be made using STARTTLS.

Although proprietary systems (such as Microsoft Exchange and IBM Notes) and webmail systems (such as Outlook.com, Gmail and Yahoo! Mail) use their own non-standard protocols to access mail box accounts on their own mail servers, all use SMTP when sending or receiving email from outside their own systems.

SMTP communication between mail servers uses TCP port 25. Mail clients on the other hand, often submit the outgoing emails to a mail server on port 587.

SMTP MTA (Mail Transfer Agent)

Sendmail, released with 4.1cBSD, right after RFC 788, was one of the first mail transfer agents to implement SMTP.Over time, as BSD Unix became the most popular operating system on the Internet, sendmail became the most common MTA (mail transfer agent).Some other popular SMTP server programs include Postfix, qmail, Novell GroupWise, Exim, Novell NetMail, Microsoft Exchange Server and Oracle Communications Messaging Server.

Message submission (RFC 2476) and SMTP-AUTH (RFC 2554) were introduced in 1998 and 1999, both describing new trends in email delivery.

SMTP content types

As this protocol started out purely ASCII text-based, it did not deal well with binary files, or characters in many non-English languages. Standards such as Multipurpose Internet Mail Extensions (MIME) were developed to encode binary files for transfer through SMTP. Mail transfer agents (MTAs) developed after Sendmail also tended to be implemented 8-bit-clean, so that the alternate “just send eight” strategy could be used to transmit arbitrary text data (in any 8-bit ASCII-like character encoding) via SMTP. Mojibake was still a problem due to differing character set mappings between vendors, although the email addresses themselves still allowed only ASCII. 8-bit-clean MTAs today tend to support the 8BITMIME extension, permitting binary files to be transmitted almost as easily as plain text. Recently the SMTPUTF8 extension was created to support UTF-8 text, allowing international content and addresses in non-Latin scripts like Cyrillic or Chinese.

Email Process

Email is submitted by a mail client (mail user agent, MUA) to a mail server (mail submission agent, MSA) using SMTP on TCP port 587. Most mailbox providers still allow submission on traditional port 25. The MSA delivers the mail to its mail transfer agent (mail transfer agent, MTA). Often, these two agents are instances of the same software launched with different options on the same machine. Local processing can be done either on a single machine, or split among multiple machines; mail agent processes on one machine can share files, but if processing is on multiple machines, they transfer messages between each other using SMTP, where each machine is configured to use the next machine as a smart host. Each process is an MTA (an SMTP server) in its own right.

The boundary MTA uses the Domain name system (DNS) to look up the mail exchanger record (MX record) for the recipient’s domain (the part of the email address on the right of @). The MX record contains the name of the target host. Based on the target host and other factors, the MTA selects an exchange server: see the article MX record. The MTA connects to the exchange server as an SMTP client.

MTA as Relay and Gateway

Message transfer can occur in a single connection between two MTAs, or in a series of hops through intermediary systems. A receiving SMTP server may be the ultimate destination, an intermediate “relay” (that is, it stores and forwards the message) or a “gateway” (that is, it may forward the message using some protocol other than SMTP). Each hop is a formal handoff of responsibility for the message, whereby the receiving server must either deliver the message or properly report the failure to do so.

Mail Delivery Agent (MDA)

Once the final hop accepts the incoming message, it hands it to a mail delivery agent (MDA) for local delivery. An MDA saves messages in the relevant mailbox format. As with sending, this reception can be done using one or multiple computers, but in the diagram above the MDA is depicted as one box near the mail exchanger box. An MDA may deliver messages directly to storage, or forward them over a network using SMTP or other protocol such as Local Mail Transfer Protocol (LMTP), a derivative of SMTP designed for this purpose.

Local Mail Transfer Protocol (LMTP)

LMTP (Local Mail Transfer Protocol) is an email transfer protocol which is designed as an alternative to Extended SMTP (ESMTP). It was first defined in RFC 2033 and Local Mail Transfer Protocol inherits most of its features and usages from ESMTP, with a few modifications. Like SMTP, Local Mail Transfer Protocol is an Application Layer protocol that relies on TCP transport.

LMTP Usage:

  • LMTP uses the syntax and semantics of ESMTP’s commands.
  • LHLO replaces ESMTP`s standard greeting, EHLO.
  • LMTP rejects the messages that are not immediately deliverable to its destination, thus not requiring a queue. Hence Local Mail Transfer Protocol never runs on TCP port 25, the default SMTP port.
  • LMTP requires a response for each previously successful RCPT command (not simply for the entire message body, like ESMPT). This makes it possible for Local Mail Transfer Protocol to succeed for some recipients and failure for others.

When a mail storage space for a queue cannot be allocated by the mail storage server or an MDA and also prevents the use of conventional SMTP (which can only report delivery success or failure for all or none of the recipients and requires a separate queue for the failed recipients), then Local Mail Transfer Protocol can be called. Unlike ESMP, Local Mail Transfer Protocol is capable of informing the client of delivery success or failure per each recipient, thus permitting the client (usually an Internet-facing gateway) to do the queuing.

Restrictions on the use of LMTP

  • As its name suggests, Local Mail Transfer Protocol is used locally, not over WANs (wide area networks).
  • The use of Local Mail Transfer Protocol must be specifically prearranged between the parties involved.
  • Local Mail Transfer Protocol may not be used on TCP port 25 as it is reserved for SMTP.

Once delivered to the local mail server, the mail is stored for batch retrieval by authenticated mail clients (MUAs). Mail is retrieved by end-user applications, called email clients, using Internet Message Access Protocol (IMAP), a protocol that both facilitates access to mail and manages stored mail, or the Post Office Protocol (POP) which typically uses the traditional mbox mail file format or a proprietary system such as Microsoft Exchange/Outlook or Lotus Notes/Domino. Webmail clients may use either method, but the retrieval protocol is often not a formal standard.

SMTP transport example

A typical example of sending a message via SMTP to two mailboxes (alice and theboss) located in the same mail domain (example.com or localhost.com) is reproduced in the following session exchange. (In this example, the conversation parts are prefixed with S: and C:, for server and client, respectively; these labels are not part of the exchange.)

After the message sender (SMTP client) establishes a reliable communications channel to the message receiver (SMTP server), the session is opened with a greeting by the server, usually containing its fully qualified domain name (FQDN), in this case smtp.example.com. The client initiates its dialog by responding with a HELO command identifying itself in the command's parameter with its FQDN (or an address literal if none is available).[23]

S: 220 smtp.example.com ESMTP Postfix
C: HELO relay.example.com
S: 250 smtp.example.com, I am glad to meet you
C: MAIL FROM:<bob@example.com>
S: 250 Ok
C: RCPT TO:<alice@example.com>
S: 250 Ok
C: RCPT TO:<theboss@example.com>
S: 250 Ok
C: DATA
S: 354 End data with <CR><LF>.<CR><LF>
C: From: "Bob Example" <bob@example.com>
C: To: Alice Example <alice@example.com>
C: Cc: theboss@example.com
C: Date: Tue, 15 January 2008 16:02:43 -0500
C: Subject: Test message
C:
C: Hello Alice.
C: This is a test message with 5 header fields and 4 lines in the message body.
C: Your friend,
C: Bob
C: .
S: 250 Ok: queued as 12345
C: QUIT
S: 221 Bye
{The server closes the connection}

The client notifies the receiver of the originating email address of the message in a MAIL FROM command. This is also the return or bounce address in case the message cannot be delivered. In this example the email message is sent to two mailboxes on the same SMTP server: one for each recipient listed in the To and Cc header fields. The corresponding SMTP command is RCPT TO. Each successful reception and execution of a command is acknowledged by the server with a result code and response message (e.g., 250 Ok).

The transmission of the body of the mail message is initiated with a DATA command after which it is transmitted verbatim line by line and is terminated with an end-of-data sequence. This sequence consists of a new-line (<CR><LF>), a single full stop (period), followed by another new-line. Since a message body can contain a line with just a period as part of the text, the client sends two periods every time a line starts with a period; correspondingly, the server replaces every sequence of two periods at the beginning of a line with a single one. Such escaping method is called dot-stuffing.

The server’s positive reply to the end-of-data, as exemplified, implies that the server has taken the responsibility of delivering the message. A message can be doubled if there is a communication failure at this time, e.g. due to a power shortage: Until the sender has received that 250 reply, it must assume the message was not delivered. On the other hand, after the receiver has decided to accept the message, it must assume the message has been delivered to it. Thus, during this time span, both agents have active copies of the message that they will try to deliver.[24] The probability that a communication failure occurs exactly at this step is directly proportional to the amount of filtering that the server performs on the message body, most often for anti-spam purposes. The limiting timeout is specified to be 10 minutes.[25]

The QUIT command ends the session. If the email has other recipients located elsewhere, the client would QUIT and connect to an appropriate SMTP server for subsequent recipients after the current destination(s) had been queued. The information that the client sends in the HELO and MAIL FROMcommands are added (not seen in example code) as additional header fields to the message by the receiving server. It adds a Received and Return-Path header field, respectively.

Some clients are implemented to close the connection after the message is accepted (250 Ok: queued as 12345), so the last two lines may actually be omitted. This causes an error on the server when trying to send the 221 reply.

Optional extensions

Clients learn what options a server supports, by using the EHLO greeting, as exemplified below, instead of the original HELO (example above). Clients fall back to HELO only if the server does not support SMTP extensions.

Modern clients may use the ESMTP extension keyword SIZE to query the server for the maximum message size that will be accepted. Older clients and servers may try to transfer excessively sized messages that will be rejected after consuming network resources, including connect time to network links that is paid by the minute.

Users can manually determine in advance the maximum size accepted by ESMTP servers. The client replaces the HELO command with the EHLOcommand.

S: 220 smtp2.example.com ESMTP Postfix
C: EHLO bob.example.com
S: 250-smtp2.example.com Hello bob.example.org [192.0.2.201]
S: 250-SIZE 14680064
S: 250-PIPELINING
S: 250 HELP

Thus smtp2.example.com declares that it will accept a fixed maximum message size no larger than 14,680,064 octets (8-bit bytes). Depending on the server’s actual resource usage, it may be currently unable to accept a message this large.

In the simplest case, an ESMTP server will declare a maximum SIZE immediately after receiving an EHLO. According to RFC 1870, however, the numeric parameter to the SIZE extension in the EHLO response is optional. Clients may instead, when issuing a MAIL FROM command, include a numeric estimate of the size of the message they are transferring, so that the server can refuse receipt of overly-large messages.

Refference

Advanced Email server Configurations

Reference:

https://www.c0ffee.net/img/mail_server_diagram.svg

Most updated and practical approach to mail server setup.

Content comming bellow is a abstracted from above url . Thanks to original auther who did nice work.

Above architecture describes most of practical aspects of email servers.

With that out of the way, here’s what this guide will get you:

  • Opportunistic TLS for sending/receiving email with Postfix
  • Access to your email anywhere using IMAP with Dovecot
  • Fast, modern spam filtering with Rspamd
  • Full-text search of your mailbox with Apache Solr
  • DKIM, SPF, and DMARC records to ensure your outgoing mail is not spam-filtered
  • Statistical training of your spam filter based on what you move in/out of the Junk folder
  • Custom email sorting/filtering using sieve

After running this setup for year or so, I have found many aspects to be better than GMail. I think the spam filtering works better, and being able to write a sieve script to sort your inbox is a godsend compared to GMail’s convoluted filter system. And as Google occasionally seems to suspend the accounts of those with opinions they don’t like, you’ll have peace of mind with all your mail on a system you control.

A final note: I run everything on FreeBSD, so you may have to massage some of the commands to work on your Linux flavor of choice, if that’s your thing. All the software used is open source, and should run equally well on any Unix-like OS.

Let’s walk through the architecture. All email (whether sent or received) first goes through Postfix — the Mail Transfer Agent (MTA). Postfix is responsible for transferring email to wherever it’s supposed to go. If the recipient domain’s mailbox is on our own server, Postfix will accept the message for delivery. Otherwise, Postfix will relay the message to the recipient’s mail server.

If you are sending an email to someone, you connect to Postfix over SMTP with mandatory STARTTLS encryption on port 587. After successfully validating your username and password, Postfix will accept your message to relay to the recipient’s mail server over SMTP using opportunistic TLS. (“Opportunistic” means that we will use encryption if the other side supports it, and fall back to plaintext if they don’t.)

If you are receiving an email from someone, the sender’s mail server will connect to Postfix over SMTP with opportunistic TLS on port 25. After doing some basic security and spam checks (like prohibiting unauthorized relaying and ensuring the other side has valid DNS records in place), Postfix will accept the message for delivery.

Whether a message is relayed (you sent an email to someone) or accepted for delivery (someone sent an email to you), it is first filtered through the rspamd milter. (milter is just a term for a Postfix mail filter.) For incoming mail, rspamd does some spam checking and may flag the message as spam or reject it altogether. For outgoing mail, rspamd just takes care of the DKIM signing (discussed in the DKIM section).

If an accepted email makes it through the rspamd milter, it is delivered to Dovecot — the Mail Delivery Agent (MDA) — using a local unix domain socket. Dovecot takes the emails from Postfix and stores them in the user’s mailbox. The mailbox can be stored on the filesystem in a few different formats — with Maildir and mbox being commonly used. Dovecot provides remote access to your mailbox using the POP3 and IMAP protocols. In addition, it supports automatic mail filtering using custom sieve scripts.

When Dovecot receives a message, it first passes it to the Solr server, which indexes it for future full-text searches. Then, a sieve script will run which automatically places mail with the X-SPAM header into the user’s Junk folder. In addition, when a user moves a message in or out of their Junk folder, Dovecot will inform rspamd to re-train a message as spam or ham. POP3 is ancient history, so in our setup we’ll only expose our emails over SSL-secured IMAP.

I run a local LDAP server, which allows me to use a single username and password for all my self-hosted apps. In this guide, I’ll describe how to store your mail credentials and email aliases in LDAP. However, it’s just as easy to store this information in a relational database or flat files.

A quick note: Dovecot supports IMAP IDLE, which provides a pseudo-push functionality to get notified of new mail “instantly.” While this works for most desktop mail clients, such as mutt and OS X’s Mail.app, it isn’t supported by mobile clients (with Android’s K-9 Mail being a notable exception). There is an open-source implementation of the Exchange ActiveSync protocol called Z-Push, which integrates with your IMAP server to provide push notifications to iOS and Android devices.

I ran Z-Push for a few months, but there were enough small bugs (along with the hassle of running PHP in production) to make me uninstall it. Setting my iPhone to check for new mail every 15 minutes is plenty fast for me, and I still have about 40% battery left at the end of the day. However, if you are dead set on having instant email notifications, it might be something to look into. It works well enough, I just didn’t find it worth the trouble.

EDIT (20 Sep 2017): I’ve got native push notifications working on iOS. See this blog post for a step-by-step guide.

Finally, all the examples in this guide will use the example.com domain and non-routable IP addresses. Obviously, you’ll need to acquire your own domain name and public IP address for your mail server, and modify my examples accordingly. All commands in this guide should be run as root unless otherwise specified.

DNS Records

First, you will need to set some DNS records so that other mail servers know where to send your email. If you use a hidden master server to host your DNS like I do, you can just edit your zone file and reload BIND. Otherwise, you can set these records in your DNS provider’s management portal.

You probably want to set a low TTL (around 60 seconds) until you’ve verified everything is working correctly. It’s very annoying to realize you typed the wrong IP address and then have to wait 3 hours for the TTL to expire in order to test again.

The first thing you’ll need is an MX record. MX records tell other mail servers which hosts are running mail servers for a given domain. You can specify multiple MX records, each with their own priority, to use as fallback mail servers when your primary one is down. For my example.com domain, I only have a single mail server, mail.example.com, so in my zone file I have a single MX record. Of course, you will need to substitute your own IP address and domain name.

DNS Configuration

It is critically important that you have reverse DNS records for your mail server host. If your reverse DNS records do not point back to your mail server, other mail servers may reject your email as spam. Normally, you can set reverse DNS records in your hosting provider’s web portal. Make sure to set reverse DNS for both the IPv4 and IPv6 address of your mail server.

Your mail server’s reverse DNS and fully qualified domain name don’t have to match exactly, but your hostname in reverse DNS should probably resolve to the same IP as your MX record. Your best bet is to have it point straight back to your mail server’s hostname. You can verify your reverse DNS record using the dig command:

dig +short -x 203.0.113.42
# mail.example.com.

However, just having any reverse DNS record in place is enough for most mail servers to accept your mail.

You will also need to set an SPF record for your mail server. While an SPF record is not technically required for your mail server to work, having one in place significantly reduces the likelihood of your mail being rejected as spam. An SPF record tells other mail servers which hosts are allowed to send mail on behalf of your domain. In my case, I have a single mail server, and I want others to accept mail from that server only. So my SPF record looks like this:

/usr/local/etc/named/master/example.com.db@  IN  TXT  "v=spf1 mx -all"

This indicates that only my MX records (mail.example.com) are allowed to send mail for example.com, and mail coming from anywhere else should be assumed to be spam and rejected. You can add your SPF definition as a TXT record in your DNS provider’s web portal (without the quotes).

Postfix: The Mail Transfer Agent

Now we’re ready to install and configure some software. I install my packages from FreeBSD ports, so substitute the appropriate commands for your package manager of choice. First, bring everything up to date:

portsnap fetch && portsnap update
portmaster -aBd

Postfix will be responsible for sending and receiving mail for our domain over SMTP. Install it from ports:

cd /usr/ports/mail/postfix
make install clean

For my setup, I use the following build options: LDAP PCRE PGSQL TLS.

Once you’ve watched the magic text scroll for a few minutes, postfix should be installed. Navigate to it’s configuration directory and edit the config file. (On FreeBSD, software packages from ports are always installed under the /usr/local prefix. It should be under /etc/postfix if you’re on Linux.)

cd /usr/local/etc/postfix
vim main.cf

Below is what I have in my main.cf. I’ve given you some brief commentary on what all the config options do, but you can always check the man page if you need more details on something. This is a pretty standard virtual users setup. Rather than host mail for actual unix accounts on the server, postfix will use an external database (LDAP, in my case) to determine which email addresses it should accept mail for.

When a message is accepted for delivery, postfix hands it off to Dovecot. Postfix will also use Dovecot’s auth mechanism to authenticate SMTP users. We’ll configure the LDAP authentication in the Dovecot section and let postfix just re-use it.

We’ll set some standard spam-proofing and security options here as well, but we’ll be coming back to this file when we set up rspamd in the section below.

/usr/local/etc/postfix/main.cf# "2" is current for postfix 3.2 configs
compatibility_level = 2
# disable "new mail" notifications for local unix users
biff = no
# directory to store mail for local unix users
mail_spool_directory = /var/mail/local
# Name of this mail server, used in the SMTP HELO for outgoing mail. Make
# sure this resolves to the same IP as your reverse DNS hostname.
myhostname = mail.example.com
# Domains for which postfix will deliver local mail. Does not apply to
# virtual domains, which are configured below. Make sure to specify the FQDN
# of your sever, as well as localhost.
# Note: NEVER specify any virtual domains here!!! Those come later.
mydestination = awesomebox.example.com, localhost.example.com, localhost
# Domain appended to mail sent locally from this machine - such as mail sent
# via the `sendmail` command.
myorigin = awesomebox.example.com
# prevent spammers from searching for valid users
disable_vrfy_command = yes
# require properly formatted email addresses - prevents a lot of spam
strict_rfc821_envelopes = yes
# don't give any helpful info when a mailbox doesn't exist
show_user_unknown_table_name = no
# limit maximum e-mail size to 50MB. mailbox size must be at least as big as
# the message size for the mail to be accepted, but has no meaning after
# that since we are using Dovecot for delivery.
message_size_limit = 51200000
mailbox_size_limit = 51200000
# require addresses of the form "user@domain.tld"
allow_percent_hack = no
swap_bangpath = no
# allow plus-aliasing: "user+tag@domain.tld" delivers to "user" mailbox
recipient_delimiter = +
# path to the SSL certificate for the mail server
smtpd_tls_cert_file = /usr/local/etc/ssl/certs/mail.example.com.rsa.crt
smtpd_tls_key_file = /usr/local/etc/ssl/certs/mail.example.com.rsa.key
# I have two certificates - one is RSA, the other uses the newer ECC. ECC is
# faster and arguably more secure, but many mail servers don't yet support
# it. I enable both types in postfix, but you most likely only have a single
# RSA cert, and don't need to include these three lines.
smtpd_tls_eccert_file = /usr/local/etc/ssl/certs/mail.example.com.ecc.crt
smtpd_tls_eckey_file = /usr/local/etc/ssl/certs/mail.example.com.ecc.key
smtpd_tls_eecdh_grade = ultra
# Path to your trusted certificates file. Usually provided by a
# ca-certificates package or similar.
smtp_tls_CAfile=/etc/ssl/cert.pem
# These two lines define how postfix will connect to other mail servers.
# DANE is a stronger form of opportunistic TLS. You can read about it here:
# http://www.postfix.org/TLS_README.html#client_tls_dane
smtp_tls_security_level = dane
smtp_dns_support_level = dnssec
# DANE requires a DNSSEC capable resolver. If your DNS resolver doesn't
# support DNSSEC, remove the above two lines and uncomment the below:
# smtp_tls_security_level = may
# IP address used by postfix to send outgoing mail. You only need this if
# your machine has multiple IP addresses - set it to your MX address to
# satisfy your SPF record.
smtp_bind_address = 203.0.113.42
smtp_bind_address6 = 2001:db8::3
# Here we define the options for "mandatory" TLS. In our setup, TLS is only
# "mandatory" for authenticating users. I got these settings from Mozilla's
# SSL reccomentations page.
#
# NOTE: do not attempt to make TLS mandatory for all incoming/outgoing
# connections. Do not attempt to change the default cipherlist for non-
# mandatory connections either. There are still a lot of mail servers out
# there that do not use TLS, and many that do only support old ciphers.
# Forcing TLS for everyone *will* cause you to lose mail.
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1, TLSv1.2
smtpd_tls_mandatory_ciphers = high
tls_high_cipherlist = ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256
# allow other mail servers to connect using TLS, but don't require it
smtpd_tls_security_level = may
# tickets and compression have known vulnerabilities
tls_ssl_options = no_ticket, no_compression
# it's more secure to generate your own DH params
smtpd_tls_dh512_param_file = /usr/local/etc/ssl/dh512.pem
smtpd_tls_dh1024_param_file = /usr/local/etc/ssl/dh2048.pem
# cache incoming and outgoing TLS sessions
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_tlscache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_tlscache
# enable SMTPD auth. Dovecot will place an `auth` socket in postfix's
# runtime directory that we will use for authentication.
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_type = dovecot
# only allow authentication over TLS
smtpd_tls_auth_only = yes
# don't allow plaintext auth methods on unencrypted connections
smtpd_sasl_security_options = noanonymous, noplaintext
# but plaintext auth is fine when using TLS
smtpd_sasl_tls_security_options = noanonymous
# add a message header when email was recieved over TLS
smtpd_tls_received_header = yes
# require that connecting mail servers identify themselves - this greatly
# reduces spam
smtpd_helo_required = yes
# The following block specifies some security restrictions for incoming
# mail. The gist of it is, authenticated users and connections from
# localhost can do anything they want. Random people connecting over the
# internet are treated with more suspicion: they must have a reverse DNS
# entry and present a valid, FQDN HELO hostname. In addition, they can only
# send mail to valid mailboxes on the server, and the sender's domain must
# actually exist.
smtpd_client_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_unknown_reverse_client_hostname,
# you might want to consider:
# reject_unknown_client_hostname,
# here. This will reject all incoming connections without a reverse DNS
# entry that resolves back to the client's IP address. This is a very
# restrictive check and may reject legitimate mail.
reject_unauth_pipelining
smtpd_helo_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_invalid_helo_hostname,
reject_non_fqdn_helo_hostname,
# you might want to consider:
# reject_unknown_helo_hostname,
# here. This will reject all incoming mail without a HELO hostname that
# properly resolves in DNS. This is a somewhat restrictive check and may
# reject legitimate mail.
reject_unauth_pipelining
smtpd_sender_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_non_fqdn_sender,
reject_unknown_sender_domain,
reject_unauth_pipelining
smtpd_relay_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
# !!! THIS SETTING PREVENTS YOU FROM BEING AN OPEN RELAY !!!
reject_unauth_destination
# !!! DO NOT REMOVE IT UNDER ANY CIRCUMSTANCES !!!
smtpd_recipient_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_non_fqdn_recipient,
reject_unknown_recipient_domain,
reject_unauth_pipelining,
reject_unverified_recipient
smtpd_data_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_multi_recipient_bounce,
reject_unauth_pipelining
# deliver mail for virtual users to Dovecot's LMTP socket
virtual_transport = lmtp:unix:private/dovecot-lmtp
# LDAP query to find which domains we accept mail for
virtual_mailbox_domains = ldap:/usr/local/etc/postfix/ldap-virtual-mailbox-domains.cf
# LDAP query to find which email addresses we accept mail for
virtual_mailbox_maps = ldap:/usr/local/etc/postfix/ldap-virtual-mailbox-maps.cf, hash:/usr/local/etc/postfix/system-virtual-mailboxes
# LDAP query to find a user's email aliases
virtual_alias_maps = ldap:/usr/local/etc/postfix/ldap-virtual-alias-maps.cf
# We'll uncomment these when we set up rspamd later:
# milter_protocol = 6
# milter_default_action = accept
# smtpd_milters = unix:/var/run/rspamd/milter.sock
# milter_mail_macros = i {mail_addr} {client_addr} {client_name} {auth_authen}

We’ll need to create some of the files and directories we specified in this file:

# create the local mail spool
mkdir /var/mail/local
chown root:mail /var/mail/local
chmod 775 /var/mail/local
# create the dhparams
openssl dhparam -out /usr/local/etc/ssl/dh512.pem 512
openssl dhparam -out /usr/local/etc/ssl/dh2048.pem 2048
chmod 644 /usr/local/etc/ssl/dh{512,2048}.pem

In master.cf, you can set service-specific overrides for the options you set in main.cf. We’ll use this file to make encryption mandatory on the submission port (587). You can just change the lines below the smtp and submission declarations — no need to change anything else in this file.

--

--

No responses yet