Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

465 rindas
16 KiB

  1. #!/bin/sh
  2. # BEFORE INSTALLING
  3. # Have a Debian or Ubuntu server with a static IP and DNS records (usually
  4. # A/AAAA) that point your domain name to it.
  5. # NOTE WHILE INSTALLING
  6. # On installation of Postfix, select "Internet Site" and put in TLD (without
  7. # `mail.` before it).
  8. # AFTER INSTALLING
  9. # More DNS records will be given to you to install. One of them will be
  10. # different for every installation and is uniquely generated on your machine.
  11. umask 0022
  12. install_packages="postfix postfix-pcre dovecot-imapd dovecot-pop3d dovecot-sieve opendkim opendkim-tools spamassassin spamc net-tools fail2ban"
  13. systemctl -q stop dovecot
  14. systemctl -q stop postfix
  15. apt-get purge ?config-files -y $install_packages
  16. apt-get install -y $install_packages
  17. domain="$(cat /etc/mailname)"
  18. subdom=${MAIL_SUBDOM:-mail}
  19. maildomain="$subdom.$domain"
  20. certdir="/etc/letsencrypt/live/$maildomain"
  21. selfsigned="no" # yes no
  22. allow_suboptimal_ciphers="yes" #yes no
  23. mailbox_format="maildir" # maildir sdbox
  24. allowed_protocols=" imap pop3 " #imap pop3
  25. use_cert_config="no"
  26. country_name="" # IT US UK IN etc etc
  27. state_or_province_name=""
  28. organization_name=""
  29. common_name="$( hostname -f )"
  30. if [ "$use_cert_config" = "yes" ]; then
  31. echo "[req]
  32. default_bit = 4096
  33. distinguished_name = req_distinguished_name
  34. prompt = no
  35. [req_distinguished_name]
  36. countryName = $country_name
  37. stateOrProvinceName = $state_or_province_name
  38. organizationName = $organization_name
  39. commonName = $common_name " > $certdir/certconfig.conf
  40. fi
  41. # Open required mail ports
  42. for port in 993 465 25 587; do
  43. ufw allow "$port" 2>/dev/null
  44. done
  45. if [ "$selfsigned" = "yes" ]; then
  46. rm -f $certdir/privkey.pem
  47. rm -f $certdir/csr.pem
  48. rm -f $certdir/fullchain.pem
  49. echo "Generating a 4096 rsa key and a self-signed certificate that lasts 100 years"
  50. mkdir -p $certdir
  51. openssl genrsa -out $certdir/privkey.pem 4096
  52. if [ "$use_cert_config" = "yes" ]; then
  53. openssl req -new -key $certdir/privkey.pem -out $certdir/csr.pem -config $certdir/certconfig.conf
  54. else
  55. openssl req -new -key $certdir/privkey.pem -out $certdir/csr.pem
  56. fi
  57. openssl req -x509 -days 36500 -key $certdir/privkey.pem -in $certdir/csr.pem -out $certdir/fullchain.pem
  58. else
  59. # Open port 80 for Certbot.
  60. ufw allow 80 2>/dev/null
  61. [ ! -d "$certdir" ] &&
  62. possiblecert="$(certbot certificates 2>/dev/null | grep "Domains:\.* \(\*\.$domain\|$maildomain\)\(\s\|$\)" -A 2 | awk '/Certificate Path/ {print $3}' | head -n1)" &&
  63. certdir="${possiblecert%/*}"
  64. [ ! -d "$certdir" ] &&
  65. certdir="/etc/letsencrypt/live/$maildomain" &&
  66. case "$(netstat -tulpn | grep ":80\s")" in
  67. *nginx*)
  68. apt install -y python3-certbot-nginx
  69. certbot -d "$maildomain" certonly --nginx --register-unsafely-without-email --agree-tos
  70. ;;
  71. *apache*)
  72. apt install -y python3-certbot-apache
  73. certbot -d "$maildomain" certonly --apache --register-unsafely-without-email --agree-tos
  74. ;;
  75. *)
  76. apt install -y python3-certbot
  77. certbot -d "$maildomain" certonly --standalone --register-unsafely-without-email --agree-tos
  78. ;;
  79. esac
  80. fi
  81. [ ! -f "$certdir/fullchain.pem" ] && echo "Error locating or installing SSL certificate." && exit 1
  82. [ ! -f "$certdir/privkey.pem" ] && echo "Error locating or installing SSL certificate." && exit 1
  83. if [ "$selfsigned" != "yes" ]; then
  84. [ ! -f "$certdir/cert.pem" ] && echo "Error locating or installing SSL certificate." && exit 1
  85. fi
  86. [ ! -d "$certdir" ] && echo "Error locating or installing SSL certificate." && exit 1
  87. echo "Configuring Postfix's main.cf..."
  88. # Adding additional vars to fix an issue with receiving emails (relay access denied) and adding it to mydestination.
  89. postconf -e "myhostname = $maildomain"
  90. postconf -e "mail_name = $domain" #This is for the smtpd_banner
  91. postconf -e "mydomain = $domain"
  92. postconf -e 'mydestination = $myhostname, $mydomain, mail, localhost.localdomain, localhost, localhost.$mydomain'
  93. # Change the cert/key files to the default locations of the Let's Encrypt cert/key
  94. postconf -e "smtpd_tls_key_file=$certdir/privkey.pem"
  95. postconf -e "smtpd_tls_cert_file=$certdir/fullchain.pem"
  96. if [ "$selfsigned" != "yes" ]; then
  97. postconf -e "smtp_tls_CAfile=$certdir/cert.pem"
  98. fi
  99. # Enable, but do not require TLS. Requiring it with other server would cause
  100. # mail delivery problems and requiring it locally would cause many other
  101. # issues.
  102. postconf -e 'smtpd_tls_security_level = may'
  103. postconf -e 'smtp_tls_security_level = may'
  104. # TLS required for authentication.
  105. postconf -e 'smtpd_tls_auth_only = yes'
  106. # Exclude insecure and obsolete encryption protocols.
  107. postconf -e 'smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
  108. postconf -e 'smtp_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
  109. postconf -e 'smtpd_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
  110. postconf -e 'smtp_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
  111. # Exclude suboptimal ciphers.
  112. if [ "$allow_suboptimal_ciphers" = "no" ]; then
  113. postconf -e 'tls_preempt_cipherlist = yes'
  114. postconf -e 'smtpd_tls_exclude_ciphers = aNULL, LOW, EXP, MEDIUM, ADH, AECDH, MD5, DSS, ECDSA, CAMELLIA128, 3DES, CAMELLIA256, RSA+AES, eNULL'
  115. fi
  116. # Here we tell Postfix to look to Dovecot for authenticating users/passwords.
  117. # Dovecot will be putting an authentication socket in /var/spool/postfix/private/auth
  118. postconf -e 'smtpd_sasl_auth_enable = yes'
  119. postconf -e 'smtpd_sasl_type = dovecot'
  120. postconf -e 'smtpd_sasl_path = private/auth'
  121. # helo, sender, relay and recipient restrictions
  122. postconf -e "smtpd_sender_login_maps = pcre:/etc/postfix/login_maps.pcre"
  123. postconf -e 'smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_sender_login_mismatch, reject_unknown_reverse_client_hostname, reject_unknown_sender_domain'
  124. postconf -e 'smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination, reject_unknown_recipient_domain'
  125. postconf -e 'smtpd_relay_restrictions = permit_sasl_authenticated, reject_unauth_destination'
  126. postconf -e 'smtpd_helo_required = yes'
  127. postconf -e 'smtpd_helo_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, reject_unknown_helo_hostname'
  128. # NOTE: the trailing slash here, or for any directory name in the home_mailbox
  129. # command, is necessary as it distinguishes a maildir (which is the actual
  130. # directories that what we want) from a spoolfile (which is what old unix
  131. # boomers want and no one else).
  132. postconf -e 'home_mailbox = Mail/Inbox/'
  133. # Prevent "Received From:" header in sent emails in order to prevent leakage of public ip addresses
  134. postconf -e "header_checks = regexp:/etc/postfix/header_checks"
  135. # strips "Received From:" in sent emails
  136. echo "/^Received:.*/ IGNORE
  137. /^X-Originating-IP:/ IGNORE" >> /etc/postfix/header_checks
  138. # Create a login map file that ensures that if a sender wants to send a mail from a user at our local
  139. # domain, they must be authenticated as that user
  140. echo "/^(.*)@$(sh -c "echo $domain | sed 's/\./\\\./'")$/ \${1}" > /etc/postfix/login_maps.pcre
  141. # master.cf
  142. echo "Configuring Postfix's master.cf..."
  143. sed -i '/^\s*-o/d;/^\s*submission/d;/^\s*smtp/d' /etc/postfix/master.cf
  144. echo "smtp unix - - n - - smtp
  145. smtp inet n - y - - smtpd
  146. -o content_filter=spamassassin
  147. submission inet n - y - - smtpd
  148. -o syslog_name=postfix/submission
  149. -o smtpd_tls_security_level=encrypt
  150. -o smtpd_tls_auth_only=yes
  151. -o smtpd_enforce_tls=yes
  152. -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  153. -o smtpd_sender_restrictions=reject_sender_login_mismatch
  154. -o smtpd_sender_login_maps=pcre:/etc/postfix/login_maps.pcre
  155. -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject_unauth_destination
  156. smtps inet n - y - - smtpd
  157. -o syslog_name=postfix/smtps
  158. -o smtpd_tls_wrappermode=yes
  159. -o smtpd_sasl_auth_enable=yes
  160. spamassassin unix - n n - - pipe
  161. user=debian-spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f \${sender} \${recipient}" >> /etc/postfix/master.cf
  162. # By default, dovecot has a bunch of configs in /etc/dovecot/conf.d/ These
  163. # files have nice documentation if you want to read it, but it's a huge pain to
  164. # go through them to organize. Instead, we simply overwrite
  165. # /etc/dovecot/dovecot.conf because it's easier to manage. You can get a backup
  166. # of the original in /usr/share/dovecot if you want.
  167. mv /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.backup.conf
  168. echo "Creating Dovecot config..."
  169. echo "# Dovecot config
  170. # Note that in the dovecot conf, you can use:
  171. # %u for username
  172. # %n for the name in name@domain.tld
  173. # %d for the domain
  174. # %h the user's home directory
  175. ssl = required
  176. ssl_cert = <$certdir/fullchain.pem
  177. ssl_key = <$certdir/privkey.pem
  178. ssl_min_protocol = TLSv1.2
  179. ssl_cipher_list = "'EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA256:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA384:EDH+aRSA+AESGCM:EDH+aRSA+SHA256:EDH+aRSA:EECDH:!aNULL:!eNULL:!MEDIUM:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!RC4:!SEED'"
  180. ssl_prefer_server_ciphers = yes
  181. ssl_dh = </usr/share/dovecot/dh.pem
  182. auth_mechanisms = plain login
  183. auth_username_format = %n
  184. protocols = \$protocols $allowed_protocols
  185. # Search for valid users in /etc/passwd
  186. userdb {
  187. driver = passwd
  188. }
  189. #Fallback: Use plain old PAM to find user passwords
  190. passdb {
  191. driver = pam
  192. }
  193. # Our mail for each user will be in ~/Mail, and the inbox will be ~/Mail/Inbox
  194. # The LAYOUT option is also important because otherwise, the boxes will be \`.Sent\` instead of \`Sent\`.
  195. mail_location = $mailbox_format:~/Mail:INBOX=~/Mail/Inbox:LAYOUT=fs
  196. namespace inbox {
  197. inbox = yes
  198. mailbox Drafts {
  199. special_use = \\Drafts
  200. auto = subscribe
  201. }
  202. mailbox Junk {
  203. special_use = \\Junk
  204. auto = subscribe
  205. autoexpunge = 30d
  206. }
  207. mailbox Sent {
  208. special_use = \\Sent
  209. auto = subscribe
  210. }
  211. mailbox Trash {
  212. special_use = \\Trash
  213. }
  214. mailbox Archive {
  215. special_use = \\Archive
  216. }
  217. }
  218. # Here we let Postfix use Dovecot's authetication system.
  219. service auth {
  220. unix_listener /var/spool/postfix/private/auth {
  221. mode = 0660
  222. user = postfix
  223. group = postfix
  224. }
  225. }
  226. protocol lda {
  227. mail_plugins = \$mail_plugins sieve
  228. }
  229. protocol lmtp {
  230. mail_plugins = \$mail_plugins sieve
  231. }
  232. protocol pop3 {
  233. pop3_uidl_format = %08Xu%08Xv
  234. pop3_no_flag_updates = yes
  235. }
  236. plugin {
  237. sieve = ~/.dovecot.sieve
  238. sieve_default = /var/lib/dovecot/sieve/default.sieve
  239. #sieve_global_path = /var/lib/dovecot/sieve/default.sieve
  240. sieve_dir = ~/.sieve
  241. sieve_global_dir = /var/lib/dovecot/sieve/
  242. }
  243. " > /etc/dovecot/dovecot.conf
  244. # If using an old version of Dovecot, remove the ssl_dl line.
  245. case "$(dovecot --version)" in
  246. 1|2.1*|2.2*) sed -i '/^ssl_dh/d' /etc/dovecot/dovecot.conf ;;
  247. esac
  248. mkdir /var/lib/dovecot/sieve/
  249. echo "require [\"fileinto\", \"mailbox\"];
  250. if header :contains \"X-Spam-Flag\" \"YES\"
  251. {
  252. fileinto \"Junk\";
  253. }" > /var/lib/dovecot/sieve/default.sieve
  254. grep -q '^vmail:' /etc/passwd || useradd vmail
  255. chown -R vmail:vmail /var/lib/dovecot
  256. sievec /var/lib/dovecot/sieve/default.sieve
  257. echo 'Preparing user authentication...'
  258. grep -q nullok /etc/pam.d/dovecot ||
  259. echo 'auth required pam_unix.so nullok
  260. account required pam_unix.so' >> /etc/pam.d/dovecot
  261. # OpenDKIM
  262. # A lot of the big name email services, like Google, will automatically reject
  263. # as spam unfamiliar and unauthenticated email addresses. As in, the server
  264. # will flatly reject the email, not even delivering it to someone's Spam
  265. # folder.
  266. # OpenDKIM is a way to authenticate your email so you can send to such services
  267. # without a problem.
  268. # Create an OpenDKIM key in the proper place with proper permissions.
  269. echo 'Generating OpenDKIM keys...'
  270. mkdir -p "/etc/postfix/dkim/$domain"
  271. opendkim-genkey -D "/etc/postfix/dkim/$domain" -d "$domain" -s "$subdom"
  272. chgrp -R opendkim /etc/postfix/dkim/*
  273. chmod -R g+r /etc/postfix/dkim/*
  274. # Generate the OpenDKIM info:
  275. echo 'Configuring OpenDKIM...'
  276. grep -q "$domain" /etc/postfix/dkim/keytable 2>/dev/null ||
  277. echo "$subdom._domainkey.$domain $domain:$subdom:/etc/postfix/dkim/$domain/$subdom.private" >> /etc/postfix/dkim/keytable
  278. grep -q "$domain" /etc/postfix/dkim/signingtable 2>/dev/null ||
  279. echo "*@$domain $subdom._domainkey.$domain" >> /etc/postfix/dkim/signingtable
  280. grep -q '127.0.0.1' /etc/postfix/dkim/trustedhosts 2>/dev/null ||
  281. echo '127.0.0.1
  282. 10.1.0.0/16' >> /etc/postfix/dkim/trustedhosts
  283. # ...and source it from opendkim.conf
  284. grep -q '^KeyTable' /etc/opendkim.conf 2>/dev/null || echo 'KeyTable file:/etc/postfix/dkim/keytable
  285. SigningTable refile:/etc/postfix/dkim/signingtable
  286. InternalHosts refile:/etc/postfix/dkim/trustedhosts' >> /etc/opendkim.conf
  287. sed -i '/^#Canonicalization/s/simple/relaxed\/simple/' /etc/opendkim.conf
  288. sed -i '/^#Canonicalization/s/^#//' /etc/opendkim.conf
  289. sed -i '/Socket/s/^#*/#/' /etc/opendkim.conf
  290. grep -q '^Socket\s*inet:12301@localhost' /etc/opendkim.conf || echo 'Socket inet:12301@localhost' >> /etc/opendkim.conf
  291. # OpenDKIM daemon settings, removing previously activated socket.
  292. sed -i '/^SOCKET/d' /etc/default/opendkim && echo "SOCKET=\"inet:12301@localhost\"" >> /etc/default/opendkim
  293. # Here we add to postconf the needed settings for working with OpenDKIM
  294. echo 'Configuring Postfix with OpenDKIM settings...'
  295. postconf -e 'smtpd_sasl_security_options = noanonymous, noplaintext'
  296. postconf -e 'smtpd_sasl_tls_security_options = noanonymous'
  297. postconf -e "myhostname = $maildomain"
  298. postconf -e 'milter_default_action = accept'
  299. postconf -e 'milter_protocol = 6'
  300. postconf -e 'smtpd_milters = inet:localhost:12301'
  301. postconf -e 'non_smtpd_milters = inet:localhost:12301'
  302. postconf -e 'mailbox_command = /usr/lib/dovecot/deliver'
  303. # A fix for "Opendkim won't start: can't open PID file?", as specified here: https://serverfault.com/a/847442
  304. /lib/opendkim/opendkim.service.generate
  305. systemctl daemon-reload
  306. # Enable fail2ban security for dovecot and postfix.
  307. [ ! -f /etc/fail2ban/jail.d/emailwiz.local ] && echo "[postfix]
  308. enabled = true
  309. [postfix-sasl]
  310. enabled = true
  311. [sieve]
  312. enabled = true
  313. [dovecot]
  314. enabled = true" > /etc/fail2ban/jail.d/emailwiz.local
  315. sed -i "s|^backend = auto$|backend = systemd|" /etc/fail2ban/jail.conf
  316. # Enable SpamAssassin update cronjob.
  317. if [ -f /etc/default/spamassassin ]
  318. then
  319. sed -i "s|^CRON=0|CRON=1|" /etc/default/spamassassin
  320. printf "Restarting spamassassin..."
  321. service spamassassin restart && printf " ...done\\n"
  322. systemctl enable spamassassin
  323. elif [ -f /etc/default/spamd ]
  324. then
  325. sed -i "s|^CRON=0|CRON=1|" /etc/default/spamd
  326. printf "Restarting spamd..."
  327. service spamd restart && printf " ...done\\n"
  328. systemctl enable spamd
  329. else
  330. printf "!!! Neither /etc/default/spamassassin or /etc/default/spamd exists, this is unexpected and needs to be investigated"
  331. fi
  332. for x in opendkim dovecot postfix fail2ban; do
  333. printf "Restarting %s..." "$x"
  334. service "$x" restart && printf " ...done\\n"
  335. systemctl enable "$x"
  336. done
  337. pval="$(tr -d '\n' <"/etc/postfix/dkim/$domain/$subdom.txt" | sed "s/k=rsa.* \"p=/k=rsa; p=/;s/\"\s*\"//;s/\"\s*).*//" | grep -o 'p=.*')"
  338. dkimentry="$subdom._domainkey.$domain TXT v=DKIM1; k=rsa; $pval"
  339. dmarcentry="_dmarc.$domain TXT v=DMARC1; p=reject; rua=mailto:dmarc@$domain; fo=1"
  340. spfentry="$domain TXT v=spf1 mx a:$maildomain -all"
  341. mxentry="$domain MX 10 $maildomain 300"
  342. useradd -m -G mail dmarc
  343. # Create a cronjob that deletes month-old dmarc feedback:
  344. cat <<EOF > /etc/cron.weekly/dmarc-clean
  345. #!/bin/sh
  346. find /home/dmarc/Mail -type f -mtime +30 -name '*.mail*' -delete >/dev/null 2>&1
  347. exit 0
  348. EOF
  349. chmod 755 /etc/cron.weekly/dmarc-clean
  350. grep -q '^deploy-hook = echo "$RENEWED_DOMAINS" | grep -q' /etc/letsencrypt/cli.ini ||
  351. echo "
  352. deploy-hook = echo \"\$RENEWED_DOMAINS\" | grep -q '$maildomain' && service postfix reload && service dovecot reload" >> /etc/letsencrypt/cli.ini
  353. echo "NOTE: Elements in the entries might appear in a different order in your registrar's DNS settings.
  354. $dkimentry
  355. $dmarcentry
  356. $spfentry
  357. $mxentry" > "$HOME/dns_emailwizard"
  358. printf "\033[31m
  359. _ _
  360. | \ | | _____ ___
  361. | \| |/ _ \ \ /\ / (_)
  362. | |\ | (_) \ V V / _
  363. |_| \_|\___/ \_/\_/ (_)\033[0m
  364. Add these three records to your DNS TXT records on either your registrar's site
  365. or your DNS server:
  366. \033[32m
  367. $dkimentry
  368. $dmarcentry
  369. $spfentry
  370. $mxentry
  371. \033[0m
  372. NOTE: You may need to omit the \`.$domain\` portion at the beginning if
  373. inputting them in a registrar's web interface.
  374. Also, these are now saved to \033[34m~/dns_emailwizard\033[0m in case you want them in a file.
  375. Once you do that, you're done! Check the README for how to add users/accounts
  376. and how to log in.\n"