Skip to content

Instantly share code, notes, and snippets.

@bennof
Last active January 5, 2020 14:43
Show Gist options
  • Save bennof/bd412538baef534c87d99108faec7d2b to your computer and use it in GitHub Desktop.
Save bennof/bd412538baef534c87d99108faec7d2b to your computer and use it in GitHub Desktop.
Privaten Emailserver Erstellen

Erstellen eines Emailservers mit Debian Postfix und Dovecot

Vorbereitung

Testen der Linuxversion: (Debian 10)

lsb_release -a

Firewall

sudo apt-get install ufw
sudo ufw allow ssh
sudo ufw allow 'OpenSSH'
sudo ufw enable

DNS

Setup DNS:

edo365.de  MX     1 mail.edo365.de.

Der Reverse DNS sollte auch gesetzt sein. Er muss nicht der mail.edo365.de entsprechen, er muss nur zur gleichen IP führen.

Edit /etc/hosts

54.38.158.150   mail.edo365.de    mail

Let's encrypt

sudo apt install nginx
sudo apt-get install python3 python3-pip pipenv

sudo apt install python3-acme python3-certbot python3-mock python3-openssl python3-pkg-resources python3-pyparsing python3-zope.interface

sudo apt install python3-certbot-nginx

Edit /etc/nginx/sites-avai:

# Default server configuration
#
server {
        listen 80;
        listen [::]:80;

        root /var/www/mail.edo365.de;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name mail.edo365.de;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

}
mkdir -p /var/www/mail.edo365.de
sudo ln -s /etc/nginx/sites-available/mail.edo365.de /etc/nginx/sites-enabled/mail.edo365.de
sudo nginx -t
sudo systemctl reload nginx
sudo ufw allow 'Nginx Full'
sudo ufw delete allow 'Nginx HTTP'
sudo certbot --nginx -d mail.edo365.de
sudo certbot renew --dry-run

crontab -e

Datenbank

Installieren des MariaDB Server, da er den MySQL in Debian ersetzt hat.

sudo apt install mariadb-server

Ausführen des Sicherheitsscripts: (die Standartauswahl ist immer zu nehmen)

sudo mysql_secure_installation

Erstellen der Nutzer:

sudo mysql
GRANT ALL ON *.* TO 'admin'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit
sudo systemctl status mariadb

sudo mysqladmin version
mysqladmin -u admin -p version

Installation der Abhängigkeiten

sudo apt-get install postfix postfix-mysql dovecot-core dovecot-imapd dovecot-lmtpd dovecot-mysql dovecot-pop3d

Einrichten der Datenbank

Erstellen der Datenbank:

mysqladmin -u admin -p create edo365_mail

Login (das Admin-Passwort der Datenbank eintragen.):

mysql -u root -p

Erstellen eines Benutzers für die Datenbank und die Datenbank öffnen:

GRANT SELECT ON edo365_mail.* TO 'edo365_mail_user'@'127.0.0.1' IDENTIFIED BY 'mailpassword';
FLUSH PRIVILEGES;
USE edo365_mail;

Anlegen der benötigten Tabellen:

CREATE TABLE `virtual_domains` (
`id`  INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `virtual_users` (
`id` INT NOT NULL AUTO_INCREMENT,
`domain_id` INT NOT NULL,
`password` VARCHAR(106) NOT NULL,
`email` VARCHAR(120) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `virtual_aliases` (
`id` INT NOT NULL AUTO_INCREMENT,
`domain_id` INT NOT NULL,
`source` varchar(100) NOT NULL,
`destination` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Virtuelle Domänen

INSERT INTO `virtual_domains`
(`id` ,`name`)
VALUES
('1', 'edo365.de');

Virtuelle Postfächer

INSERT INTO `virtual_users`
(`id`, `domain_id`, `password` , `email`)
VALUES
('1', '1', ENCRYPT('firstpassword', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), 'bennof@edo365.de');

Virtuelle Weiterleitungen

INSERT INTO `virtual_aliases`
(`id`, `domain_id`, `source`, `destination`)
VALUES
('1', '1', 'benno.falkner@edo365.de', 'bennof@edo365.de'),
('2', '1', 'b.falkner@edo365.de', 'bennof@edo365.de'),
('3', '1', 'contact@edo365.de', 'bennof@edo365.de');

exit

Postfix

Speichern der orginalen Config-Datei

sudo cp /etc/postfix/main.cf /etc/postfix/main.cf.orig
sudo vi /etc/postfix/main.cf
# See /usr/share/postfix/main.cf.dist for a commented, more complete version


# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 2 on
# fresh installs.
compatibility_level = 2


# TLS parameters
smtpd_tls_cert_file=/etc/letsencrypt/live/mail.edo365.de/fullchain.pem; # managed by Certbot
smtpd_tls_key_file=/etc/letsencrypt/live/mail.edo365.de/privkey.pem; # managed by Certbot
smtpd_use_tls=yes
smtpd_tls_auth_only = yes

smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
smtpd_recipient_restrictions =
        permit_sasl_authenticated,
        permit_mynetworks,
        reject_unauth_destination

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination

## Configure Server
myhostname = edo365.de
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
#mydestination = $myhostname, edo365.de, vps740579, localhost.localdomain, localhost
mydestination = localhost 
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all

## Configure Postfix to use Dovecot's LMTP
virtual_transport = lmtp:unix:private/dovecot-lmtp

## Configure Postfix to use MySQL/MariaDB
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf

DB Access

Erstelle /etc/postfix/mysql-virtual-mailbox-domains.cf:

user = edo365_mail_user
password = mailpassword
hosts = 127.0.0.1
dbname = edo365_mail
query = SELECT 1 FROM virtual_domains WHERE name='%s'

Erstelle /etc/postfix/mysql-virtual-mailbox-maps.cf:

user = edo365_mail_user
password = mailpassword
hosts = 127.0.0.1
dbname = edo365_mail
query = SELECT 1 FROM virtual_users WHERE email='%s'

Erstelle /etc/postfix/mysql-virtual-alias-maps.cf:

user = edo365_mail_user
password = mailpassword
hosts = 127.0.0.1
dbname = edo365_mail
query = SELECT destination FROM virtual_aliases WHERE source='%s'
sudo service postfix restart
sudo postmap -q edo365.de mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf # check domain
sudo postmap -q bennof@edo365.de mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf # check mailbox
sudo postmap -q b.falkner@edo365.de mysql:/etc/postfix/mysql-virtual-alias-maps.cf # check alisa

Edit /etc/postfix/master.cf:

submission inet n       -       -       -       -       smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_security_level=encrypt
-o smtpd_sasl_auth_enable=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
service postfix restart
sudo ufw allow Postfix
sudo ufw allow "Postfix SMTPS"
sudo ufw allow "Postfix Submission"

Dovecot

Backup:

sudo cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf.orig
sudo cp /etc/dovecot/conf.d/10-mail.conf /etc/dovecot/conf.d/10-mail.conf.orig
sudo cp /etc/dovecot/conf.d/10-auth.conf /etc/dovecot/conf.d/10-auth.conf.orig
sudo cp /etc/dovecot/dovecot-sql.conf.ext /etc/dovecot/dovecot-sql.conf.ext.orig
sudo cp /etc/dovecot/conf.d/10-master.conf /etc/dovecot/conf.d/10-master.conf.orig
sudo cp /etc/dovecot/conf.d/10-ssl.conf /etc/dovecot/conf.d/10-ssl.conf.orig

Uncomment in /etc/dovecot/dovecot.conf:

!include_try /usr/share/dovecot/protocols.d/*.protocol
protocols = imap lmtp
...
!include conf.d/*.conf

Edit /etc/dovecot/conf.d/10-mail.conf:

mail_location = maildir:/var/mail/vhosts/%d/%n
mail_privileged_group = mail

Create Directories

sudo mkdir -p /var/mail/vhosts/edo365.de
sudo groupadd -g 5000 vmail 
sudo useradd -g vmail -u 5000 vmail -d /var/mail
sudo chown -R vmail:vmail /var/mail
```

Edit /etc/dovecot/conf.d/10-auth.conf:
```
disable_plaintext_auth = yes
...
auth_mechanisms = plain login
...
#!include auth-system.conf.ext
...
!include auth-sql.conf.ext
```

Edit /etc/dovecot/conf.d/auth-sql.conf.ext:
```
passdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}
userdb {
  driver = static
  args = uid=vmail gid=vmail home=/var/mail/vhosts/%d/%n
}
```


Edit: /etc/dovecot/dovecot-sql.conf.ext:
```
Uncomment the driver parameter and set mysql as parameter:

driver = mysql
connect = host=127.0.0.1 dbname=edo365_mail user=edo365_mail_user password=mailpassword
default_pass_scheme = SHA512-CRYPT
Uncomment the password_query line and add this information:

password_query = SELECT email as user, password FROM virtual_users WHERE email='%u';
```

````shell
sudo chown -R vmail:dovecot /etc/dovecot
sudo chmod -R o-rwx /etc/dovecot 
```

Edit /etc/dovecot/conf.d/10-master.conf:
```
##Uncomment inet_listener_imap and modify to port 0
service imap-login {
  inet_listener imap {
    port = 0
}

#Create LMTP socket and this configurations
service lmtp {
   unix_listener /var/spool/postfix/private/dovecot-lmtp {
	   mode = 0600
	   user = postfix
	   group = postfix
   }
  #inet_listener lmtp {
    # Avoid making LMTP visible for the entire internet
    #address =
    #port =
  #}
} 

service auth {

  unix_listener /var/spool/postfix/private/auth {
  mode = 0666
  user = postfix
  group = postfix
  }

  unix_listener auth-userdb {
  mode = 0600
  user = vmail
  #group =
  }

  #unix_listener /var/spool/postfix/private/auth {
  # mode = 0666
  #}

  user = dovecot
}

service auth-worker {
  # Auth worker process is run as root by default, so that it can access
  # /etc/shadow. If this isn't necessary, the user should be changed to
  # $default_internal_user.
  user = vmail
}
```
Edit /etc/dovecot/conf.d/10-ssl.conf:
```
ssl = required
ssl_cert = </etc/letsencrypt/live/mail.edo365.de/fullchain.pem; # managed by Certbot
ssl_key = </etc/letsencrypt/live/mail.edo365.de/privkey.pem; # managed by Certbot
```

```shell
sudo service dovecot restart
sudo ufw allow "Dovecot IMAP"
sudo ufw allow "Dovecot Secure IMAP"
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment