Self-host your own digital island
1# nixos-mailserver: a simple mail server 2# Copyright (C) 2016-2018 Robin Raymond 3# 4# This program is free software: you can redistribute it and/or modify 5# it under the terms of the GNU General Public License as published by 6# the Free Software Foundation, either version 3 of the License, or 7# (at your option) any later version. 8# 9# This program is distributed in the hope that it will be useful, 10# but WITHOUT ANY WARRANTY; without even the implied warranty of 11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12# GNU General Public License for more details. 13# 14# You should have received a copy of the GNU General Public License 15# along with this program. If not, see <http://www.gnu.org/licenses/> 16 17{ config, pkgs, lib, ... }: 18 19let 20 cfg = config.mailserver; 21 certificatesDeps = 22 if cfg.certificateScheme == 1 then 23 [] 24 else if cfg.certificateScheme == 2 then 25 [ "mailserver-selfsigned-certificate.service" ] 26 else 27 [ "acme-finished-${cfg.fqdn}.target" ]; 28in 29{ 30 config = with cfg; lib.mkIf enable { 31 # Create self signed certificate 32 systemd.services.mailserver-selfsigned-certificate = lib.mkIf (cfg.certificateScheme == 2) { 33 after = [ "local-fs.target" ]; 34 script = '' 35 # Create certificates if they do not exist yet 36 dir="${cfg.certificateDirectory}" 37 fqdn="${cfg.fqdn}" 38 [[ $fqdn == /* ]] && fqdn=$(< "$fqdn") 39 key="$dir/key-${cfg.fqdn}.pem"; 40 cert="$dir/cert-${cfg.fqdn}.pem"; 41 42 if [[ ! -f $key || ! -f $cert ]]; then 43 mkdir -p "${cfg.certificateDirectory}" 44 (umask 077; "${pkgs.openssl}/bin/openssl" genrsa -out "$key" 2048) && 45 "${pkgs.openssl}/bin/openssl" req -new -key "$key" -x509 -subj "/CN=$fqdn" \ 46 -days 3650 -out "$cert" 47 fi 48 ''; 49 serviceConfig = { 50 Type = "oneshot"; 51 PrivateTmp = true; 52 }; 53 }; 54 55 # Create maildir folder before dovecot startup 56 systemd.services.dovecot2 = { 57 wants = certificatesDeps; 58 after = certificatesDeps; 59 preStart = let 60 directories = lib.strings.escapeShellArgs ( 61 [ mailDirectory ] 62 ++ lib.optional (cfg.indexDir != null) cfg.indexDir 63 ); 64 in '' 65 # Create mail directory and set permissions. See 66 # <http://wiki2.dovecot.org/SharedMailboxes/Permissions>. 67 mkdir -p ${directories} 68 chgrp "${vmailGroupName}" ${directories} 69 chmod 02770 ${directories} 70 ''; 71 }; 72 73 # Postfix requires dovecot lmtp socket, dovecot auth socket and certificate to work 74 systemd.services.postfix = { 75 wants = certificatesDeps; 76 after = [ "dovecot2.service" ] 77 ++ lib.optional cfg.dkimSigning "opendkim.service" 78 ++ certificatesDeps; 79 requires = [ "dovecot2.service" ] 80 ++ lib.optional cfg.dkimSigning "opendkim.service"; 81 }; 82 }; 83}