mirror of
https://github.com/mail-in-a-box/mailinabox.git
synced 2026-03-12 17:07:23 +01:00
Compare commits
237 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2aca421415 | ||
|
|
99474b348f | ||
|
|
8bebaf6a48 | ||
|
|
9004bb6e8e | ||
|
|
69d8fdef99 | ||
|
|
eeee712cf3 | ||
|
|
8f42d97b54 | ||
|
|
6e40c69cb5 | ||
|
|
c0e54f87d7 | ||
|
|
3a7de051ee | ||
|
|
f11cb04a72 | ||
|
|
cb564a130a | ||
|
|
d1d6318862 | ||
|
|
34b7a02f4f | ||
|
|
a312acc3bc | ||
|
|
aab1ec691c | ||
|
|
520caf6557 | ||
|
|
c92fd02262 | ||
|
|
a85c429a85 | ||
|
|
50a5cb90bc | ||
|
|
aac878dce5 | ||
|
|
58b0323b36 | ||
|
|
646f971d8b | ||
|
|
86067be142 | ||
|
|
c67ff241c4 | ||
|
|
7b4cd443bf | ||
|
|
34017548d5 | ||
|
|
65861c68b7 | ||
|
|
71a7a3e201 | ||
|
|
1c3bca53bb | ||
|
|
b643cb3478 | ||
|
|
113b7bd827 | ||
|
|
3e19f85fad | ||
|
|
11e84d0d40 | ||
|
|
79966e36e3 | ||
|
|
66b15d42a5 | ||
|
|
df46e1311b | ||
|
|
353084ce67 | ||
|
|
91079ab934 | ||
|
|
e5909a6287 | ||
|
|
26932ecb10 | ||
|
|
e884c4774f | ||
|
|
53ec0f39cb | ||
|
|
700188c443 | ||
|
|
ba80d9e72d | ||
|
|
a71a58e816 | ||
|
|
67b5711c68 | ||
|
|
20ccda8710 | ||
|
|
0ba841c7b6 | ||
|
|
daad122236 | ||
|
|
21ad26e452 | ||
|
|
4cb46ea465 | ||
|
|
35fa3fe891 | ||
|
|
d510c8ae2a | ||
|
|
e283a12047 | ||
|
|
e421addf1c | ||
|
|
354a774989 | ||
|
|
aaa81ec879 | ||
|
|
dbd6dae5ce | ||
|
|
d4c5872547 | ||
|
|
3701e05d92 | ||
|
|
bc4ae51c2d | ||
|
|
12aaebfc54 | ||
|
|
49813534bd | ||
|
|
16e81e1439 | ||
|
|
b7b67e31b7 | ||
|
|
2e7f2835e7 | ||
|
|
8a5f9f464a | ||
|
|
69fc2fdd3a | ||
|
|
9b07d86bf7 | ||
|
|
ae3feebd80 | ||
|
|
2c295bcafd | ||
|
|
8cda58fb22 | ||
|
|
178c587654 | ||
|
|
34569d24a9 | ||
|
|
6653dbb2e2 | ||
|
|
5fc1162355 | ||
|
|
a839602cba | ||
|
|
f21a41dc84 | ||
|
|
055ac07663 | ||
|
|
c7b295f403 | ||
|
|
d36a2cc938 | ||
|
|
82ca54df96 | ||
|
|
af62e7a99b | ||
|
|
90d63fd208 | ||
|
|
e81963e585 | ||
|
|
b1d703a5e7 | ||
|
|
e3d98b781e | ||
|
|
50d50ba653 | ||
|
|
879467d358 | ||
|
|
8025c41ee4 | ||
|
|
7a5d729a53 | ||
|
|
e2f9cd845a | ||
|
|
e26cf4512c | ||
|
|
c7280055a8 | ||
|
|
003e8b7bb1 | ||
|
|
3422cc61ce | ||
|
|
8664afa997 | ||
|
|
82229ce04b | ||
|
|
f66e609d3f | ||
|
|
b85b86e6de | ||
|
|
7fd35bbd11 | ||
|
|
7ce41e3865 | ||
|
|
92221f9efb | ||
|
|
0bd3977cde | ||
|
|
6a979f4f52 | ||
|
|
545e7a52e4 | ||
|
|
48c233ebe5 | ||
|
|
9a588de754 | ||
|
|
ac9ecc3bd3 | ||
|
|
8b166f3041 | ||
|
|
5509420637 | ||
|
|
7d6c7b6610 | ||
|
|
1f0e493b8c | ||
|
|
ada2167d08 | ||
|
|
be5032ffbe | ||
|
|
00b3a3b0a9 | ||
|
|
6d82c0035a | ||
|
|
4dced10a3f | ||
|
|
b80f225691 | ||
|
|
7f0f28f8e3 | ||
|
|
a8ea456b49 | ||
|
|
03bff5292b | ||
|
|
e891a9a3f3 | ||
|
|
51aedcf6c3 | ||
|
|
853008ddcc | ||
|
|
7d6427904f | ||
|
|
dcb93d071c | ||
|
|
2ea97f0643 | ||
|
|
4791c2fc62 | ||
|
|
49c333221a | ||
|
|
481a333dc0 | ||
|
|
b0df35eba0 | ||
|
|
08ae3d2b7f | ||
|
|
7c4eb0fb70 | ||
|
|
ee01eae55e | ||
|
|
89b301afc7 | ||
|
|
ce70f44c58 | ||
|
|
6594e19a1f | ||
|
|
8597646a12 | ||
|
|
f205c48564 | ||
|
|
3c3683429b | ||
|
|
a7a66929aa | ||
|
|
0d72566c99 | ||
|
|
62db58eaaf | ||
|
|
891de8d6c3 | ||
|
|
62b9b1f15f | ||
|
|
94da7bb088 | ||
|
|
65983b8ac7 | ||
|
|
56d0289ed9 | ||
|
|
f253c40012 | ||
|
|
4bbe4af377 | ||
|
|
2c34a6df2b | ||
|
|
1098e2b48e | ||
|
|
c50170b816 | ||
|
|
cd518e6820 | ||
|
|
967409b157 | ||
|
|
1b2711fc42 | ||
|
|
e6102eacfb | ||
|
|
6fd3195275 | ||
|
|
224242dfde | ||
|
|
049bfb6f7f | ||
|
|
12d60d102b | ||
|
|
9db2fc7f05 | ||
|
|
e03a6541ce | ||
|
|
41642f2f59 | ||
|
|
df9bb263dc | ||
|
|
339c330b4f | ||
|
|
cfc8fb484c | ||
|
|
bc1be9d70a | ||
|
|
3a4b8da8fd | ||
|
|
37dad9d4bb | ||
|
|
b805f8695e | ||
|
|
10bedad3a3 | ||
|
|
afc9f9686a | ||
|
|
7de8fc9bc0 | ||
|
|
c87b62b8c2 | ||
|
|
8fe33da85d | ||
|
|
c202a5cbc6 | ||
|
|
1353949e42 | ||
|
|
c19f8c9ee6 | ||
|
|
40b21c466d | ||
|
|
f52749b403 | ||
|
|
d67e09f334 | ||
|
|
e224fc6656 | ||
|
|
5e47677f7a | ||
|
|
db9637ce4f | ||
|
|
f908bc364e | ||
|
|
30c2c60f59 | ||
|
|
ab5ce01bdd | ||
|
|
ddadb6c28a | ||
|
|
23be1031b8 | ||
|
|
faee29ba8b | ||
|
|
b86bf07d57 | ||
|
|
e6294049bc | ||
|
|
30885bcc8a | ||
|
|
a67f90593d | ||
|
|
385340da46 | ||
|
|
0271e549bb | ||
|
|
f53b18ebb9 | ||
|
|
8567a9b719 | ||
|
|
ad9d732608 | ||
|
|
aa15670dc2 | ||
|
|
81176c8e4b | ||
|
|
960b5d5bbd | ||
|
|
802e7a1f4d | ||
|
|
52c68c6510 | ||
|
|
54b1ee9a3d | ||
|
|
6e3dee8b3b | ||
|
|
cd62fd9826 | ||
|
|
91638c7fe0 | ||
|
|
ff8170d5ab | ||
|
|
f6f75f6fab | ||
|
|
2f54f39f31 | ||
|
|
fa792f664e | ||
|
|
b50dfb7f93 | ||
|
|
cde4e0caca | ||
|
|
df80b9fc71 | ||
|
|
7558ffd4f3 | ||
|
|
50e9e8af30 | ||
|
|
ed02e2106b | ||
|
|
24a567c3be | ||
|
|
70f05e9d52 | ||
|
|
889118aeb6 | ||
|
|
a70ba94b0c | ||
|
|
9e29564f48 | ||
|
|
5aeced5c2e | ||
|
|
46f64e0e0a | ||
|
|
4971b63501 | ||
|
|
3ff9817325 | ||
|
|
d6becddbe5 | ||
|
|
1d6793d124 | ||
|
|
c7377e602d | ||
|
|
08021ea19f | ||
|
|
295d481603 | ||
|
|
c4cb828f65 | ||
|
|
0657f9e875 |
@@ -13,7 +13,7 @@ trim_trailing_whitespace = true
|
|||||||
insert_final_newline = true
|
insert_final_newline = true
|
||||||
|
|
||||||
[Makefile]
|
[Makefile]
|
||||||
indent_style = tabs
|
indent_style = tab
|
||||||
indent_size = 4
|
indent_size = 4
|
||||||
|
|
||||||
[Vagrantfile]
|
[Vagrantfile]
|
||||||
@@ -23,7 +23,7 @@ indent_size = 2
|
|||||||
indent_size = 2
|
indent_size = 2
|
||||||
|
|
||||||
[*.py]
|
[*.py]
|
||||||
indent_style = tabs
|
indent_style = tab
|
||||||
|
|
||||||
[*.js]
|
[*.js]
|
||||||
indent_size = 2
|
indent_size = 2
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -5,3 +5,4 @@ tools/__pycache__/
|
|||||||
externals/
|
externals/
|
||||||
.env
|
.env
|
||||||
.vagrant
|
.vagrant
|
||||||
|
api/docs/api-docs.html
|
||||||
306
CHANGELOG.md
306
CHANGELOG.md
@@ -1,6 +1,312 @@
|
|||||||
CHANGELOG
|
CHANGELOG
|
||||||
=========
|
=========
|
||||||
|
|
||||||
|
Version 57 (June 12, 2022)
|
||||||
|
--------------------------
|
||||||
|
|
||||||
|
Setup:
|
||||||
|
|
||||||
|
* Fixed issue upgrading from Mail-in-a-Box v0.40-v0.50 because of a changed URL that Nextcloud is downloaded from.
|
||||||
|
|
||||||
|
Backups:
|
||||||
|
|
||||||
|
* Fixed S3 backups which broke with duplicity 0.8.23.
|
||||||
|
* Fixed Backblaze backups which broke with latest b2sdk package by rolling back its version.
|
||||||
|
|
||||||
|
Control panel:
|
||||||
|
|
||||||
|
* Fixed spurious changes in system status checks messages by sorting DNSSEC DS records.
|
||||||
|
* Fixed fail2ban lockout over IPv6 from excessive loads of the system status checks.
|
||||||
|
* Fixed an incorrect IPv6 system status check message.
|
||||||
|
|
||||||
|
Version 56 (January 19, 2022)
|
||||||
|
-----------------------------
|
||||||
|
|
||||||
|
Software updates:
|
||||||
|
|
||||||
|
* Roundcube updated to 1.5.2 (from 1.5.0), and the persistent_login and CardDAV (to 4.3.0 from 3.0.3) plugins are updated.
|
||||||
|
* Nextcloud updated to 20.0.14 (from 20.0.8), contacts to 4.0.7 (from 3.5.1), and calendar to 3.0.4 (from 2.2.0).
|
||||||
|
|
||||||
|
Setup:
|
||||||
|
|
||||||
|
* Fixed failed setup if a previous attempt failed while updating Nextcloud.
|
||||||
|
|
||||||
|
Control panel:
|
||||||
|
|
||||||
|
* Fixed a crash if a custom DNS entry is not under a zone managed by the box.
|
||||||
|
* Fix DNSSEC instructions typo.
|
||||||
|
|
||||||
|
Other:
|
||||||
|
|
||||||
|
* Set systemd journald log retention to 10 days (from no limit) to reduce disk usage.
|
||||||
|
* Fixed log processing for submission lines that have a sasl_sender or other extra information.
|
||||||
|
* Fix DNS secondary nameserver refesh failure retry period.
|
||||||
|
|
||||||
|
Version 55 (October 18, 2021)
|
||||||
|
-----------------------------
|
||||||
|
|
||||||
|
Mail:
|
||||||
|
|
||||||
|
* "SMTPUTF8" is now disabled in Postfix. Because Dovecot still does not support SMTPUTF8, incoming mail to internationalized addresses was bouncing. This fixes incoming mail to internationalized domains (which was probably working prior to v0.40), but it will prevent sending outbound mail to addresses with internationalized local-parts.
|
||||||
|
* Upgraded to Roundcube 1.5.
|
||||||
|
|
||||||
|
Control panel:
|
||||||
|
|
||||||
|
* The control panel menus are now hidden before login, but now non-admins can log in to access the mail and contacts/calendar instruction pages.
|
||||||
|
* The login form now disables browser autocomplete in the two-factor authentication code field.
|
||||||
|
* After logging in, the default page is now a fast-loading welcome page rather than the slow-loading system status checks page.
|
||||||
|
* The backup retention period option now displays for B2 backup targets.
|
||||||
|
* The DNSSEC DS record recommendations are cleaned up and now recommend changing records that use SHA1.
|
||||||
|
* The Munin monitoring pages no longer require a separate HTTP basic authentication login and can be used if two-factor authentication is turned on.
|
||||||
|
* Control panel logins are now tied to a session backend that allows true logouts (rather than an encrypted cookie).
|
||||||
|
* Failed logins no longer directly reveal whether the email address corresponds to a user account.
|
||||||
|
* Browser dark mode now inverts the color scheme.
|
||||||
|
|
||||||
|
Other:
|
||||||
|
|
||||||
|
* Fail2ban's IPv6 support is enabled.
|
||||||
|
* The mail log tool now doesn't crash if there are email addresess in log messages with invalid UTF-8 characters.
|
||||||
|
* Additional nsd.conf files can be placed in /etc/nsd.conf.d.
|
||||||
|
|
||||||
|
v0.54 (June 20, 2021)
|
||||||
|
---------------------
|
||||||
|
|
||||||
|
Mail:
|
||||||
|
|
||||||
|
* Forwarded mail using mail filter rules (in Roundcube; "sieve" rules) stopped re-writing the envelope address at some point, causing forwarded mail to often be marked as spam by the final recipient. These forwards will now re-write the envelope as the Mail-in-a-Box user receiving the mail to comply with SPF/DMARC rules.
|
||||||
|
* Sending mail is now possible on port 465 with the "SSL" or "TLS" option in mail clients, and this is now the recommended setting. Port 587 with STARTTLS remains available but should be avoided when configuring new mail clients.
|
||||||
|
* Roundcube's login cookie is updated to use a new encryption algorithm (AES-256-CBC instead of DES-EDE-CBC).
|
||||||
|
|
||||||
|
DNS:
|
||||||
|
|
||||||
|
* The ECDSAP256SHA256 DNSSEC algorithm is now available. If a DS record is set for any of your domain names that have DNS hosted on your box, you will be prompted by status checks to update the DS record at your convenience.
|
||||||
|
* Null MX records are added for domains that do not serve mail.
|
||||||
|
|
||||||
|
Contacts/calendar:
|
||||||
|
|
||||||
|
* Updated Nextcloud to 20.0.8, contacts to 3.5.1, calendar to 2.2.0 (#1960).
|
||||||
|
|
||||||
|
Control panel:
|
||||||
|
|
||||||
|
* Fixed a crash in the status checks.
|
||||||
|
* Small wording improvements.
|
||||||
|
|
||||||
|
Setup:
|
||||||
|
|
||||||
|
* Minor improvements to the setup scripts.
|
||||||
|
|
||||||
|
v0.53a (May 8, 2021)
|
||||||
|
--------------------
|
||||||
|
|
||||||
|
The download URL for Z-Push has been revised becaue the old URL stopped working.
|
||||||
|
|
||||||
|
v0.53 (April 12, 2021)
|
||||||
|
----------------------
|
||||||
|
|
||||||
|
Software updates:
|
||||||
|
|
||||||
|
* Upgraded Roundcube to version 1.4.11 addressing a security issue, and its desktop notifications plugin.
|
||||||
|
* Upgraded Z-Push (for Exchange/ActiveSync) to version 2.6.2.
|
||||||
|
|
||||||
|
Control panel:
|
||||||
|
|
||||||
|
* Backblaze B2 is now a supported backup protocol.
|
||||||
|
* Fixed an issue in the daily mail reports.
|
||||||
|
* Sort the Custom DNS by zone and qname, and add an option to go back to the old sort order (creation order).
|
||||||
|
|
||||||
|
Mail:
|
||||||
|
|
||||||
|
* Enable sending DMARC failure reports to senders that request them.
|
||||||
|
|
||||||
|
Setup:
|
||||||
|
|
||||||
|
* Fixed error when upgrading from Nextcloud 13.
|
||||||
|
|
||||||
|
v0.52 (January 31, 2021)
|
||||||
|
------------------------
|
||||||
|
|
||||||
|
Software updates:
|
||||||
|
|
||||||
|
* Upgraded Roundcube to version 1.4.10.
|
||||||
|
* Upgraded Z-Push to 2.6.1.
|
||||||
|
|
||||||
|
Mail:
|
||||||
|
|
||||||
|
* Incoming emails with SPF/DKIM/DMARC failures now get a higher spam score, and these messages are more likely to appear in the junk folder, since they are often spam/phishing.
|
||||||
|
* Fixed the MTA-STS policy file's line endings.
|
||||||
|
|
||||||
|
Control panel:
|
||||||
|
|
||||||
|
* A new Download button in the control panel's External DNS page can be used to download the required DNS records in zonefile format.
|
||||||
|
* Fixed the problem when the control panel would report DNS entries as Not Set by increasing a bind query limit.
|
||||||
|
* Fixed a control panel startup bug on some systems.
|
||||||
|
* Improved an error message on a DNS lookup timeout.
|
||||||
|
* A typo was fixed.
|
||||||
|
|
||||||
|
DNS:
|
||||||
|
|
||||||
|
* The TTL for NS records has been increased to 1 day to comply with some registrar requirements.
|
||||||
|
|
||||||
|
System:
|
||||||
|
|
||||||
|
* Nextcloud's photos, dashboard, and activity apps are disabled since we only support contacts and calendar.
|
||||||
|
|
||||||
|
v0.51 (November 14, 2020)
|
||||||
|
-------------------------
|
||||||
|
|
||||||
|
Software updates:
|
||||||
|
|
||||||
|
* Upgraded Nextcloud from 17.0.6 to 20.0.1 (with Contacts from 3.3.0 to 3.4.1 and Calendar from 2.0.3 to 2.1.2)
|
||||||
|
* Upgraded Roundcube to version 1.4.9.
|
||||||
|
|
||||||
|
Mail:
|
||||||
|
|
||||||
|
* The MTA-STA max_age value was increased to the normal one week.
|
||||||
|
|
||||||
|
Control panel:
|
||||||
|
|
||||||
|
* Two-factor authentication can now be enabled for logins to the control panel. However, keep in mind that many online services (including domain name registrars, cloud server providers, and TLS certificate providers) may allow an attacker to take over your account or issue a fraudulent TLS certificate with only access to your email address, and this new two-factor authentication does not protect access to your inbox. It therefore remains very important that user accounts with administrative email addresses have strong passwords.
|
||||||
|
* TLS certificate expiry dates are now shown in ISO8601 format for clarity.
|
||||||
|
|
||||||
|
v0.50 (September 25, 2020)
|
||||||
|
--------------------------
|
||||||
|
|
||||||
|
Setup:
|
||||||
|
|
||||||
|
* When upgrading from versions before v0.40, setup will now warn that ownCloud/Nextcloud data cannot be migrated rather than failing the installation.
|
||||||
|
|
||||||
|
Mail:
|
||||||
|
|
||||||
|
* An MTA-STS policy for incoming mail is now published (in DNS and over HTTPS) when the primary hostname and email address domain both have a signed TLS certificate installed, allowing senders to know that an encrypted connection should be enforced.
|
||||||
|
* The per-IP connection limit to the IMAP server has been doubled to allow more devices to connect at once, especially with multiple users behind a NAT.
|
||||||
|
|
||||||
|
DNS:
|
||||||
|
|
||||||
|
* autoconfig and autodiscover subdomains and CalDAV/CardDAV SRV records are no longer generated for domains that don't have user accounts since they are unnecessary.
|
||||||
|
* IPv6 addresses can now be specified for secondary DNS nameservers in the control panel.
|
||||||
|
|
||||||
|
TLS:
|
||||||
|
|
||||||
|
* TLS certificates are now provisioned in groups by parent domain to limit easy domain enumeration and make provisioning more resilient to errors for particular domains.
|
||||||
|
|
||||||
|
Control panel:
|
||||||
|
|
||||||
|
* The control panel API is now fully documented at https://mailinabox.email/api-docs.html.
|
||||||
|
* User passwords can now have spaces.
|
||||||
|
* Status checks for automatic subdomains have been moved into the section for the parent domain.
|
||||||
|
* Typo fixed.
|
||||||
|
|
||||||
|
Web:
|
||||||
|
|
||||||
|
* The default web page served on fresh installations now adds the `noindex` meta tag.
|
||||||
|
* The HSTS header is revised to also be sent on non-success responses.
|
||||||
|
|
||||||
|
v0.48 (August 26, 2020)
|
||||||
|
-----------------------
|
||||||
|
|
||||||
|
Security fixes:
|
||||||
|
|
||||||
|
* Roundcube is updated to version 1.4.8 fixing additional cross-site scripting (XSS) vulnerabilities.
|
||||||
|
|
||||||
|
v0.47 (July 29, 2020)
|
||||||
|
---------------------
|
||||||
|
|
||||||
|
Security fixes:
|
||||||
|
|
||||||
|
* Roundcube is updated to version 1.4.7 fixing a cross-site scripting (XSS) vulnerability with HTML messages with malicious svg/namespace (CVE-2020-15562) (https://roundcube.net/news/2020/07/05/security-updates-1.4.7-1.3.14-and-1.2.11).
|
||||||
|
* SSH connections are now rate-limited at the firewall level (in addition to fail2ban).
|
||||||
|
|
||||||
|
v0.46 (June 11, 2020)
|
||||||
|
---------------------
|
||||||
|
|
||||||
|
Security fixes:
|
||||||
|
|
||||||
|
* Roundcube is updated to version 1.4.6 (https://roundcube.net/news/2020/06/02/security-updates-1.4.5-and-1.3.12).
|
||||||
|
|
||||||
|
v0.45 (May 16, 2020)
|
||||||
|
--------------------
|
||||||
|
|
||||||
|
Security fixes:
|
||||||
|
|
||||||
|
* Fix missing brute force login protection for Roundcube logins.
|
||||||
|
|
||||||
|
Software updates:
|
||||||
|
|
||||||
|
* Upgraded Roundcube from 1.4.2 to 1.4.4.
|
||||||
|
* Upgraded Nextcloud from 17.0.2 to 17.0.6 (with Contacts from 3.1.6 to 3.3.0 and Calendar from 1.7.1 to v2.0.3)
|
||||||
|
* Upgraded Z-Push to 2.5.2.
|
||||||
|
|
||||||
|
System:
|
||||||
|
|
||||||
|
* Nightly backups now occur on a random minute in the 3am hour (in the system time zone). The minute is chosen during Mail-in-a-Box installation/upgrade and remains the same until the next upgrade.
|
||||||
|
* Fix for mail log statistics report on leap days.
|
||||||
|
* Fix Mozilla autoconfig useGlobalPreferredServer setting.
|
||||||
|
|
||||||
|
Web:
|
||||||
|
|
||||||
|
* Add a new hidden feature to set nginx alias in www/custom.yaml.
|
||||||
|
|
||||||
|
Setup:
|
||||||
|
|
||||||
|
* Improved error handling.
|
||||||
|
|
||||||
|
v0.44 (February 15, 2020)
|
||||||
|
-------------------------
|
||||||
|
|
||||||
|
System:
|
||||||
|
|
||||||
|
* TLS settings have been upgraded following Mozilla's recommendations for servers. TLS1.2 and 1.3 are now the only supported protocols for web, IMAP, and SMTP (submission).
|
||||||
|
* Fixed an issue starting services when Mail-in-a-Box isn't on the root filesystem.
|
||||||
|
* Changed some performance options affecting Roundcube and Nextcloud.
|
||||||
|
|
||||||
|
Software updates:
|
||||||
|
|
||||||
|
* Upgraded Nextcloud from 15.0.8 to 17.0.2 (with Contacts from 3.1.1 to 3.1.6 and Calendar from 1.6.5 to 1.7.1)
|
||||||
|
* Upgraded Z-Push to 2.5.1.
|
||||||
|
* Upgraded Roundcube from 1.3.10 to 1.4.2 and changed the default skin (theme) to Elastic.
|
||||||
|
|
||||||
|
Control panel:
|
||||||
|
|
||||||
|
* The Custom DNS list of records is now sorted.
|
||||||
|
* The emails that report TLS provisioning results now has a less scary subject line.
|
||||||
|
|
||||||
|
Mail:
|
||||||
|
|
||||||
|
* Fetching of updated whitelist for greylisting was fetching each day instead of every month.
|
||||||
|
* OpenDKIM signing has been changed to 'relaxed' mode so that some old mail lists that forward mail can do so.
|
||||||
|
|
||||||
|
DNS:
|
||||||
|
|
||||||
|
* Automatic autoconfig.* subdomains can now be suppressed with custom DNS records.
|
||||||
|
* DNS zone transfer now works with IPv6 addresses.
|
||||||
|
|
||||||
|
Setup:
|
||||||
|
|
||||||
|
* An Ubuntu package source was missing on systems where it defaults off.
|
||||||
|
|
||||||
|
v0.43 (September 1, 2019)
|
||||||
|
-------------------------
|
||||||
|
|
||||||
|
Security fixes:
|
||||||
|
|
||||||
|
* A security issue was discovered in rsync backups. If you have enabled rsync backups, the file `id_rsa_miab` may have been copied to your backup destination. This file can be used to access your backup destination. If the file was copied to your backup destination, we recommend that you delete the file on your backup destination, delete `/root/.ssh/id_rsa_miab` on your Mail-in-a-Box, then re-run Mail-in-a-Box setup, and re-configure your SSH public key at your backup destination according to the instructions in the Mail-in-a-Box control panel.
|
||||||
|
* Brute force attack prevention was missing for the managesieve service.
|
||||||
|
|
||||||
|
Setup:
|
||||||
|
|
||||||
|
* Nextcloud was not upgraded properly after restoring Mail-in-a-Box from a backup from v0.40 or earlier.
|
||||||
|
|
||||||
|
Mail:
|
||||||
|
|
||||||
|
* Upgraded Roundcube to 1.3.10.
|
||||||
|
* Fetch an updated whitelist for greylisting on a monthly basis to reduce the number of delayed incoming emails.
|
||||||
|
|
||||||
|
Control panel:
|
||||||
|
|
||||||
|
* When using secondary DNS, it is now possible to specify a subnet range with the `xfr:` option.
|
||||||
|
* Fixed an issue when the secondary DNS option is used and the secondary DNS hostname resolves to multiple IP addresses.
|
||||||
|
* Fix a bug in how a backup configuration error is shown.
|
||||||
|
|
||||||
v0.42b (August 3, 2019)
|
v0.42b (August 3, 2019)
|
||||||
-----------------------
|
-----------------------
|
||||||
|
|
||||||
|
|||||||
@@ -20,9 +20,9 @@ _If you're seeing an error message about your *IP address being listed in the Sp
|
|||||||
|
|
||||||
### Modifying your `hosts` file
|
### Modifying your `hosts` file
|
||||||
|
|
||||||
After a while, Mail-in-a-Box will be available at `192.168.50.4` (unless you changed that in your `Vagrantfile`). To be able to use the web-based bits, we recommend to add a hostname to your `hosts` file:
|
After a while, Mail-in-a-Box will be available at `192.168.56.4` (unless you changed that in your `Vagrantfile`). To be able to use the web-based bits, we recommend to add a hostname to your `hosts` file:
|
||||||
|
|
||||||
$ echo "192.168.50.4 mailinabox.lan" | sudo tee -a /etc/hosts
|
$ echo "192.168.56.4 mailinabox.lan" | sudo tee -a /etc/hosts
|
||||||
|
|
||||||
You should now be able to navigate to https://mailinabox.lan/admin using your browser. There should be an initial admin user with the name `me@mailinabox.lan` and the password `12345678`.
|
You should now be able to navigate to https://mailinabox.lan/admin using your browser. There should be an initial admin user with the name `me@mailinabox.lan` and the password `12345678`.
|
||||||
|
|
||||||
|
|||||||
62
README.md
62
README.md
@@ -13,33 +13,42 @@ Our goals are to:
|
|||||||
|
|
||||||
* Make deploying a good mail server easy.
|
* Make deploying a good mail server easy.
|
||||||
* Promote [decentralization](http://redecentralize.org/), innovation, and privacy on the web.
|
* Promote [decentralization](http://redecentralize.org/), innovation, and privacy on the web.
|
||||||
* Have automated, auditable, and [idempotent](https://sharknet.us/2014/02/01/automated-configuration-management-challenges-with-idempotency/) configuration.
|
* Have automated, auditable, and [idempotent](https://web.archive.org/web/20190518072631/https://sharknet.us/2014/02/01/automated-configuration-management-challenges-with-idempotency/) configuration.
|
||||||
* **Not** make a totally unhackable, NSA-proof server.
|
* **Not** make a totally unhackable, NSA-proof server.
|
||||||
* **Not** make something customizable by power users.
|
* **Not** make something customizable by power users.
|
||||||
|
|
||||||
Additionally, this project has a [Code of Conduct](CODE_OF_CONDUCT.md), which supersedes the goals above. Please review it when joining our community.
|
Additionally, this project has a [Code of Conduct](CODE_OF_CONDUCT.md), which supersedes the goals above. Please review it when joining our community.
|
||||||
|
|
||||||
The Box
|
|
||||||
-------
|
In The Box
|
||||||
|
----------
|
||||||
|
|
||||||
Mail-in-a-Box turns a fresh Ubuntu 18.04 LTS 64-bit machine into a working mail server by installing and configuring various components.
|
Mail-in-a-Box turns a fresh Ubuntu 18.04 LTS 64-bit machine into a working mail server by installing and configuring various components.
|
||||||
|
|
||||||
It is a one-click email appliance. There are no user-configurable setup options. It "just works".
|
It is a one-click email appliance. There are no user-configurable setup options. It "just works."
|
||||||
|
|
||||||
The components installed are:
|
The components installed are:
|
||||||
|
|
||||||
* SMTP ([postfix](http://www.postfix.org/)), IMAP ([dovecot](http://dovecot.org/)), CardDAV/CalDAV ([Nextcloud](https://nextcloud.com/)), Exchange ActiveSync ([z-push](http://z-push.org/))
|
* SMTP ([postfix](http://www.postfix.org/)), IMAP ([Dovecot](http://dovecot.org/)), CardDAV/CalDAV ([Nextcloud](https://nextcloud.com/)), and Exchange ActiveSync ([z-push](http://z-push.org/)) servers
|
||||||
* Webmail ([Roundcube](http://roundcube.net/)), static website hosting ([nginx](http://nginx.org/))
|
* Webmail ([Roundcube](http://roundcube.net/)), mail filter rules (thanks to Roundcube and Dovecot), and email client autoconfig settings (served by [nginx](http://nginx.org/))
|
||||||
* Spam filtering ([spamassassin](https://spamassassin.apache.org/)), greylisting ([postgrey](http://postgrey.schweikert.ch/))
|
* Spam filtering ([spamassassin](https://spamassassin.apache.org/)) and greylisting ([postgrey](http://postgrey.schweikert.ch/))
|
||||||
* DNS ([nsd4](https://www.nlnetlabs.nl/projects/nsd/)) with [SPF](https://en.wikipedia.org/wiki/Sender_Policy_Framework), DKIM ([OpenDKIM](http://www.opendkim.org/)), [DMARC](https://en.wikipedia.org/wiki/DMARC), [DNSSEC](https://en.wikipedia.org/wiki/DNSSEC), [DANE TLSA](https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities), and [SSHFP](https://tools.ietf.org/html/rfc4255) records automatically set
|
* DNS ([nsd4](https://www.nlnetlabs.nl/projects/nsd/)) with [SPF](https://en.wikipedia.org/wiki/Sender_Policy_Framework), DKIM ([OpenDKIM](http://www.opendkim.org/)), [DMARC](https://en.wikipedia.org/wiki/DMARC), [DNSSEC](https://en.wikipedia.org/wiki/DNSSEC), [DANE TLSA](https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities), [MTA-STS](https://tools.ietf.org/html/rfc8461), and [SSHFP](https://tools.ietf.org/html/rfc4255) policy records automatically set
|
||||||
* Backups ([duplicity](http://duplicity.nongnu.org/)), firewall ([ufw](https://launchpad.net/ufw)), intrusion protection ([fail2ban](http://www.fail2ban.org/wiki/index.php/Main_Page)), system monitoring ([munin](http://munin-monitoring.org/))
|
* TLS certificates are automatically provisioned using [Let's Encrypt](https://letsencrypt.org/) for protecting https and all of the other services on the box
|
||||||
|
* Backups ([duplicity](http://duplicity.nongnu.org/)), firewall ([ufw](https://launchpad.net/ufw)), intrusion protection ([fail2ban](http://www.fail2ban.org/wiki/index.php/Main_Page)), and basic system monitoring ([munin](http://munin-monitoring.org/))
|
||||||
|
|
||||||
It also includes:
|
It also includes system management tools:
|
||||||
|
|
||||||
* A control panel and API for adding/removing mail users, aliases, custom DNS records, etc. and detailed system monitoring.
|
* Comprehensive health monitoring that checks each day that services are running, ports are open, TLS certificates are valid, and DNS records are correct
|
||||||
|
* A control panel for adding/removing mail users, aliases, custom DNS records, configuring backups, etc.
|
||||||
|
* An API for all of the actions on the control panel
|
||||||
|
|
||||||
|
Internationalized domain names are supported and configured easily (but SMTPUTF8 is not supported, unfortunately).
|
||||||
|
|
||||||
|
It also supports static website hosting since the box is serving HTTPS anyway. (To serve a website for your domains elsewhere, just add a custom DNS "A" record in you Mail-in-a-Box's control panel to point domains to another server.)
|
||||||
|
|
||||||
For more information on how Mail-in-a-Box handles your privacy, see the [security details page](security.md).
|
For more information on how Mail-in-a-Box handles your privacy, see the [security details page](security.md).
|
||||||
|
|
||||||
|
|
||||||
Installation
|
Installation
|
||||||
------------
|
------------
|
||||||
|
|
||||||
@@ -47,40 +56,26 @@ See the [setup guide](https://mailinabox.email/guide.html) for detailed, user-fr
|
|||||||
|
|
||||||
For experts, start with a completely fresh (really, I mean it) Ubuntu 18.04 LTS 64-bit machine. On the machine...
|
For experts, start with a completely fresh (really, I mean it) Ubuntu 18.04 LTS 64-bit machine. On the machine...
|
||||||
|
|
||||||
Clone this repository:
|
Clone this repository and checkout the tag corresponding to the most recent release:
|
||||||
|
|
||||||
$ git clone https://github.com/mail-in-a-box/mailinabox
|
$ git clone https://github.com/mail-in-a-box/mailinabox
|
||||||
$ cd mailinabox
|
$ cd mailinabox
|
||||||
|
$ git checkout v57
|
||||||
_Optional:_ Download Josh's PGP key and then verify that the sources were signed
|
|
||||||
by him:
|
|
||||||
|
|
||||||
$ curl -s https://keybase.io/joshdata/key.asc | gpg --import
|
|
||||||
gpg: key C10BDD81: public key "Joshua Tauberer <jt@occams.info>" imported
|
|
||||||
|
|
||||||
$ git verify-tag v0.42b
|
|
||||||
gpg: Signature made ..... using RSA key ID C10BDD81
|
|
||||||
gpg: Good signature from "Joshua Tauberer <jt@occams.info>"
|
|
||||||
gpg: WARNING: This key is not certified with a trusted signature!
|
|
||||||
gpg: There is no indication that the signature belongs to the owner.
|
|
||||||
Primary key fingerprint: 5F4C 0E73 13CC D744 693B 2AEA B920 41F4 C10B DD81
|
|
||||||
|
|
||||||
You'll get a lot of warnings, but that's OK. Check that the primary key fingerprint matches the
|
|
||||||
fingerprint in the key details at [https://keybase.io/joshdata](https://keybase.io/joshdata)
|
|
||||||
and on his [personal homepage](https://razor.occams.info/). (Of course, if this repository has been compromised you can't trust these instructions.)
|
|
||||||
|
|
||||||
Checkout the tag corresponding to the most recent release:
|
|
||||||
|
|
||||||
$ git checkout v0.42b
|
|
||||||
|
|
||||||
Begin the installation.
|
Begin the installation.
|
||||||
|
|
||||||
$ sudo setup/start.sh
|
$ sudo setup/start.sh
|
||||||
|
|
||||||
|
The installation will install, uninstall, and configure packages to turn the machine into a working, good mail server.
|
||||||
|
|
||||||
For help, DO NOT contact Josh directly --- I don't do tech support by email or tweet (no exceptions).
|
For help, DO NOT contact Josh directly --- I don't do tech support by email or tweet (no exceptions).
|
||||||
|
|
||||||
Post your question on the [discussion forum](https://discourse.mailinabox.email/) instead, where maintainers and Mail-in-a-Box users may be able to help you.
|
Post your question on the [discussion forum](https://discourse.mailinabox.email/) instead, where maintainers and Mail-in-a-Box users may be able to help you.
|
||||||
|
|
||||||
|
Note that while we want everything to "just work," we can't control the rest of the Internet. Other mail services might block or spam-filter email sent from your Mail-in-a-Box.
|
||||||
|
This is a challenge faced by everyone who runs their own mail server, with or without Mail-in-a-Box. See our discussion forum for tips about that.
|
||||||
|
|
||||||
|
|
||||||
Contributing and Development
|
Contributing and Development
|
||||||
----------------------------
|
----------------------------
|
||||||
|
|
||||||
@@ -94,6 +89,7 @@ This project was inspired in part by the ["NSA-proof your email in 2 hours"](htt
|
|||||||
|
|
||||||
Mail-in-a-Box is similar to [iRedMail](http://www.iredmail.org/) and [Modoboa](https://github.com/tonioo/modoboa).
|
Mail-in-a-Box is similar to [iRedMail](http://www.iredmail.org/) and [Modoboa](https://github.com/tonioo/modoboa).
|
||||||
|
|
||||||
|
|
||||||
The History
|
The History
|
||||||
-----------
|
-----------
|
||||||
|
|
||||||
|
|||||||
2
Vagrantfile
vendored
2
Vagrantfile
vendored
@@ -9,7 +9,7 @@ Vagrant.configure("2") do |config|
|
|||||||
# the machine's box will let anyone log into it. So instead we'll put the
|
# the machine's box will let anyone log into it. So instead we'll put the
|
||||||
# machine on a private network.
|
# machine on a private network.
|
||||||
config.vm.hostname = "mailinabox.lan"
|
config.vm.hostname = "mailinabox.lan"
|
||||||
config.vm.network "private_network", ip: "192.168.50.4"
|
config.vm.network "private_network", ip: "192.168.56.4"
|
||||||
|
|
||||||
config.vm.provision :shell, :inline => <<-SH
|
config.vm.provision :shell, :inline => <<-SH
|
||||||
# Set environment variables so that the setup script does
|
# Set environment variables so that the setup script does
|
||||||
|
|||||||
23
api/docs/generate-docs.sh
Executable file
23
api/docs/generate-docs.sh
Executable file
@@ -0,0 +1,23 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
|
||||||
|
# Requirements:
|
||||||
|
# - Node.js
|
||||||
|
# - redoc-cli (`npm install redoc-cli -g`)
|
||||||
|
|
||||||
|
redoc-cli bundle ../mailinabox.yml \
|
||||||
|
-t template.hbs \
|
||||||
|
-o api-docs.html \
|
||||||
|
--templateOptions.metaDescription="Mail-in-a-Box HTTP API" \
|
||||||
|
--title="Mail-in-a-Box HTTP API" \
|
||||||
|
--options.expandSingleSchemaField \
|
||||||
|
--options.hideSingleRequestSampleTab \
|
||||||
|
--options.jsonSampleExpandLevel=10 \
|
||||||
|
--options.hideDownloadButton \
|
||||||
|
--options.theme.logo.maxHeight=180px \
|
||||||
|
--options.theme.logo.maxWidth=180px \
|
||||||
|
--options.theme.colors.primary.main="#C52" \
|
||||||
|
--options.theme.typography.fontSize=16px \
|
||||||
|
--options.theme.typography.fontFamily="Raleway, sans-serif" \
|
||||||
|
--options.theme.typography.headings.fontFamily="Ubuntu, Arial, sans-serif" \
|
||||||
|
--options.theme.typography.code.fontSize=15px \
|
||||||
|
--options.theme.typography.code.fontFamily='"Source Code Pro", monospace'
|
||||||
31
api/docs/template.hbs
Normal file
31
api/docs/template.hbs
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="utf8" />
|
||||||
|
<title>{{title}}</title>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="description" content="{{templateOptions.metaDescription}}" />
|
||||||
|
<link rel="icon" type="image/png" href="https://mailinabox.email/static/logo_small.png">
|
||||||
|
<link rel="apple-touch-icon" type="image/png" href="https://mailinabox.email/static/logo_small.png">
|
||||||
|
<link href="https://fonts.googleapis.com/css?family=Raleway:400,700" rel="stylesheet" />
|
||||||
|
<link href="https://fonts.googleapis.com/css?family=Ubuntu:300" rel="stylesheet" />
|
||||||
|
<link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" />
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
color: #000 !important;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
{{{redocHead}}}
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
{{{redocHTML}}}
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
2732
api/mailinabox.yml
Normal file
2732
api/mailinabox.yml
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
|||||||
# Fail2Ban filter Dovecot authentication and pop3/imap server
|
# Fail2Ban filter Dovecot authentication and pop3/imap/managesieve server
|
||||||
# For Mail-in-a-Box
|
# For Mail-in-a-Box
|
||||||
|
|
||||||
[INCLUDES]
|
[INCLUDES]
|
||||||
@@ -9,7 +9,7 @@ before = common.conf
|
|||||||
|
|
||||||
_daemon = (auth|dovecot(-auth)?|auth-worker)
|
_daemon = (auth|dovecot(-auth)?|auth-worker)
|
||||||
|
|
||||||
failregex = ^%(__prefix_line)s(pop3|imap)-login: (Info: )?(Aborted login|Disconnected)(: Inactivity)? \(((no auth attempts|auth failed, \d+ attempts)( in \d+ secs)?|tried to use (disabled|disallowed) \S+ auth)\):( user=<\S*>,)?( method=\S+,)? rip=<HOST>, lip=(\d{1,3}\.){3}\d{1,3}(, TLS( handshaking)?(: Disconnected)?)?(, session=<\S+>)?\s*$
|
failregex = ^%(__prefix_line)s(pop3|imap|managesieve)-login: (Info: )?(Aborted login|Disconnected)(: Inactivity)? \(((no auth attempts|auth failed, \d+ attempts)( in \d+ secs)?|tried to use (disabled|disallowed) \S+ auth)\):( user=<\S*>,)?( method=\S+,)? rip=<HOST>, lip=(\d{1,3}\.){3}\d{1,3}(, TLS( handshaking)?(: Disconnected)?)?(, session=<\S+>)?\s*$
|
||||||
|
|
||||||
ignoreregex =
|
ignoreregex =
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
# Whitelist our own IP addresses. 127.0.0.1/8 is the default. But our status checks
|
# Whitelist our own IP addresses. 127.0.0.1/8 is the default. But our status checks
|
||||||
# ping services over the public interface so we should whitelist that address of
|
# ping services over the public interface so we should whitelist that address of
|
||||||
# ours too. The string is substituted during installation.
|
# ours too. The string is substituted during installation.
|
||||||
ignoreip = 127.0.0.1/8 PUBLIC_IP
|
ignoreip = 127.0.0.1/8 PUBLIC_IP ::1 PUBLIC_IPV6
|
||||||
|
|
||||||
[dovecot]
|
[dovecot]
|
||||||
enabled = true
|
enabled = true
|
||||||
@@ -38,6 +38,14 @@ logpath = STORAGE_ROOT/owncloud/nextcloud.log
|
|||||||
maxretry = 20
|
maxretry = 20
|
||||||
findtime = 120
|
findtime = 120
|
||||||
|
|
||||||
|
[miab-postfix465]
|
||||||
|
enabled = true
|
||||||
|
port = 465
|
||||||
|
filter = miab-postfix-submission
|
||||||
|
logpath = /var/log/mail.log
|
||||||
|
maxretry = 20
|
||||||
|
findtime = 30
|
||||||
|
|
||||||
[miab-postfix587]
|
[miab-postfix587]
|
||||||
enabled = true
|
enabled = true
|
||||||
port = 587
|
port = 587
|
||||||
@@ -50,7 +58,7 @@ findtime = 30
|
|||||||
enabled = true
|
enabled = true
|
||||||
port = http,https
|
port = http,https
|
||||||
filter = miab-roundcube
|
filter = miab-roundcube
|
||||||
logpath = /var/log/roundcubemail/errors
|
logpath = /var/log/roundcubemail/errors.log
|
||||||
maxretry = 20
|
maxretry = 20
|
||||||
findtime = 30
|
findtime = 30
|
||||||
|
|
||||||
|
|||||||
@@ -53,7 +53,7 @@
|
|||||||
<key>OutgoingMailServerHostName</key>
|
<key>OutgoingMailServerHostName</key>
|
||||||
<string>PRIMARY_HOSTNAME</string>
|
<string>PRIMARY_HOSTNAME</string>
|
||||||
<key>OutgoingMailServerPortNumber</key>
|
<key>OutgoingMailServerPortNumber</key>
|
||||||
<integer>587</integer>
|
<integer>465</integer>
|
||||||
<key>OutgoingMailServerUseSSL</key>
|
<key>OutgoingMailServerUseSSL</key>
|
||||||
<true/>
|
<true/>
|
||||||
<key>OutgoingPasswordSameAsIncomingPassword</key>
|
<key>OutgoingPasswordSameAsIncomingPassword</key>
|
||||||
|
|||||||
@@ -16,12 +16,12 @@
|
|||||||
|
|
||||||
<outgoingServer type="smtp">
|
<outgoingServer type="smtp">
|
||||||
<hostname>PRIMARY_HOSTNAME</hostname>
|
<hostname>PRIMARY_HOSTNAME</hostname>
|
||||||
<port>587</port>
|
<port>465</port>
|
||||||
<socketType>STARTTLS</socketType>
|
<socketType>SSL</socketType>
|
||||||
<username>%EMAILADDRESS%</username>
|
<username>%EMAILADDRESS%</username>
|
||||||
<authentication>password-cleartext</authentication>
|
<authentication>password-cleartext</authentication>
|
||||||
<addThisServer>true</addThisServer>
|
<addThisServer>true</addThisServer>
|
||||||
<useGlobalPreferredServer>true</useGlobalPreferredServer>
|
<useGlobalPreferredServer>false</useGlobalPreferredServer>
|
||||||
</outgoingServer>
|
</outgoingServer>
|
||||||
|
|
||||||
<documentation url="https://PRIMARY_HOSTNAME/">
|
<documentation url="https://PRIMARY_HOSTNAME/">
|
||||||
|
|||||||
4
conf/mta-sts.txt
Normal file
4
conf/mta-sts.txt
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
version: STSv1
|
||||||
|
mode: MODE
|
||||||
|
mx: PRIMARY_HOSTNAME
|
||||||
|
max_age: 604800
|
||||||
@@ -21,6 +21,9 @@
|
|||||||
location = /mail/config-v1.1.xml {
|
location = /mail/config-v1.1.xml {
|
||||||
alias /var/lib/mailinabox/mozilla-autoconfig.xml;
|
alias /var/lib/mailinabox/mozilla-autoconfig.xml;
|
||||||
}
|
}
|
||||||
|
location = /.well-known/mta-sts.txt {
|
||||||
|
alias /var/lib/mailinabox/mta-sts.txt;
|
||||||
|
}
|
||||||
|
|
||||||
# Roundcube Webmail configuration.
|
# Roundcube Webmail configuration.
|
||||||
rewrite ^/mail$ /mail/ redirect;
|
rewrite ^/mail$ /mail/ redirect;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# We track the Mozilla "intermediate" compatibility TLS recommendations.
|
# We track the Mozilla "intermediate" compatibility TLS recommendations.
|
||||||
# Note that these settings are repeated in the SMTP and IMAP configuration.
|
# Note that these settings are repeated in the SMTP and IMAP configuration.
|
||||||
# ssl_protocols has moved to nginx.conf in bionic, check there for enabled protocols.
|
# ssl_protocols has moved to nginx.conf in bionic, check there for enabled protocols.
|
||||||
ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
|
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
|
||||||
ssl_dhparam STORAGE_ROOT/ssl/dh2048.pem;
|
ssl_dhparam STORAGE_ROOT/ssl/dh2048.pem;
|
||||||
|
|
||||||
# as recommended by http://nginx.org/en/docs/http/configuring_https_servers.html
|
# as recommended by http://nginx.org/en/docs/http/configuring_https_servers.html
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<title>this is a mail-in-a-box</title>
|
<title>this is a mail-in-a-box</title>
|
||||||
|
<meta name="robots" content="noindex">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>this is a mail-in-a-box</h1>
|
<h1>this is a mail-in-a-box</h1>
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ define('IMAP_FROM_LDAP_FULLNAME', '#givenname #sn');
|
|||||||
define('IMAP_SMTP_METHOD', 'sendmail');
|
define('IMAP_SMTP_METHOD', 'sendmail');
|
||||||
|
|
||||||
global $imap_smtp_params;
|
global $imap_smtp_params;
|
||||||
$imap_smtp_params = array('host' => 'ssl://127.0.0.1', 'port' => 587, 'auth' => true, 'username' => 'imap_username', 'password' => 'imap_password');
|
$imap_smtp_params = array('host' => 'ssl://127.0.0.1', 'port' => 465, 'auth' => true, 'username' => 'imap_username', 'password' => 'imap_password');
|
||||||
|
|
||||||
define('MAIL_MIMEPART_CRLF', "\r\n");
|
define('MAIL_MIMEPART_CRLF', "\r\n");
|
||||||
define('IMAP_MEETING_USE_CALDAV', true);
|
define('IMAP_MEETING_USE_CALDAV', true);
|
||||||
|
|||||||
@@ -1,32 +1,27 @@
|
|||||||
import base64, os, os.path, hmac
|
import base64, os, os.path, hmac, json, secrets
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
from flask import make_response
|
from expiringdict import ExpiringDict
|
||||||
|
|
||||||
import utils
|
import utils
|
||||||
from mailconfig import get_mail_password, get_mail_user_privileges
|
from mailconfig import get_mail_password, get_mail_user_privileges
|
||||||
|
from mfa import get_hash_mfa_state, validate_auth_mfa
|
||||||
|
|
||||||
DEFAULT_KEY_PATH = '/var/lib/mailinabox/api.key'
|
DEFAULT_KEY_PATH = '/var/lib/mailinabox/api.key'
|
||||||
DEFAULT_AUTH_REALM = 'Mail-in-a-Box Management Server'
|
DEFAULT_AUTH_REALM = 'Mail-in-a-Box Management Server'
|
||||||
|
|
||||||
class KeyAuthService:
|
class AuthService:
|
||||||
"""Generate an API key for authenticating clients
|
|
||||||
|
|
||||||
Clients must read the key from the key file and send the key with all HTTP
|
|
||||||
requests. The key is passed as the username field in the standard HTTP
|
|
||||||
Basic Auth header.
|
|
||||||
"""
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.auth_realm = DEFAULT_AUTH_REALM
|
self.auth_realm = DEFAULT_AUTH_REALM
|
||||||
self.key = self._generate_key()
|
|
||||||
self.key_path = DEFAULT_KEY_PATH
|
self.key_path = DEFAULT_KEY_PATH
|
||||||
|
self.max_session_duration = timedelta(days=2)
|
||||||
|
|
||||||
def write_key(self):
|
self.init_system_api_key()
|
||||||
"""Write key to file so authorized clients can get the key
|
self.sessions = ExpiringDict(max_len=64, max_age_seconds=self.max_session_duration.total_seconds())
|
||||||
|
|
||||||
|
def init_system_api_key(self):
|
||||||
|
"""Write an API key to a local file so local processes can use the API"""
|
||||||
|
|
||||||
The key file is created with mode 0640 so that additional users can be
|
|
||||||
authorized to access the API by granting group/ACL read permissions on
|
|
||||||
the key file.
|
|
||||||
"""
|
|
||||||
def create_file_with_mode(path, mode):
|
def create_file_with_mode(path, mode):
|
||||||
# Based on answer by A-B-B: http://stackoverflow.com/a/15015748
|
# Based on answer by A-B-B: http://stackoverflow.com/a/15015748
|
||||||
old_umask = os.umask(0)
|
old_umask = os.umask(0)
|
||||||
@@ -35,71 +30,92 @@ class KeyAuthService:
|
|||||||
finally:
|
finally:
|
||||||
os.umask(old_umask)
|
os.umask(old_umask)
|
||||||
|
|
||||||
|
self.key = secrets.token_hex(32)
|
||||||
|
|
||||||
os.makedirs(os.path.dirname(self.key_path), exist_ok=True)
|
os.makedirs(os.path.dirname(self.key_path), exist_ok=True)
|
||||||
|
|
||||||
with create_file_with_mode(self.key_path, 0o640) as key_file:
|
with create_file_with_mode(self.key_path, 0o640) as key_file:
|
||||||
key_file.write(self.key + '\n')
|
key_file.write(self.key + '\n')
|
||||||
|
|
||||||
def authenticate(self, request, env):
|
def authenticate(self, request, env, login_only=False, logout=False):
|
||||||
"""Test if the client key passed in HTTP Authorization header matches the service key
|
"""Test if the HTTP Authorization header's username matches the system key, a session key,
|
||||||
or if the or username/password passed in the header matches an administrator user.
|
or if the username/password passed in the header matches a local user.
|
||||||
Returns a tuple of the user's email address and list of user privileges (e.g.
|
Returns a tuple of the user's email address and list of user privileges (e.g.
|
||||||
('my@email', []) or ('my@email', ['admin']); raises a ValueError on login failure.
|
('my@email', []) or ('my@email', ['admin']); raises a ValueError on login failure.
|
||||||
If the user used an API key, the user's email is returned as None."""
|
If the user used the system API key, the user's email is returned as None since
|
||||||
|
this key is not associated with a user."""
|
||||||
|
|
||||||
|
def parse_http_authorization_basic(header):
|
||||||
def decode(s):
|
def decode(s):
|
||||||
return base64.b64decode(s.encode('ascii')).decode('ascii')
|
return base64.b64decode(s.encode('ascii')).decode('ascii')
|
||||||
|
|
||||||
def parse_basic_auth(header):
|
|
||||||
if " " not in header:
|
if " " not in header:
|
||||||
return None, None
|
return None, None
|
||||||
scheme, credentials = header.split(maxsplit=1)
|
scheme, credentials = header.split(maxsplit=1)
|
||||||
if scheme != 'Basic':
|
if scheme != 'Basic':
|
||||||
return None, None
|
return None, None
|
||||||
|
|
||||||
credentials = decode(credentials)
|
credentials = decode(credentials)
|
||||||
if ":" not in credentials:
|
if ":" not in credentials:
|
||||||
return None, None
|
return None, None
|
||||||
username, password = credentials.split(':', maxsplit=1)
|
username, password = credentials.split(':', maxsplit=1)
|
||||||
return username, password
|
return username, password
|
||||||
|
|
||||||
header = request.headers.get('Authorization')
|
username, password = parse_http_authorization_basic(request.headers.get('Authorization', ''))
|
||||||
if not header:
|
|
||||||
raise ValueError("No authorization header provided.")
|
|
||||||
|
|
||||||
username, password = parse_basic_auth(header)
|
|
||||||
|
|
||||||
if username in (None, ""):
|
if username in (None, ""):
|
||||||
raise ValueError("Authorization header invalid.")
|
raise ValueError("Authorization header invalid.")
|
||||||
elif username == self.key:
|
|
||||||
# The user passed the API key which grants administrative privs.
|
if username.strip() == "" and password.strip() == "":
|
||||||
|
raise ValueError("No email address, password, session key, or API key provided.")
|
||||||
|
|
||||||
|
# If user passed the system API key, grant administrative privs. This key
|
||||||
|
# is not associated with a user.
|
||||||
|
if username == self.key and not login_only:
|
||||||
return (None, ["admin"])
|
return (None, ["admin"])
|
||||||
|
|
||||||
|
# If the password corresponds with a session token for the user, grant access for that user.
|
||||||
|
if self.get_session(username, password, "login", env) and not login_only:
|
||||||
|
sessionid = password
|
||||||
|
session = self.sessions[sessionid]
|
||||||
|
if logout:
|
||||||
|
# Clear the session.
|
||||||
|
del self.sessions[sessionid]
|
||||||
else:
|
else:
|
||||||
# The user is trying to log in with a username and user-specific
|
# Re-up the session so that it does not expire.
|
||||||
# API key or password. Raises or returns privs.
|
self.sessions[sessionid] = session
|
||||||
return (username, self.get_user_credentials(username, password, env))
|
|
||||||
|
|
||||||
def get_user_credentials(self, email, pw, env):
|
# If no password was given, but a username was given, we're missing some information.
|
||||||
# Validate a user's credentials. On success returns a list of
|
elif password.strip() == "":
|
||||||
# privileges (e.g. [] or ['admin']). On failure raises a ValueError
|
raise ValueError("Enter a password.")
|
||||||
# with a login error message.
|
|
||||||
|
|
||||||
# Sanity check.
|
|
||||||
if email == "" or pw == "":
|
|
||||||
raise ValueError("Enter an email address and password.")
|
|
||||||
|
|
||||||
# The password might be a user-specific API key. create_user_key raises
|
|
||||||
# a ValueError if the user does not exist.
|
|
||||||
if hmac.compare_digest(self.create_user_key(email, env), pw):
|
|
||||||
# OK.
|
|
||||||
pass
|
|
||||||
else:
|
else:
|
||||||
# Get the hashed password of the user. Raise a ValueError if the
|
# The user is trying to log in with a username and a password
|
||||||
# email address does not correspond to a user.
|
# (and possibly a MFA token). On failure, an exception is raised.
|
||||||
pw_hash = get_mail_password(email, env)
|
self.check_user_auth(username, password, request, env)
|
||||||
|
|
||||||
|
# Get privileges for authorization. This call should never fail because by this
|
||||||
|
# point we know the email address is a valid user --- unless the user has been
|
||||||
|
# deleted after the session was granted. On error the call will return a tuple
|
||||||
|
# of an error message and an HTTP status code.
|
||||||
|
privs = get_mail_user_privileges(username, env)
|
||||||
|
if isinstance(privs, tuple): raise ValueError(privs[0])
|
||||||
|
|
||||||
|
# Return the authorization information.
|
||||||
|
return (username, privs)
|
||||||
|
|
||||||
|
def check_user_auth(self, email, pw, request, env):
|
||||||
|
# Validate a user's login email address and password. If MFA is enabled,
|
||||||
|
# check the MFA token in the X-Auth-Token header.
|
||||||
|
#
|
||||||
|
# On login failure, raises a ValueError with a login error message. On
|
||||||
|
# success, nothing is returned.
|
||||||
|
|
||||||
# Authenticate.
|
# Authenticate.
|
||||||
try:
|
try:
|
||||||
|
# Get the hashed password of the user. Raise a ValueError if the
|
||||||
|
# email address does not correspond to a user. But wrap it in the
|
||||||
|
# same exception as if a password fails so we don't easily reveal
|
||||||
|
# if an email address is valid.
|
||||||
|
pw_hash = get_mail_password(email, env)
|
||||||
|
|
||||||
# Use 'doveadm pw' to check credentials. doveadm will return
|
# Use 'doveadm pw' to check credentials. doveadm will return
|
||||||
# a non-zero exit status if the credentials are no good,
|
# a non-zero exit status if the credentials are no good,
|
||||||
# and check_call will raise an exception in that case.
|
# and check_call will raise an exception in that case.
|
||||||
@@ -110,29 +126,41 @@ class KeyAuthService:
|
|||||||
])
|
])
|
||||||
except:
|
except:
|
||||||
# Login failed.
|
# Login failed.
|
||||||
raise ValueError("Invalid password.")
|
raise ValueError("Incorrect email address or password.")
|
||||||
|
|
||||||
# Get privileges for authorization. This call should never fail because by this
|
# If MFA is enabled, check that MFA passes.
|
||||||
# point we know the email address is a valid user. But on error the call will
|
status, hints = validate_auth_mfa(email, request, env)
|
||||||
# return a tuple of an error message and an HTTP status code.
|
if not status:
|
||||||
privs = get_mail_user_privileges(email, env)
|
# Login valid. Hints may have more info.
|
||||||
if isinstance(privs, tuple): raise ValueError(privs[0])
|
raise ValueError(",".join(hints))
|
||||||
|
|
||||||
# Return a list of privileges.
|
def create_user_password_state_token(self, email, env):
|
||||||
return privs
|
# Create a token that changes if the user's password or MFA options change
|
||||||
|
# so that sessions become invalid if any of that information changes.
|
||||||
|
msg = get_mail_password(email, env).encode("utf8")
|
||||||
|
|
||||||
def create_user_key(self, email, env):
|
# Add to the message the current MFA state, which is a list of MFA information.
|
||||||
# Store an HMAC with the client. The hashed message of the HMAC will be the user's
|
# Turn it into a string stably.
|
||||||
# email address & hashed password and the key will be the master API key. The user of
|
msg += b" " + json.dumps(get_hash_mfa_state(email, env), sort_keys=True).encode("utf8")
|
||||||
# course has their own email address and password. We assume they do not have the master
|
|
||||||
# API key (unless they are trusted anyway). The HMAC proves that they authenticated
|
|
||||||
# with us in some other way to get the HMAC. Including the password means that when
|
|
||||||
# a user's password is reset, the HMAC changes and they will correctly need to log
|
|
||||||
# in to the control panel again. This method raises a ValueError if the user does
|
|
||||||
# not exist, due to get_mail_password.
|
|
||||||
msg = b"AUTH:" + email.encode("utf8") + b" " + get_mail_password(email, env).encode("utf8")
|
|
||||||
return hmac.new(self.key.encode('ascii'), msg, digestmod="sha256").hexdigest()
|
|
||||||
|
|
||||||
def _generate_key(self):
|
# Make a HMAC using the system API key as a hash key.
|
||||||
raw_key = os.urandom(32)
|
hash_key = self.key.encode('ascii')
|
||||||
return base64.b64encode(raw_key).decode('ascii')
|
return hmac.new(hash_key, msg, digestmod="sha256").hexdigest()
|
||||||
|
|
||||||
|
def create_session_key(self, username, env, type=None):
|
||||||
|
# Create a new session.
|
||||||
|
token = secrets.token_hex(32)
|
||||||
|
self.sessions[token] = {
|
||||||
|
"email": username,
|
||||||
|
"password_token": self.create_user_password_state_token(username, env),
|
||||||
|
"type": type,
|
||||||
|
}
|
||||||
|
return token
|
||||||
|
|
||||||
|
def get_session(self, user_email, session_key, session_type, env):
|
||||||
|
if session_key not in self.sessions: return None
|
||||||
|
session = self.sessions[session_key]
|
||||||
|
if session_type == "login" and session["email"] != user_email: return None
|
||||||
|
if session["type"] != session_type: return None
|
||||||
|
if session["password_token"] != self.create_user_password_state_token(session["email"], env): return None
|
||||||
|
return session
|
||||||
|
|||||||
@@ -14,11 +14,6 @@ from exclusiveprocess import Lock
|
|||||||
|
|
||||||
from utils import load_environment, shell, wait_for_service, fix_boto
|
from utils import load_environment, shell, wait_for_service, fix_boto
|
||||||
|
|
||||||
rsync_ssh_options = [
|
|
||||||
"--ssh-options='-i /root/.ssh/id_rsa_miab'",
|
|
||||||
"--rsync-options=-e \"/usr/bin/ssh -oStrictHostKeyChecking=no -oBatchMode=yes -p 22 -i /root/.ssh/id_rsa_miab\"",
|
|
||||||
]
|
|
||||||
|
|
||||||
def backup_status(env):
|
def backup_status(env):
|
||||||
# If backups are dissbled, return no status.
|
# If backups are dissbled, return no status.
|
||||||
config = get_backup_config(env)
|
config = get_backup_config(env)
|
||||||
@@ -64,9 +59,9 @@ def backup_status(env):
|
|||||||
"--archive-dir", backup_cache_dir,
|
"--archive-dir", backup_cache_dir,
|
||||||
"--gpg-options", "--cipher-algo=AES256",
|
"--gpg-options", "--cipher-algo=AES256",
|
||||||
"--log-fd", "1",
|
"--log-fd", "1",
|
||||||
config["target"],
|
get_duplicity_target_url(config),
|
||||||
] + rsync_ssh_options,
|
] + get_duplicity_additional_args(env),
|
||||||
get_env(env),
|
get_duplicity_env_vars(env),
|
||||||
trap=True)
|
trap=True)
|
||||||
if code != 0:
|
if code != 0:
|
||||||
# Command failed. This is likely due to an improperly configured remote
|
# Command failed. This is likely due to an improperly configured remote
|
||||||
@@ -195,7 +190,48 @@ def get_passphrase(env):
|
|||||||
|
|
||||||
return passphrase
|
return passphrase
|
||||||
|
|
||||||
def get_env(env):
|
def get_duplicity_target_url(config):
|
||||||
|
target = config["target"]
|
||||||
|
|
||||||
|
if get_target_type(config) == "s3":
|
||||||
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
target = list(urlsplit(target))
|
||||||
|
|
||||||
|
# Duplicity now defaults to boto3 as the backend for S3, but we have
|
||||||
|
# legacy boto installed (boto3 doesn't support Ubuntu 18.04) so
|
||||||
|
# we retarget for classic boto.
|
||||||
|
target[0] = "boto+" + target[0]
|
||||||
|
|
||||||
|
# In addition, although we store the S3 hostname in the target URL,
|
||||||
|
# duplicity no longer accepts it in the target URL. The hostname in
|
||||||
|
# the target URL must be the bucket name. The hostname is passed
|
||||||
|
# via get_duplicity_additional_args. Move the first part of the
|
||||||
|
# path (the bucket name) into the hostname URL component, and leave
|
||||||
|
# the rest for the path.
|
||||||
|
target[1], target[2] = target[2].lstrip('/').split('/', 1)
|
||||||
|
|
||||||
|
target = urlunsplit(target)
|
||||||
|
|
||||||
|
return target
|
||||||
|
|
||||||
|
def get_duplicity_additional_args(env):
|
||||||
|
config = get_backup_config(env)
|
||||||
|
|
||||||
|
if get_target_type(config) == 'rsync':
|
||||||
|
return [
|
||||||
|
"--ssh-options= -i /root/.ssh/id_rsa_miab",
|
||||||
|
"--rsync-options= -e \"/usr/bin/ssh -oStrictHostKeyChecking=no -oBatchMode=yes -p 22 -i /root/.ssh/id_rsa_miab\"",
|
||||||
|
]
|
||||||
|
elif get_target_type(config) == 's3':
|
||||||
|
# See note about hostname in get_duplicity_target_url.
|
||||||
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
target = urlsplit(config["target"])
|
||||||
|
endpoint_url = urlunsplit(("https", target.netloc, '', '', ''))
|
||||||
|
return ["--s3-endpoint-url", endpoint_url]
|
||||||
|
|
||||||
|
return []
|
||||||
|
|
||||||
|
def get_duplicity_env_vars(env):
|
||||||
config = get_backup_config(env)
|
config = get_backup_config(env)
|
||||||
|
|
||||||
env = { "PASSPHRASE" : get_passphrase(env) }
|
env = { "PASSPHRASE" : get_passphrase(env) }
|
||||||
@@ -273,10 +309,10 @@ def perform_backup(full_backup):
|
|||||||
"--volsize", "250",
|
"--volsize", "250",
|
||||||
"--gpg-options", "--cipher-algo=AES256",
|
"--gpg-options", "--cipher-algo=AES256",
|
||||||
env["STORAGE_ROOT"],
|
env["STORAGE_ROOT"],
|
||||||
config["target"],
|
get_duplicity_target_url(config),
|
||||||
"--allow-source-mismatch"
|
"--allow-source-mismatch"
|
||||||
] + rsync_ssh_options,
|
] + get_duplicity_additional_args(env),
|
||||||
get_env(env))
|
get_duplicity_env_vars(env))
|
||||||
finally:
|
finally:
|
||||||
# Start services again.
|
# Start services again.
|
||||||
service_command("dovecot", "start", quit=False)
|
service_command("dovecot", "start", quit=False)
|
||||||
@@ -292,9 +328,9 @@ def perform_backup(full_backup):
|
|||||||
"--verbosity", "error",
|
"--verbosity", "error",
|
||||||
"--archive-dir", backup_cache_dir,
|
"--archive-dir", backup_cache_dir,
|
||||||
"--force",
|
"--force",
|
||||||
config["target"]
|
get_duplicity_target_url(config)
|
||||||
] + rsync_ssh_options,
|
] + get_duplicity_additional_args(env),
|
||||||
get_env(env))
|
get_duplicity_env_vars(env))
|
||||||
|
|
||||||
# From duplicity's manual:
|
# From duplicity's manual:
|
||||||
# "This should only be necessary after a duplicity session fails or is
|
# "This should only be necessary after a duplicity session fails or is
|
||||||
@@ -307,9 +343,9 @@ def perform_backup(full_backup):
|
|||||||
"--verbosity", "error",
|
"--verbosity", "error",
|
||||||
"--archive-dir", backup_cache_dir,
|
"--archive-dir", backup_cache_dir,
|
||||||
"--force",
|
"--force",
|
||||||
config["target"]
|
get_duplicity_target_url(config)
|
||||||
] + rsync_ssh_options,
|
] + get_duplicity_additional_args(env),
|
||||||
get_env(env))
|
get_duplicity_env_vars(env))
|
||||||
|
|
||||||
# Change ownership of backups to the user-data user, so that the after-bcakup
|
# Change ownership of backups to the user-data user, so that the after-bcakup
|
||||||
# script can access them.
|
# script can access them.
|
||||||
@@ -345,9 +381,9 @@ def run_duplicity_verification():
|
|||||||
"--compare-data",
|
"--compare-data",
|
||||||
"--archive-dir", backup_cache_dir,
|
"--archive-dir", backup_cache_dir,
|
||||||
"--exclude", backup_root,
|
"--exclude", backup_root,
|
||||||
config["target"],
|
get_duplicity_target_url(config),
|
||||||
env["STORAGE_ROOT"],
|
env["STORAGE_ROOT"],
|
||||||
] + rsync_ssh_options, get_env(env))
|
] + get_duplicity_additional_args(env), get_duplicity_env_vars(env))
|
||||||
|
|
||||||
def run_duplicity_restore(args):
|
def run_duplicity_restore(args):
|
||||||
env = load_environment()
|
env = load_environment()
|
||||||
@@ -357,9 +393,9 @@ def run_duplicity_restore(args):
|
|||||||
"/usr/bin/duplicity",
|
"/usr/bin/duplicity",
|
||||||
"restore",
|
"restore",
|
||||||
"--archive-dir", backup_cache_dir,
|
"--archive-dir", backup_cache_dir,
|
||||||
config["target"],
|
get_duplicity_target_url(config),
|
||||||
] + rsync_ssh_options + args,
|
] + get_duplicity_additional_args(env) + args,
|
||||||
get_env(env))
|
get_duplicity_env_vars(env))
|
||||||
|
|
||||||
def list_target_files(config):
|
def list_target_files(config):
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
@@ -406,11 +442,11 @@ def list_target_files(config):
|
|||||||
reason = "Provided path {} is invalid.".format(target_path)
|
reason = "Provided path {} is invalid.".format(target_path)
|
||||||
elif 'Network is unreachable' in listing:
|
elif 'Network is unreachable' in listing:
|
||||||
reason = "The IP address {} is unreachable.".format(target.hostname)
|
reason = "The IP address {} is unreachable.".format(target.hostname)
|
||||||
elif 'Could not resolve hostname':
|
elif 'Could not resolve hostname' in listing:
|
||||||
reason = "The hostname {} cannot be resolved.".format(target.hostname)
|
reason = "The hostname {} cannot be resolved.".format(target.hostname)
|
||||||
else:
|
else:
|
||||||
reason = "Unknown error." \
|
reason = "Unknown error." \
|
||||||
"Please check running 'python management/backup.py --verify'" \
|
"Please check running 'management/backup.py --verify'" \
|
||||||
"from mailinabox sources to debug the issue."
|
"from mailinabox sources to debug the issue."
|
||||||
raise ValueError("Connection to rsync host failed: {}".format(reason))
|
raise ValueError("Connection to rsync host failed: {}".format(reason))
|
||||||
|
|
||||||
@@ -456,6 +492,23 @@ def list_target_files(config):
|
|||||||
raise ValueError(e.reason)
|
raise ValueError(e.reason)
|
||||||
|
|
||||||
return [(key.name[len(path):], key.size) for key in bucket.list(prefix=path)]
|
return [(key.name[len(path):], key.size) for key in bucket.list(prefix=path)]
|
||||||
|
elif target.scheme == 'b2':
|
||||||
|
from b2sdk.v1 import InMemoryAccountInfo, B2Api
|
||||||
|
from b2sdk.v1.exception import NonExistentBucket
|
||||||
|
info = InMemoryAccountInfo()
|
||||||
|
b2_api = B2Api(info)
|
||||||
|
|
||||||
|
# Extract information from target
|
||||||
|
b2_application_keyid = target.netloc[:target.netloc.index(':')]
|
||||||
|
b2_application_key = target.netloc[target.netloc.index(':')+1:target.netloc.index('@')]
|
||||||
|
b2_bucket = target.netloc[target.netloc.index('@')+1:]
|
||||||
|
|
||||||
|
try:
|
||||||
|
b2_api.authorize_account("production", b2_application_keyid, b2_application_key)
|
||||||
|
bucket = b2_api.get_bucket_by_name(b2_bucket)
|
||||||
|
except NonExistentBucket as e:
|
||||||
|
raise ValueError("B2 Bucket does not exist. Please double check your information!")
|
||||||
|
return [(key.file_name, key.size) for key, _ in bucket.ls()]
|
||||||
|
|
||||||
else:
|
else:
|
||||||
raise ValueError(config["target"])
|
raise ValueError(config["target"])
|
||||||
|
|||||||
150
management/cli.py
Executable file
150
management/cli.py
Executable file
@@ -0,0 +1,150 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
#
|
||||||
|
# This is a command-line script for calling management APIs
|
||||||
|
# on the Mail-in-a-Box control panel backend. The script
|
||||||
|
# reads /var/lib/mailinabox/api.key for the backend's
|
||||||
|
# root API key. This file is readable only by root, so this
|
||||||
|
# tool can only be used as root.
|
||||||
|
|
||||||
|
import sys, getpass, urllib.request, urllib.error, json, re, csv
|
||||||
|
|
||||||
|
def mgmt(cmd, data=None, is_json=False):
|
||||||
|
# The base URL for the management daemon. (Listens on IPv4 only.)
|
||||||
|
mgmt_uri = 'http://127.0.0.1:10222'
|
||||||
|
|
||||||
|
setup_key_auth(mgmt_uri)
|
||||||
|
|
||||||
|
req = urllib.request.Request(mgmt_uri + cmd, urllib.parse.urlencode(data).encode("utf8") if data else None)
|
||||||
|
try:
|
||||||
|
response = urllib.request.urlopen(req)
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
if e.code == 401:
|
||||||
|
try:
|
||||||
|
print(e.read().decode("utf8"))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
print("The management daemon refused access. The API key file may be out of sync. Try 'service mailinabox restart'.", file=sys.stderr)
|
||||||
|
elif hasattr(e, 'read'):
|
||||||
|
print(e.read().decode('utf8'), file=sys.stderr)
|
||||||
|
else:
|
||||||
|
print(e, file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
resp = response.read().decode('utf8')
|
||||||
|
if is_json: resp = json.loads(resp)
|
||||||
|
return resp
|
||||||
|
|
||||||
|
def read_password():
|
||||||
|
while True:
|
||||||
|
first = getpass.getpass('password: ')
|
||||||
|
if len(first) < 8:
|
||||||
|
print("Passwords must be at least eight characters.")
|
||||||
|
continue
|
||||||
|
second = getpass.getpass(' (again): ')
|
||||||
|
if first != second:
|
||||||
|
print("Passwords not the same. Try again.")
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
return first
|
||||||
|
|
||||||
|
def setup_key_auth(mgmt_uri):
|
||||||
|
key = open('/var/lib/mailinabox/api.key').read().strip()
|
||||||
|
|
||||||
|
auth_handler = urllib.request.HTTPBasicAuthHandler()
|
||||||
|
auth_handler.add_password(
|
||||||
|
realm='Mail-in-a-Box Management Server',
|
||||||
|
uri=mgmt_uri,
|
||||||
|
user=key,
|
||||||
|
passwd='')
|
||||||
|
opener = urllib.request.build_opener(auth_handler)
|
||||||
|
urllib.request.install_opener(opener)
|
||||||
|
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print("""Usage:
|
||||||
|
{cli} user (lists users)
|
||||||
|
{cli} user add user@domain.com [password]
|
||||||
|
{cli} user password user@domain.com [password]
|
||||||
|
{cli} user remove user@domain.com
|
||||||
|
{cli} user make-admin user@domain.com
|
||||||
|
{cli} user remove-admin user@domain.com
|
||||||
|
{cli} user admins (lists admins)
|
||||||
|
{cli} user mfa show user@domain.com (shows MFA devices for user, if any)
|
||||||
|
{cli} user mfa disable user@domain.com [id] (disables MFA for user)
|
||||||
|
{cli} alias (lists aliases)
|
||||||
|
{cli} alias add incoming.name@domain.com sent.to@other.domain.com
|
||||||
|
{cli} alias add incoming.name@domain.com 'sent.to@other.domain.com, multiple.people@other.domain.com'
|
||||||
|
{cli} alias remove incoming.name@domain.com
|
||||||
|
|
||||||
|
Removing a mail user does not delete their mail folders on disk. It only prevents IMAP/SMTP login.
|
||||||
|
""".format(
|
||||||
|
cli="management/cli.py"
|
||||||
|
))
|
||||||
|
|
||||||
|
elif sys.argv[1] == "user" and len(sys.argv) == 2:
|
||||||
|
# Dump a list of users, one per line. Mark admins with an asterisk.
|
||||||
|
users = mgmt("/mail/users?format=json", is_json=True)
|
||||||
|
for domain in users:
|
||||||
|
for user in domain["users"]:
|
||||||
|
if user['status'] == 'inactive': continue
|
||||||
|
print(user['email'], end='')
|
||||||
|
if "admin" in user['privileges']:
|
||||||
|
print("*", end='')
|
||||||
|
print()
|
||||||
|
|
||||||
|
elif sys.argv[1] == "user" and sys.argv[2] in ("add", "password"):
|
||||||
|
if len(sys.argv) < 5:
|
||||||
|
if len(sys.argv) < 4:
|
||||||
|
email = input("email: ")
|
||||||
|
else:
|
||||||
|
email = sys.argv[3]
|
||||||
|
pw = read_password()
|
||||||
|
else:
|
||||||
|
email, pw = sys.argv[3:5]
|
||||||
|
|
||||||
|
if sys.argv[2] == "add":
|
||||||
|
print(mgmt("/mail/users/add", { "email": email, "password": pw }))
|
||||||
|
elif sys.argv[2] == "password":
|
||||||
|
print(mgmt("/mail/users/password", { "email": email, "password": pw }))
|
||||||
|
|
||||||
|
elif sys.argv[1] == "user" and sys.argv[2] == "remove" and len(sys.argv) == 4:
|
||||||
|
print(mgmt("/mail/users/remove", { "email": sys.argv[3] }))
|
||||||
|
|
||||||
|
elif sys.argv[1] == "user" and sys.argv[2] in ("make-admin", "remove-admin") and len(sys.argv) == 4:
|
||||||
|
if sys.argv[2] == "make-admin":
|
||||||
|
action = "add"
|
||||||
|
else:
|
||||||
|
action = "remove"
|
||||||
|
print(mgmt("/mail/users/privileges/" + action, { "email": sys.argv[3], "privilege": "admin" }))
|
||||||
|
|
||||||
|
elif sys.argv[1] == "user" and sys.argv[2] == "admins":
|
||||||
|
# Dump a list of admin users.
|
||||||
|
users = mgmt("/mail/users?format=json", is_json=True)
|
||||||
|
for domain in users:
|
||||||
|
for user in domain["users"]:
|
||||||
|
if "admin" in user['privileges']:
|
||||||
|
print(user['email'])
|
||||||
|
|
||||||
|
elif sys.argv[1] == "user" and len(sys.argv) == 5 and sys.argv[2:4] == ["mfa", "show"]:
|
||||||
|
# Show MFA status for a user.
|
||||||
|
status = mgmt("/mfa/status", { "user": sys.argv[4] }, is_json=True)
|
||||||
|
W = csv.writer(sys.stdout)
|
||||||
|
W.writerow(["id", "type", "label"])
|
||||||
|
for mfa in status["enabled_mfa"]:
|
||||||
|
W.writerow([mfa["id"], mfa["type"], mfa["label"]])
|
||||||
|
|
||||||
|
elif sys.argv[1] == "user" and len(sys.argv) in (5, 6) and sys.argv[2:4] == ["mfa", "disable"]:
|
||||||
|
# Disable MFA (all or a particular device) for a user.
|
||||||
|
print(mgmt("/mfa/disable", { "user": sys.argv[4], "mfa-id": sys.argv[5] if len(sys.argv) == 6 else None }))
|
||||||
|
|
||||||
|
elif sys.argv[1] == "alias" and len(sys.argv) == 2:
|
||||||
|
print(mgmt("/mail/aliases"))
|
||||||
|
|
||||||
|
elif sys.argv[1] == "alias" and sys.argv[2] == "add" and len(sys.argv) == 5:
|
||||||
|
print(mgmt("/mail/aliases/add", { "address": sys.argv[3], "forwards_to": sys.argv[4] }))
|
||||||
|
|
||||||
|
elif sys.argv[1] == "alias" and sys.argv[2] == "remove" and len(sys.argv) == 4:
|
||||||
|
print(mgmt("/mail/aliases/remove", { "address": sys.argv[3] }))
|
||||||
|
|
||||||
|
else:
|
||||||
|
print("Invalid command-line arguments.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
@@ -1,18 +1,31 @@
|
|||||||
|
#!/usr/local/lib/mailinabox/env/bin/python3
|
||||||
|
#
|
||||||
|
# The API can be accessed on the command line, e.g. use `curl` like so:
|
||||||
|
# curl --user $(</var/lib/mailinabox/api.key): http://localhost:10222/mail/users
|
||||||
|
#
|
||||||
|
# During development, you can start the Mail-in-a-Box control panel
|
||||||
|
# by running this script, e.g.:
|
||||||
|
#
|
||||||
|
# service mailinabox stop # stop the system process
|
||||||
|
# DEBUG=1 management/daemon.py
|
||||||
|
# service mailinabox start # when done debugging, start it up again
|
||||||
|
|
||||||
import os, os.path, re, json, time
|
import os, os.path, re, json, time
|
||||||
import subprocess
|
import multiprocessing.pool, subprocess
|
||||||
|
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
|
|
||||||
from flask import Flask, request, render_template, abort, Response, send_from_directory, make_response
|
from flask import Flask, request, render_template, abort, Response, send_from_directory, make_response
|
||||||
|
|
||||||
import auth, utils, multiprocessing.pool
|
import auth, utils
|
||||||
from mailconfig import get_mail_users, get_mail_users_ex, get_admins, add_mail_user, set_mail_password, remove_mail_user
|
from mailconfig import get_mail_users, get_mail_users_ex, get_admins, add_mail_user, set_mail_password, remove_mail_user
|
||||||
from mailconfig import get_mail_user_privileges, add_remove_mail_user_privilege
|
from mailconfig import get_mail_user_privileges, add_remove_mail_user_privilege
|
||||||
from mailconfig import get_mail_aliases, get_mail_aliases_ex, get_mail_domains, add_mail_alias, remove_mail_alias
|
from mailconfig import get_mail_aliases, get_mail_aliases_ex, get_mail_domains, add_mail_alias, remove_mail_alias
|
||||||
|
from mfa import get_public_mfa_state, provision_totp, validate_totp_secret, enable_mfa, disable_mfa
|
||||||
|
|
||||||
env = utils.load_environment()
|
env = utils.load_environment()
|
||||||
|
|
||||||
auth_service = auth.KeyAuthService()
|
auth_service = auth.AuthService()
|
||||||
|
|
||||||
# We may deploy via a symbolic link, which confuses flask's template finding.
|
# We may deploy via a symbolic link, which confuses flask's template finding.
|
||||||
me = __file__
|
me = __file__
|
||||||
@@ -35,23 +48,33 @@ app = Flask(__name__, template_folder=os.path.abspath(os.path.join(os.path.dirna
|
|||||||
def authorized_personnel_only(viewfunc):
|
def authorized_personnel_only(viewfunc):
|
||||||
@wraps(viewfunc)
|
@wraps(viewfunc)
|
||||||
def newview(*args, **kwargs):
|
def newview(*args, **kwargs):
|
||||||
# Authenticate the passed credentials, which is either the API key or a username:password pair.
|
# Authenticate the passed credentials, which is either the API key or a username:password pair
|
||||||
|
# and an optional X-Auth-Token token.
|
||||||
error = None
|
error = None
|
||||||
|
privs = []
|
||||||
|
|
||||||
try:
|
try:
|
||||||
email, privs = auth_service.authenticate(request, env)
|
email, privs = auth_service.authenticate(request, env)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
# Authentication failed.
|
# Write a line in the log recording the failed login, unless no authorization header
|
||||||
privs = []
|
# was given which can happen on an initial request before a 403 response.
|
||||||
error = "Incorrect username or password"
|
if "Authorization" in request.headers:
|
||||||
|
|
||||||
# Write a line in the log recording the failed login
|
|
||||||
log_failed_login(request)
|
log_failed_login(request)
|
||||||
|
|
||||||
|
# Authentication failed.
|
||||||
|
error = str(e)
|
||||||
|
|
||||||
# Authorized to access an API view?
|
# Authorized to access an API view?
|
||||||
if "admin" in privs:
|
if "admin" in privs:
|
||||||
|
# Store the email address of the logged in user so it can be accessed
|
||||||
|
# from the API methods that affect the calling user.
|
||||||
|
request.user_email = email
|
||||||
|
request.user_privs = privs
|
||||||
|
|
||||||
# Call view func.
|
# Call view func.
|
||||||
return viewfunc(*args, **kwargs)
|
return viewfunc(*args, **kwargs)
|
||||||
elif not error:
|
|
||||||
|
if not error:
|
||||||
error = "You are not an administrator."
|
error = "You are not an administrator."
|
||||||
|
|
||||||
# Not authorized. Return a 401 (send auth) and a prompt to authorize by default.
|
# Not authorized. Return a 401 (send auth) and a prompt to authorize by default.
|
||||||
@@ -83,8 +106,8 @@ def authorized_personnel_only(viewfunc):
|
|||||||
def unauthorized(error):
|
def unauthorized(error):
|
||||||
return auth_service.make_unauthorized_response()
|
return auth_service.make_unauthorized_response()
|
||||||
|
|
||||||
def json_response(data):
|
def json_response(data, status=200):
|
||||||
return Response(json.dumps(data, indent=2, sort_keys=True)+'\n', status=200, mimetype='application/json')
|
return Response(json.dumps(data, indent=2, sort_keys=True)+'\n', status=status, mimetype='application/json')
|
||||||
|
|
||||||
###################################
|
###################################
|
||||||
|
|
||||||
@@ -113,33 +136,49 @@ def index():
|
|||||||
csr_country_codes=csr_country_codes,
|
csr_country_codes=csr_country_codes,
|
||||||
)
|
)
|
||||||
|
|
||||||
@app.route('/me')
|
# Create a session key by checking the username/password in the Authorization header.
|
||||||
def me():
|
@app.route('/login', methods=["POST"])
|
||||||
|
def login():
|
||||||
# Is the caller authorized?
|
# Is the caller authorized?
|
||||||
try:
|
try:
|
||||||
email, privs = auth_service.authenticate(request, env)
|
email, privs = auth_service.authenticate(request, env, login_only=True)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
|
if "missing-totp-token" in str(e):
|
||||||
|
return json_response({
|
||||||
|
"status": "missing-totp-token",
|
||||||
|
"reason": str(e),
|
||||||
|
})
|
||||||
|
else:
|
||||||
# Log the failed login
|
# Log the failed login
|
||||||
log_failed_login(request)
|
log_failed_login(request)
|
||||||
|
|
||||||
return json_response({
|
return json_response({
|
||||||
"status": "invalid",
|
"status": "invalid",
|
||||||
"reason": "Incorrect username or password",
|
"reason": str(e),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
# Return a new session for the user.
|
||||||
resp = {
|
resp = {
|
||||||
"status": "ok",
|
"status": "ok",
|
||||||
"email": email,
|
"email": email,
|
||||||
"privileges": privs,
|
"privileges": privs,
|
||||||
|
"api_key": auth_service.create_session_key(email, env, type='login'),
|
||||||
}
|
}
|
||||||
|
|
||||||
# Is authorized as admin? Return an API key for future use.
|
app.logger.info("New login session created for {}".format(email))
|
||||||
if "admin" in privs:
|
|
||||||
resp["api_key"] = auth_service.create_user_key(email, env)
|
|
||||||
|
|
||||||
# Return.
|
# Return.
|
||||||
return json_response(resp)
|
return json_response(resp)
|
||||||
|
|
||||||
|
@app.route('/logout', methods=["POST"])
|
||||||
|
def logout():
|
||||||
|
try:
|
||||||
|
email, _ = auth_service.authenticate(request, env, logout=True)
|
||||||
|
app.logger.info("{} logged out".format(email))
|
||||||
|
except ValueError as e:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
return json_response({ "status": "ok" })
|
||||||
|
|
||||||
# MAIL
|
# MAIL
|
||||||
|
|
||||||
@app.route('/mail/users')
|
@app.route('/mail/users')
|
||||||
@@ -196,7 +235,7 @@ def mail_aliases():
|
|||||||
if request.args.get("format", "") == "json":
|
if request.args.get("format", "") == "json":
|
||||||
return json_response(get_mail_aliases_ex(env))
|
return json_response(get_mail_aliases_ex(env))
|
||||||
else:
|
else:
|
||||||
return "".join(address+"\t"+receivers+"\t"+(senders or "")+"\n" for address, receivers, senders in get_mail_aliases(env))
|
return "".join(address+"\t"+receivers+"\t"+(senders or "")+"\n" for address, receivers, senders, auto in get_mail_aliases(env))
|
||||||
|
|
||||||
@app.route('/mail/aliases/add', methods=['POST'])
|
@app.route('/mail/aliases/add', methods=['POST'])
|
||||||
@authorized_personnel_only
|
@authorized_personnel_only
|
||||||
@@ -254,17 +293,50 @@ def dns_set_secondary_nameserver():
|
|||||||
@app.route('/dns/custom')
|
@app.route('/dns/custom')
|
||||||
@authorized_personnel_only
|
@authorized_personnel_only
|
||||||
def dns_get_records(qname=None, rtype=None):
|
def dns_get_records(qname=None, rtype=None):
|
||||||
from dns_update import get_custom_dns_config
|
# Get the current set of custom DNS records.
|
||||||
return json_response([
|
from dns_update import get_custom_dns_config, get_dns_zones
|
||||||
|
records = get_custom_dns_config(env, only_real_records=True)
|
||||||
|
|
||||||
|
# Filter per the arguments for the more complex GET routes below.
|
||||||
|
records = [r for r in records
|
||||||
|
if (not qname or r[0] == qname)
|
||||||
|
and (not rtype or r[1] == rtype) ]
|
||||||
|
|
||||||
|
# Make a better data structure.
|
||||||
|
records = [
|
||||||
{
|
{
|
||||||
"qname": r[0],
|
"qname": r[0],
|
||||||
"rtype": r[1],
|
"rtype": r[1],
|
||||||
"value": r[2],
|
"value": r[2],
|
||||||
}
|
"sort-order": { },
|
||||||
for r in get_custom_dns_config(env)
|
} for r in records ]
|
||||||
if r[0] != "_secondary_nameserver"
|
|
||||||
and (not qname or r[0] == qname)
|
# To help with grouping by zone in qname sorting, label each record with which zone it is in.
|
||||||
and (not rtype or r[1] == rtype) ])
|
# There's an inconsistency in how we handle zones in get_dns_zones and in sort_domains, so
|
||||||
|
# do this first before sorting the domains within the zones.
|
||||||
|
zones = utils.sort_domains([z[0] for z in get_dns_zones(env)], env)
|
||||||
|
for r in records:
|
||||||
|
for z in zones:
|
||||||
|
if r["qname"] == z or r["qname"].endswith("." + z):
|
||||||
|
r["zone"] = z
|
||||||
|
break
|
||||||
|
|
||||||
|
# Add sorting information. The 'created' order follows the order in the YAML file on disk,
|
||||||
|
# which tracs the order entries were added in the control panel since we append to the end.
|
||||||
|
# The 'qname' sort order sorts by our standard domain name sort (by zone then by qname),
|
||||||
|
# then by rtype, and last by the original order in the YAML file (since sorting by value
|
||||||
|
# may not make sense, unless we parse IP addresses, for example).
|
||||||
|
for i, r in enumerate(records):
|
||||||
|
r["sort-order"]["created"] = i
|
||||||
|
domain_sort_order = utils.sort_domains([r["qname"] for r in records], env)
|
||||||
|
for i, r in enumerate(sorted(records, key = lambda r : (
|
||||||
|
zones.index(r["zone"]) if r.get("zone") else 0, # record is not within a zone managed by the box
|
||||||
|
domain_sort_order.index(r["qname"]),
|
||||||
|
r["rtype"]))):
|
||||||
|
r["sort-order"]["qname"] = i
|
||||||
|
|
||||||
|
# Return.
|
||||||
|
return json_response(records)
|
||||||
|
|
||||||
@app.route('/dns/custom/<qname>', methods=['GET', 'POST', 'PUT', 'DELETE'])
|
@app.route('/dns/custom/<qname>', methods=['GET', 'POST', 'PUT', 'DELETE'])
|
||||||
@app.route('/dns/custom/<qname>/<rtype>', methods=['GET', 'POST', 'PUT', 'DELETE'])
|
@app.route('/dns/custom/<qname>/<rtype>', methods=['GET', 'POST', 'PUT', 'DELETE'])
|
||||||
@@ -324,6 +396,12 @@ def dns_get_dump():
|
|||||||
from dns_update import build_recommended_dns
|
from dns_update import build_recommended_dns
|
||||||
return json_response(build_recommended_dns(env))
|
return json_response(build_recommended_dns(env))
|
||||||
|
|
||||||
|
@app.route('/dns/zonefile/<zone>')
|
||||||
|
@authorized_personnel_only
|
||||||
|
def dns_get_zonefile(zone):
|
||||||
|
from dns_update import get_dns_zonefile
|
||||||
|
return Response(get_dns_zonefile(zone, env), status=200, mimetype='text/plain')
|
||||||
|
|
||||||
# SSL
|
# SSL
|
||||||
|
|
||||||
@app.route('/ssl/status')
|
@app.route('/ssl/status')
|
||||||
@@ -383,6 +461,60 @@ def ssl_provision_certs():
|
|||||||
requests = provision_certificates(env, limit_domains=None)
|
requests = provision_certificates(env, limit_domains=None)
|
||||||
return json_response({ "requests": requests })
|
return json_response({ "requests": requests })
|
||||||
|
|
||||||
|
# multi-factor auth
|
||||||
|
|
||||||
|
@app.route('/mfa/status', methods=['POST'])
|
||||||
|
@authorized_personnel_only
|
||||||
|
def mfa_get_status():
|
||||||
|
# Anyone accessing this route is an admin, and we permit them to
|
||||||
|
# see the MFA status for any user if they submit a 'user' form
|
||||||
|
# field. But we don't include provisioning info since a user can
|
||||||
|
# only provision for themselves.
|
||||||
|
email = request.form.get('user', request.user_email) # user field if given, otherwise the user making the request
|
||||||
|
try:
|
||||||
|
resp = {
|
||||||
|
"enabled_mfa": get_public_mfa_state(email, env)
|
||||||
|
}
|
||||||
|
if email == request.user_email:
|
||||||
|
resp.update({
|
||||||
|
"new_mfa": {
|
||||||
|
"totp": provision_totp(email, env)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
except ValueError as e:
|
||||||
|
return (str(e), 400)
|
||||||
|
return json_response(resp)
|
||||||
|
|
||||||
|
@app.route('/mfa/totp/enable', methods=['POST'])
|
||||||
|
@authorized_personnel_only
|
||||||
|
def totp_post_enable():
|
||||||
|
secret = request.form.get('secret')
|
||||||
|
token = request.form.get('token')
|
||||||
|
label = request.form.get('label')
|
||||||
|
if type(token) != str:
|
||||||
|
return ("Bad Input", 400)
|
||||||
|
try:
|
||||||
|
validate_totp_secret(secret)
|
||||||
|
enable_mfa(request.user_email, "totp", secret, token, label, env)
|
||||||
|
except ValueError as e:
|
||||||
|
return (str(e), 400)
|
||||||
|
return "OK"
|
||||||
|
|
||||||
|
@app.route('/mfa/disable', methods=['POST'])
|
||||||
|
@authorized_personnel_only
|
||||||
|
def totp_post_disable():
|
||||||
|
# Anyone accessing this route is an admin, and we permit them to
|
||||||
|
# disable the MFA status for any user if they submit a 'user' form
|
||||||
|
# field.
|
||||||
|
email = request.form.get('user', request.user_email) # user field if given, otherwise the user making the request
|
||||||
|
try:
|
||||||
|
result = disable_mfa(email, request.form.get('mfa-id') or None, env) # convert empty string to None
|
||||||
|
except ValueError as e:
|
||||||
|
return (str(e), 400)
|
||||||
|
if result: # success
|
||||||
|
return "OK"
|
||||||
|
else: # error
|
||||||
|
return ("Invalid user or MFA id.", 400)
|
||||||
|
|
||||||
# WEB
|
# WEB
|
||||||
|
|
||||||
@@ -437,9 +569,8 @@ def system_status():
|
|||||||
self.items[-1]["extra"].append({ "text": message, "monospace": monospace })
|
self.items[-1]["extra"].append({ "text": message, "monospace": monospace })
|
||||||
output = WebOutput()
|
output = WebOutput()
|
||||||
# Create a temporary pool of processes for the status checks
|
# Create a temporary pool of processes for the status checks
|
||||||
pool = multiprocessing.pool.Pool(processes=5)
|
with multiprocessing.pool.Pool(processes=5) as pool:
|
||||||
run_checks(False, env, output, pool)
|
run_checks(False, env, output, pool)
|
||||||
pool.terminate()
|
|
||||||
return json_response(output.items)
|
return json_response(output.items)
|
||||||
|
|
||||||
@app.route('/system/updates')
|
@app.route('/system/updates')
|
||||||
@@ -523,16 +654,42 @@ def privacy_status_set():
|
|||||||
# MUNIN
|
# MUNIN
|
||||||
|
|
||||||
@app.route('/munin/')
|
@app.route('/munin/')
|
||||||
@app.route('/munin/<path:filename>')
|
|
||||||
@authorized_personnel_only
|
@authorized_personnel_only
|
||||||
def munin(filename=""):
|
def munin_start():
|
||||||
# Checks administrative access (@authorized_personnel_only) and then just proxies
|
# Munin pages, static images, and dynamically generated images are served
|
||||||
# the request to static files.
|
# outside of the AJAX API. We'll start with a 'start' API that sets a cookie
|
||||||
|
# that subsequent requests will read for authorization. (We don't use cookies
|
||||||
|
# for the API to avoid CSRF vulnerabilities.)
|
||||||
|
response = make_response("OK")
|
||||||
|
response.set_cookie("session", auth_service.create_session_key(request.user_email, env, type='cookie'),
|
||||||
|
max_age=60*30, secure=True, httponly=True, samesite="Strict") # 30 minute duration
|
||||||
|
return response
|
||||||
|
|
||||||
|
def check_request_cookie_for_admin_access():
|
||||||
|
session = auth_service.get_session(None, request.cookies.get("session", ""), "cookie", env)
|
||||||
|
if not session: return False
|
||||||
|
privs = get_mail_user_privileges(session["email"], env)
|
||||||
|
if not isinstance(privs, list): return False
|
||||||
|
if "admin" not in privs: return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def authorized_personnel_only_via_cookie(f):
|
||||||
|
@wraps(f)
|
||||||
|
def g(*args, **kwargs):
|
||||||
|
if not check_request_cookie_for_admin_access():
|
||||||
|
return Response("Unauthorized", status=403, mimetype='text/plain', headers={})
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
return g
|
||||||
|
|
||||||
|
@app.route('/munin/<path:filename>')
|
||||||
|
@authorized_personnel_only_via_cookie
|
||||||
|
def munin_static_file(filename=""):
|
||||||
|
# Proxy the request to static files.
|
||||||
if filename == "": filename = "index.html"
|
if filename == "": filename = "index.html"
|
||||||
return send_from_directory("/var/cache/munin/www", filename)
|
return send_from_directory("/var/cache/munin/www", filename)
|
||||||
|
|
||||||
@app.route('/munin/cgi-graph/<path:filename>')
|
@app.route('/munin/cgi-graph/<path:filename>')
|
||||||
@authorized_personnel_only
|
@authorized_personnel_only_via_cookie
|
||||||
def munin_cgi(filename):
|
def munin_cgi(filename):
|
||||||
""" Relay munin cgi dynazoom requests
|
""" Relay munin cgi dynazoom requests
|
||||||
/usr/lib/munin/cgi/munin-cgi-graph is a perl cgi script in the munin package
|
/usr/lib/munin/cgi/munin-cgi-graph is a perl cgi script in the munin package
|
||||||
@@ -605,19 +762,14 @@ def log_failed_login(request):
|
|||||||
# APP
|
# APP
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
if "DEBUG" in os.environ: app.debug = True
|
if "DEBUG" in os.environ:
|
||||||
if "APIKEY" in os.environ: auth_service.key = os.environ["APIKEY"]
|
# Turn on Flask debugging.
|
||||||
|
app.debug = True
|
||||||
|
|
||||||
if not app.debug:
|
if not app.debug:
|
||||||
app.logger.addHandler(utils.create_syslog_handler())
|
app.logger.addHandler(utils.create_syslog_handler())
|
||||||
|
|
||||||
# For testing on the command line, you can use `curl` like so:
|
#app.logger.info('API key: ' + auth_service.key)
|
||||||
# curl --user $(</var/lib/mailinabox/api.key): http://localhost:10222/mail/users
|
|
||||||
auth_service.write_key()
|
|
||||||
|
|
||||||
# For testing in the browser, you can copy the API key that's output to the
|
|
||||||
# debug console and enter that as the username
|
|
||||||
app.logger.info('API key: ' + auth_service.key)
|
|
||||||
|
|
||||||
# Start the application server. Listens on 127.0.0.1 (IPv4 only).
|
# Start the application server. Listens on 127.0.0.1 (IPv4 only).
|
||||||
app.run(port=10222)
|
app.run(port=10222)
|
||||||
|
|||||||
@@ -16,10 +16,10 @@ if [ `date "+%u"` -eq 1 ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Take a backup.
|
# Take a backup.
|
||||||
management/backup.py | management/email_administrator.py "Backup Status"
|
management/backup.py 2>&1 | management/email_administrator.py "Backup Status"
|
||||||
|
|
||||||
# Provision any new certificates for new domains or domains with expiring certificates.
|
# Provision any new certificates for new domains or domains with expiring certificates.
|
||||||
management/ssl_certificates.py -q | management/email_administrator.py "Error Provisioning TLS Certificate"
|
management/ssl_certificates.py -q 2>&1 | management/email_administrator.py "TLS Certificate Provisioning Result"
|
||||||
|
|
||||||
# Run status checks and email the administrator if anything changed.
|
# Run status checks and email the administrator if anything changed.
|
||||||
management/status_checks.py --show-changes | management/email_administrator.py "Status Checks Change Notice"
|
management/status_checks.py --show-changes 2>&1 | management/email_administrator.py "Status Checks Change Notice"
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ import ipaddress
|
|||||||
import rtyaml
|
import rtyaml
|
||||||
import dns.resolver
|
import dns.resolver
|
||||||
|
|
||||||
from mailconfig import get_mail_domains
|
|
||||||
from utils import shell, load_env_vars_from_file, safe_domain_name, sort_domains
|
from utils import shell, load_env_vars_from_file, safe_domain_name, sort_domains
|
||||||
|
from ssl_certificates import get_ssl_certificates, check_certificate
|
||||||
|
|
||||||
# From https://stackoverflow.com/questions/3026957/how-to-validate-a-domain-name-using-regex-php/16491074#16491074
|
# From https://stackoverflow.com/questions/3026957/how-to-validate-a-domain-name-using-regex-php/16491074#16491074
|
||||||
# This regular expression matches domain names according to RFCs, it also accepts fqdn with an leading dot,
|
# This regular expression matches domain names according to RFCs, it also accepts fqdn with an leading dot,
|
||||||
@@ -19,10 +19,14 @@ from utils import shell, load_env_vars_from_file, safe_domain_name, sort_domains
|
|||||||
DOMAIN_RE = "^(?!\-)(?:[*][.])?(?:[a-zA-Z\d\-_]{0,62}[a-zA-Z\d_]\.){1,126}(?!\d+)[a-zA-Z\d_]{1,63}(\.?)$"
|
DOMAIN_RE = "^(?!\-)(?:[*][.])?(?:[a-zA-Z\d\-_]{0,62}[a-zA-Z\d_]\.){1,126}(?!\d+)[a-zA-Z\d_]{1,63}(\.?)$"
|
||||||
|
|
||||||
def get_dns_domains(env):
|
def get_dns_domains(env):
|
||||||
# Add all domain names in use by email users and mail aliases and ensure
|
# Add all domain names in use by email users and mail aliases, any
|
||||||
# PRIMARY_HOSTNAME is in the list.
|
# domains we serve web for (except www redirects because that would
|
||||||
|
# lead to infinite recursion here) and ensure PRIMARY_HOSTNAME is in the list.
|
||||||
|
from mailconfig import get_mail_domains
|
||||||
|
from web_update import get_web_domains
|
||||||
domains = set()
|
domains = set()
|
||||||
domains |= get_mail_domains(env)
|
domains |= set(get_mail_domains(env))
|
||||||
|
domains |= set(get_web_domains(env, include_www_redirects=False))
|
||||||
domains.add(env['PRIMARY_HOSTNAME'])
|
domains.add(env['PRIMARY_HOSTNAME'])
|
||||||
return domains
|
return domains
|
||||||
|
|
||||||
@@ -96,7 +100,8 @@ def do_dns_update(env, force=False):
|
|||||||
if len(updated_domains) > 0:
|
if len(updated_domains) > 0:
|
||||||
shell('check_call', ["/usr/sbin/service", "nsd", "restart"])
|
shell('check_call', ["/usr/sbin/service", "nsd", "restart"])
|
||||||
|
|
||||||
# Write the OpenDKIM configuration tables for all of the domains.
|
# Write the OpenDKIM configuration tables for all of the mail domains.
|
||||||
|
from mailconfig import get_mail_domains
|
||||||
if write_opendkim_tables(get_mail_domains(env), env):
|
if write_opendkim_tables(get_mail_domains(env), env):
|
||||||
# Settings changed. Kick opendkim.
|
# Settings changed. Kick opendkim.
|
||||||
shell('check_call', ["/usr/sbin/service", "opendkim", "restart"])
|
shell('check_call', ["/usr/sbin/service", "opendkim", "restart"])
|
||||||
@@ -121,18 +126,47 @@ def build_zones(env):
|
|||||||
domains = get_dns_domains(env)
|
domains = get_dns_domains(env)
|
||||||
zonefiles = get_dns_zones(env)
|
zonefiles = get_dns_zones(env)
|
||||||
|
|
||||||
# Custom records to add to zones.
|
# Create a dictionary of domains to a set of attributes for each
|
||||||
additional_records = list(get_custom_dns_config(env))
|
# domain, such as whether there are mail users at the domain.
|
||||||
|
from mailconfig import get_mail_domains
|
||||||
from web_update import get_web_domains
|
from web_update import get_web_domains
|
||||||
www_redirect_domains = set(get_web_domains(env)) - set(get_web_domains(env, include_www_redirects=False))
|
mail_domains = set(get_mail_domains(env))
|
||||||
|
mail_user_domains = set(get_mail_domains(env, users_only=True)) # i.e. will log in for mail, Nextcloud
|
||||||
|
web_domains = set(get_web_domains(env))
|
||||||
|
auto_domains = web_domains - set(get_web_domains(env, include_auto=False))
|
||||||
|
domains |= auto_domains # www redirects not included in the initial list, see above
|
||||||
|
|
||||||
|
# Add ns1/ns2+PRIMARY_HOSTNAME which must also have A/AAAA records
|
||||||
|
# when the box is acting as authoritative DNS server for its domains.
|
||||||
|
for ns in ("ns1", "ns2"):
|
||||||
|
d = ns + "." + env["PRIMARY_HOSTNAME"]
|
||||||
|
domains.add(d)
|
||||||
|
auto_domains.add(d)
|
||||||
|
|
||||||
|
domains = {
|
||||||
|
domain: {
|
||||||
|
"user": domain in mail_user_domains,
|
||||||
|
"mail": domain in mail_domains,
|
||||||
|
"web": domain in web_domains,
|
||||||
|
"auto": domain in auto_domains,
|
||||||
|
}
|
||||||
|
for domain in domains
|
||||||
|
}
|
||||||
|
|
||||||
|
# For MTA-STS, we'll need to check if the PRIMARY_HOSTNAME certificate is
|
||||||
|
# singned and valid. Check that now rather than repeatedly for each domain.
|
||||||
|
domains[env["PRIMARY_HOSTNAME"]]["certificate-is-valid"] = is_domain_cert_signed_and_valid(env["PRIMARY_HOSTNAME"], env)
|
||||||
|
|
||||||
|
# Load custom records to add to zones.
|
||||||
|
additional_records = list(get_custom_dns_config(env))
|
||||||
|
|
||||||
# Build DNS records for each zone.
|
# Build DNS records for each zone.
|
||||||
for domain, zonefile in zonefiles:
|
for domain, zonefile in zonefiles:
|
||||||
# Build the records to put in the zone.
|
# Build the records to put in the zone.
|
||||||
records = build_zone(domain, domains, additional_records, www_redirect_domains, env)
|
records = build_zone(domain, domains, additional_records, env)
|
||||||
yield (domain, zonefile, records)
|
yield (domain, zonefile, records)
|
||||||
|
|
||||||
def build_zone(domain, all_domains, additional_records, www_redirect_domains, env, is_zone=True):
|
def build_zone(domain, domain_properties, additional_records, env, is_zone=True):
|
||||||
records = []
|
records = []
|
||||||
|
|
||||||
# For top-level zones, define the authoritative name servers.
|
# For top-level zones, define the authoritative name servers.
|
||||||
@@ -144,10 +178,10 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|||||||
# 'False' in the tuple indicates these records would not be used if the zone
|
# 'False' in the tuple indicates these records would not be used if the zone
|
||||||
# is managed outside of the box.
|
# is managed outside of the box.
|
||||||
if is_zone:
|
if is_zone:
|
||||||
# Obligatory definition of ns1.PRIMARY_HOSTNAME.
|
# Obligatory NS record to ns1.PRIMARY_HOSTNAME.
|
||||||
records.append((None, "NS", "ns1.%s." % env["PRIMARY_HOSTNAME"], False))
|
records.append((None, "NS", "ns1.%s." % env["PRIMARY_HOSTNAME"], False))
|
||||||
|
|
||||||
# Define ns2.PRIMARY_HOSTNAME or whatever the user overrides.
|
# NS record to ns2.PRIMARY_HOSTNAME or whatever the user overrides.
|
||||||
# User may provide one or more additional nameservers
|
# User may provide one or more additional nameservers
|
||||||
secondary_ns_list = get_secondary_dns(additional_records, mode="NS") \
|
secondary_ns_list = get_secondary_dns(additional_records, mode="NS") \
|
||||||
or ["ns2." + env["PRIMARY_HOSTNAME"]]
|
or ["ns2." + env["PRIMARY_HOSTNAME"]]
|
||||||
@@ -157,15 +191,6 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|||||||
|
|
||||||
# In PRIMARY_HOSTNAME...
|
# In PRIMARY_HOSTNAME...
|
||||||
if domain == env["PRIMARY_HOSTNAME"]:
|
if domain == env["PRIMARY_HOSTNAME"]:
|
||||||
# Define ns1 and ns2.
|
|
||||||
# 'False' in the tuple indicates these records would not be used if the zone
|
|
||||||
# is managed outside of the box.
|
|
||||||
records.append(("ns1", "A", env["PUBLIC_IP"], False))
|
|
||||||
records.append(("ns2", "A", env["PUBLIC_IP"], False))
|
|
||||||
if env.get('PUBLIC_IPV6'):
|
|
||||||
records.append(("ns1", "AAAA", env["PUBLIC_IPV6"], False))
|
|
||||||
records.append(("ns2", "AAAA", env["PUBLIC_IPV6"], False))
|
|
||||||
|
|
||||||
# Set the A/AAAA records. Do this early for the PRIMARY_HOSTNAME so that the user cannot override them
|
# Set the A/AAAA records. Do this early for the PRIMARY_HOSTNAME so that the user cannot override them
|
||||||
# and we can provide different explanatory text.
|
# and we can provide different explanatory text.
|
||||||
records.append((None, "A", env["PUBLIC_IP"], "Required. Sets the IP address of the box."))
|
records.append((None, "A", env["PUBLIC_IP"], "Required. Sets the IP address of the box."))
|
||||||
@@ -183,10 +208,11 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|||||||
|
|
||||||
# Add DNS records for any subdomains of this domain. We should not have a zone for
|
# Add DNS records for any subdomains of this domain. We should not have a zone for
|
||||||
# both a domain and one of its subdomains.
|
# both a domain and one of its subdomains.
|
||||||
subdomains = [d for d in all_domains if d.endswith("." + domain)]
|
if is_zone: # don't recurse when we're just loading data for a subdomain
|
||||||
|
subdomains = [d for d in domain_properties if d.endswith("." + domain)]
|
||||||
for subdomain in subdomains:
|
for subdomain in subdomains:
|
||||||
subdomain_qname = subdomain[0:-len("." + domain)]
|
subdomain_qname = subdomain[0:-len("." + domain)]
|
||||||
subzone = build_zone(subdomain, [], additional_records, www_redirect_domains, env, is_zone=False)
|
subzone = build_zone(subdomain, domain_properties, additional_records, env, is_zone=False)
|
||||||
for child_qname, child_rtype, child_value, child_explanation in subzone:
|
for child_qname, child_rtype, child_value, child_explanation in subzone:
|
||||||
if child_qname == None:
|
if child_qname == None:
|
||||||
child_qname = subdomain_qname
|
child_qname = subdomain_qname
|
||||||
@@ -219,21 +245,23 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|||||||
continue
|
continue
|
||||||
records.append((qname, rtype, value, "(Set by user.)"))
|
records.append((qname, rtype, value, "(Set by user.)"))
|
||||||
|
|
||||||
# Add defaults if not overridden by the user's custom settings (and not otherwise configured).
|
# Add A/AAAA defaults if not overridden by the user's custom settings (and not otherwise configured).
|
||||||
# Any CNAME or A record on the qname overrides A and AAAA. But when we set the default A record,
|
# Any CNAME or A record on the qname overrides A and AAAA. But when we set the default A record,
|
||||||
# we should not cause the default AAAA record to be skipped because it thinks a custom A record
|
# we should not cause the default AAAA record to be skipped because it thinks a custom A record
|
||||||
# was set. So set has_rec_base to a clone of the current set of DNS settings, and don't update
|
# was set. So set has_rec_base to a clone of the current set of DNS settings, and don't update
|
||||||
# during this process.
|
# during this process.
|
||||||
has_rec_base = list(records)
|
has_rec_base = list(records)
|
||||||
|
a_expl = "Required. May have a different value. Sets the IP address that %s resolves to for web hosting and other services besides mail. The A record must be present but its value does not affect mail delivery." % domain
|
||||||
|
if domain_properties[domain]["auto"]:
|
||||||
|
if domain.startswith("ns1.") or domain.startswith("ns2."): a_expl = False # omit from 'External DNS' page since this only applies if box is its own DNS server
|
||||||
|
if domain.startswith("www."): a_expl = "Optional. Sets the IP address that %s resolves to so that the box can provide a redirect to the parent domain." % domain
|
||||||
|
if domain.startswith("mta-sts."): a_expl = "Optional. MTA-STS Policy Host serving /.well-known/mta-sts.txt."
|
||||||
|
if domain.startswith("autoconfig."): a_expl = "Provides email configuration autodiscovery support for Thunderbird Autoconfig."
|
||||||
|
if domain.startswith("autodiscover."): a_expl = "Provides email configuration autodiscovery support for Z-Push ActiveSync Autodiscover."
|
||||||
defaults = [
|
defaults = [
|
||||||
(None, "A", env["PUBLIC_IP"], "Required. May have a different value. Sets the IP address that %s resolves to for web hosting and other services besides mail. The A record must be present but its value does not affect mail delivery." % domain),
|
(None, "A", env["PUBLIC_IP"], a_expl),
|
||||||
(None, "AAAA", env.get('PUBLIC_IPV6'), "Optional. Sets the IPv6 address that %s resolves to, e.g. for web hosting. (It is not necessary for receiving mail on this domain.)" % domain),
|
(None, "AAAA", env.get('PUBLIC_IPV6'), "Optional. Sets the IPv6 address that %s resolves to, e.g. for web hosting. (It is not necessary for receiving mail on this domain.)" % domain),
|
||||||
]
|
]
|
||||||
if "www." + domain in www_redirect_domains:
|
|
||||||
defaults += [
|
|
||||||
("www", "A", env["PUBLIC_IP"], "Optional. Sets the IP address that www.%s resolves to so that the box can provide a redirect to the parent domain." % domain),
|
|
||||||
("www", "AAAA", env.get('PUBLIC_IPV6'), "Optional. Sets the IPv6 address that www.%s resolves to so that the box can provide a redirect to the parent domain." % domain),
|
|
||||||
]
|
|
||||||
for qname, rtype, value, explanation in defaults:
|
for qname, rtype, value, explanation in defaults:
|
||||||
if value is None or value.strip() == "": continue # skip IPV6 if not set
|
if value is None or value.strip() == "": continue # skip IPV6 if not set
|
||||||
if not is_zone and qname == "www": continue # don't create any default 'www' subdomains on what are themselves subdomains
|
if not is_zone and qname == "www": continue # don't create any default 'www' subdomains on what are themselves subdomains
|
||||||
@@ -247,6 +275,7 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|||||||
# Don't pin the list of records that has_rec checks against anymore.
|
# Don't pin the list of records that has_rec checks against anymore.
|
||||||
has_rec_base = records
|
has_rec_base = records
|
||||||
|
|
||||||
|
if domain_properties[domain]["mail"]:
|
||||||
# The MX record says where email for the domain should be delivered: Here!
|
# The MX record says where email for the domain should be delivered: Here!
|
||||||
if not has_rec(None, "MX", prefix="10 "):
|
if not has_rec(None, "MX", prefix="10 "):
|
||||||
records.append((None, "MX", "10 %s." % env["PRIMARY_HOSTNAME"], "Required. Specifies the hostname (and priority) of the machine that handles @%s mail." % domain))
|
records.append((None, "MX", "10 %s." % env["PRIMARY_HOSTNAME"], "Required. Specifies the hostname (and priority) of the machine that handles @%s mail." % domain))
|
||||||
@@ -271,16 +300,9 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|||||||
if not has_rec("_dmarc", "TXT", prefix="v=DMARC1; "):
|
if not has_rec("_dmarc", "TXT", prefix="v=DMARC1; "):
|
||||||
records.append(("_dmarc", "TXT", 'v=DMARC1; p=quarantine', "Recommended. Specifies that mail that does not originate from the box but claims to be from @%s or which does not have a valid DKIM signature is suspect and should be quarantined by the recipient's mail system." % domain))
|
records.append(("_dmarc", "TXT", 'v=DMARC1; p=quarantine', "Recommended. Specifies that mail that does not originate from the box but claims to be from @%s or which does not have a valid DKIM signature is suspect and should be quarantined by the recipient's mail system." % domain))
|
||||||
|
|
||||||
# For any subdomain with an A record but no SPF or DMARC record, add strict policy records.
|
if domain_properties[domain]["user"]:
|
||||||
all_resolvable_qnames = set(r[0] for r in records if r[1] in ("A", "AAAA"))
|
# Add CardDAV/CalDAV SRV records on the non-primary hostname that points to the primary hostname
|
||||||
for qname in all_resolvable_qnames:
|
# for autoconfiguration of mail clients (so only domains hosting user accounts need it).
|
||||||
if not has_rec(qname, "TXT", prefix="v=spf1 "):
|
|
||||||
records.append((qname, "TXT", 'v=spf1 -all', "Recommended. Prevents use of this domain name for outbound mail by specifying that no servers are valid sources for mail from @%s. If you do send email from this domain name you should either override this record such that the SPF rule does allow the originating server, or, take the recommended approach and have the box handle mail for this domain (simply add any receiving alias at this domain name to make this machine treat the domain name as one of its mail domains)." % (qname + "." + domain)))
|
|
||||||
dmarc_qname = "_dmarc" + ("" if qname is None else "." + qname)
|
|
||||||
if not has_rec(dmarc_qname, "TXT", prefix="v=DMARC1; "):
|
|
||||||
records.append((dmarc_qname, "TXT", 'v=DMARC1; p=reject', "Recommended. Prevents use of this domain name for outbound mail by specifying that the SPF rule should be honoured for mail from @%s." % (qname + "." + domain)))
|
|
||||||
|
|
||||||
# Add CardDAV/CalDAV SRV records on the non-primary hostname that points to the primary hostname.
|
|
||||||
# The SRV record format is priority (0, whatever), weight (0, whatever), port, service provider hostname (w/ trailing dot).
|
# The SRV record format is priority (0, whatever), weight (0, whatever), port, service provider hostname (w/ trailing dot).
|
||||||
if domain != env["PRIMARY_HOSTNAME"]:
|
if domain != env["PRIMARY_HOSTNAME"]:
|
||||||
for dav in ("card", "cal"):
|
for dav in ("card", "cal"):
|
||||||
@@ -288,26 +310,76 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|||||||
if not has_rec(qname, "SRV"):
|
if not has_rec(qname, "SRV"):
|
||||||
records.append((qname, "SRV", "0 0 443 " + env["PRIMARY_HOSTNAME"] + ".", "Recommended. Specifies the hostname of the server that handles CardDAV/CalDAV services for email addresses on this domain."))
|
records.append((qname, "SRV", "0 0 443 " + env["PRIMARY_HOSTNAME"] + ".", "Recommended. Specifies the hostname of the server that handles CardDAV/CalDAV services for email addresses on this domain."))
|
||||||
|
|
||||||
# Adds autoconfiguration A records for all domains.
|
# If this is a domain name that there are email addresses configured for, i.e. "something@"
|
||||||
# This allows the following clients to automatically configure email addresses in the respective applications.
|
# this domain name, then the domain name is a MTA-STS (https://tools.ietf.org/html/rfc8461)
|
||||||
# autodiscover.* - Z-Push ActiveSync Autodiscover
|
# Policy Domain.
|
||||||
# autoconfig.* - Thunderbird Autoconfig
|
#
|
||||||
autodiscover_records = [
|
# A "_mta-sts" TXT record signals the presence of a MTA-STS policy. The id field helps clients
|
||||||
("autodiscover", "A", env["PUBLIC_IP"], "Provides email configuration autodiscovery support for Z-Push ActiveSync Autodiscover."),
|
# cache the policy. It should be stable so we don't update DNS unnecessarily but change when
|
||||||
("autodiscover", "AAAA", env["PUBLIC_IPV6"], "Provides email configuration autodiscovery support for Z-Push ActiveSync Autodiscover."),
|
# the policy changes. It must be at most 32 letters and numbers, so we compute a hash of the
|
||||||
("autoconfig", "A", env["PUBLIC_IP"], "Provides email configuration autodiscovery support for Thunderbird Autoconfig."),
|
# policy file.
|
||||||
("autoconfig", "AAAA", env["PUBLIC_IPV6"], "Provides email configuration autodiscovery support for Thunderbird Autoconfig.")
|
#
|
||||||
]
|
# The policy itself is served at the "mta-sts" (no underscore) subdomain over HTTPS. Therefore
|
||||||
for qname, rtype, value, explanation in autodiscover_records:
|
# the TLS certificate used by Postfix for STARTTLS must be a valid certificate for the MX
|
||||||
if value is None or value.strip() == "": continue # skip IPV6 if not set
|
# domain name (PRIMARY_HOSTNAME) *and* the TLS certificate used by nginx for HTTPS on the mta-sts
|
||||||
|
# subdomain must be valid certificate for that domain. Do not set an MTA-STS policy if either
|
||||||
|
# certificate in use is not valid (e.g. because it is self-signed and a valid certificate has not
|
||||||
|
# yet been provisioned). Since we cannot provision a certificate without A/AAAA records, we
|
||||||
|
# always set them (by including them in the www domains) --- only the TXT records depend on there
|
||||||
|
# being valid certificates.
|
||||||
|
mta_sts_records = [ ]
|
||||||
|
if domain_properties[domain]["mail"] \
|
||||||
|
and domain_properties[env["PRIMARY_HOSTNAME"]]["certificate-is-valid"] \
|
||||||
|
and is_domain_cert_signed_and_valid("mta-sts." + domain, env):
|
||||||
|
# Compute an up-to-32-character hash of the policy file. We'll take a SHA-1 hash of the policy
|
||||||
|
# file (20 bytes) and encode it as base-64 (28 bytes, using alphanumeric alternate characters
|
||||||
|
# instead of '+' and '/' which are not allowed in an MTA-STS policy id) but then just take its
|
||||||
|
# first 20 characters, which is more than sufficient to change whenever the policy file changes
|
||||||
|
# (and ensures any '=' padding at the end of the base64 encoding is dropped).
|
||||||
|
with open("/var/lib/mailinabox/mta-sts.txt", "rb") as f:
|
||||||
|
mta_sts_policy_id = base64.b64encode(hashlib.sha1(f.read()).digest(), altchars=b"AA").decode("ascii")[0:20]
|
||||||
|
mta_sts_records.extend([
|
||||||
|
("_mta-sts", "TXT", "v=STSv1; id=" + mta_sts_policy_id, "Optional. Part of the MTA-STS policy for incoming mail. If set, a MTA-STS policy must also be published.")
|
||||||
|
])
|
||||||
|
|
||||||
|
# Enable SMTP TLS reporting (https://tools.ietf.org/html/rfc8460) if the user has set a config option.
|
||||||
|
# Skip if the rules below if the user has set a custom _smtp._tls record.
|
||||||
|
if env.get("MTA_STS_TLSRPT_RUA") and not has_rec("_smtp._tls", "TXT", prefix="v=TLSRPTv1;"):
|
||||||
|
mta_sts_records.append(("_smtp._tls", "TXT", "v=TLSRPTv1; rua=" + env["MTA_STS_TLSRPT_RUA"], "Optional. Enables MTA-STS reporting."))
|
||||||
|
for qname, rtype, value, explanation in mta_sts_records:
|
||||||
if not has_rec(qname, rtype):
|
if not has_rec(qname, rtype):
|
||||||
records.append((qname, rtype, value, explanation))
|
records.append((qname, rtype, value, explanation))
|
||||||
|
|
||||||
|
# Add no-mail-here records for any qname that has an A or AAAA record
|
||||||
|
# but no MX record. This would include domain itself if domain is a
|
||||||
|
# non-mail domain and also may include qnames from custom DNS records.
|
||||||
|
# Do this once at the end of generating a zone.
|
||||||
|
if is_zone:
|
||||||
|
qnames_with_a = set(qname for (qname, rtype, value, explanation) in records if rtype in ("A", "AAAA"))
|
||||||
|
qnames_with_mx = set(qname for (qname, rtype, value, explanation) in records if rtype == "MX")
|
||||||
|
for qname in qnames_with_a - qnames_with_mx:
|
||||||
|
# Mark this domain as not sending mail with hard-fail SPF and DMARC records.
|
||||||
|
d = (qname+"." if qname else "") + domain
|
||||||
|
if not has_rec(qname, "TXT", prefix="v=spf1 "):
|
||||||
|
records.append((qname, "TXT", 'v=spf1 -all', "Recommended. Prevents use of this domain name for outbound mail by specifying that no servers are valid sources for mail from @%s. If you do send email from this domain name you should either override this record such that the SPF rule does allow the originating server, or, take the recommended approach and have the box handle mail for this domain (simply add any receiving alias at this domain name to make this machine treat the domain name as one of its mail domains)." % d))
|
||||||
|
if not has_rec("_dmarc" + ("."+qname if qname else ""), "TXT", prefix="v=DMARC1; "):
|
||||||
|
records.append(("_dmarc" + ("."+qname if qname else ""), "TXT", 'v=DMARC1; p=reject', "Recommended. Prevents use of this domain name for outbound mail by specifying that the SPF rule should be honoured for mail from @%s." % d))
|
||||||
|
|
||||||
|
# And with a null MX record (https://explained-from-first-principles.com/email/#null-mx-record)
|
||||||
|
if not has_rec(qname, "MX"):
|
||||||
|
records.append((qname, "MX", '0 .', "Recommended. Prevents use of this domain name for incoming mail."))
|
||||||
|
|
||||||
# Sort the records. The None records *must* go first in the nsd zone file. Otherwise it doesn't matter.
|
# Sort the records. The None records *must* go first in the nsd zone file. Otherwise it doesn't matter.
|
||||||
records.sort(key = lambda rec : list(reversed(rec[0].split(".")) if rec[0] is not None else ""))
|
records.sort(key = lambda rec : list(reversed(rec[0].split(".")) if rec[0] is not None else ""))
|
||||||
|
|
||||||
return records
|
return records
|
||||||
|
|
||||||
|
def is_domain_cert_signed_and_valid(domain, env):
|
||||||
|
cert = get_ssl_certificates(env).get(domain)
|
||||||
|
if not cert: return False # no certificate provisioned
|
||||||
|
cert_status = check_certificate(domain, cert['certificate'], cert['private-key'])
|
||||||
|
return cert_status[0] == 'OK'
|
||||||
|
|
||||||
########################################################################
|
########################################################################
|
||||||
|
|
||||||
def build_tlsa_record(env):
|
def build_tlsa_record(env):
|
||||||
@@ -372,6 +444,7 @@ def build_sshfp_records():
|
|||||||
# to the zone file (that trigger bumping the serial number). However,
|
# to the zone file (that trigger bumping the serial number). However,
|
||||||
# if SSH has been configured to listen on a nonstandard port, we must
|
# if SSH has been configured to listen on a nonstandard port, we must
|
||||||
# specify that port to sshkeyscan.
|
# specify that port to sshkeyscan.
|
||||||
|
|
||||||
port = 22
|
port = 22
|
||||||
with open('/etc/ssh/sshd_config', 'r') as f:
|
with open('/etc/ssh/sshd_config', 'r') as f:
|
||||||
for line in f:
|
for line in f:
|
||||||
@@ -382,8 +455,11 @@ def build_sshfp_records():
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
break
|
break
|
||||||
|
|
||||||
keys = shell("check_output", ["ssh-keyscan", "-t", "rsa,dsa,ecdsa,ed25519", "-p", str(port), "localhost"])
|
keys = shell("check_output", ["ssh-keyscan", "-t", "rsa,dsa,ecdsa,ed25519", "-p", str(port), "localhost"])
|
||||||
for key in sorted(keys.split("\n")):
|
keys = sorted(keys.split("\n"))
|
||||||
|
|
||||||
|
for key in keys:
|
||||||
if key.strip() == "" or key[0] == "#": continue
|
if key.strip() == "" or key[0] == "#": continue
|
||||||
try:
|
try:
|
||||||
host, keytype, pubkey = key.split(" ")
|
host, keytype, pubkey = key.split(" ")
|
||||||
@@ -403,24 +479,27 @@ def write_nsd_zone(domain, zonefile, records, env, force):
|
|||||||
# On the $ORIGIN line, there's typically a ';' comment at the end explaining
|
# On the $ORIGIN line, there's typically a ';' comment at the end explaining
|
||||||
# what the $ORIGIN line does. Any further data after the domain confuses
|
# what the $ORIGIN line does. Any further data after the domain confuses
|
||||||
# ldns-signzone, however. It used to say '; default zone domain'.
|
# ldns-signzone, however. It used to say '; default zone domain'.
|
||||||
|
#
|
||||||
# The SOA contact address for all of the domains on this system is hostmaster
|
# The SOA contact address for all of the domains on this system is hostmaster
|
||||||
# @ the PRIMARY_HOSTNAME. Hopefully that's legit.
|
# @ the PRIMARY_HOSTNAME. Hopefully that's legit.
|
||||||
|
#
|
||||||
# For the refresh through TTL fields, a good reference is:
|
# For the refresh through TTL fields, a good reference is:
|
||||||
# http://www.peerwisdom.org/2013/05/15/dns-understanding-the-soa-record/
|
# https://www.ripe.net/publications/docs/ripe-203
|
||||||
|
#
|
||||||
|
# A hash of the available DNSSEC keys are added in a comment so that when
|
||||||
|
# the keys change we force a re-generation of the zone which triggers
|
||||||
|
# re-signing it.
|
||||||
|
|
||||||
zone = """
|
zone = """
|
||||||
$ORIGIN {domain}.
|
$ORIGIN {domain}.
|
||||||
$TTL 1800 ; default time to live
|
$TTL 86400 ; default time to live
|
||||||
|
|
||||||
@ IN SOA ns1.{primary_domain}. hostmaster.{primary_domain}. (
|
@ IN SOA ns1.{primary_domain}. hostmaster.{primary_domain}. (
|
||||||
__SERIAL__ ; serial number
|
__SERIAL__ ; serial number
|
||||||
7200 ; Refresh (secondary nameserver update interval)
|
7200 ; Refresh (secondary nameserver update interval)
|
||||||
1800 ; Retry (when refresh fails, how often to try again)
|
3600 ; Retry (when refresh fails, how often to try again, should be lower than the refresh)
|
||||||
1209600 ; Expire (when refresh fails, how long secondary nameserver will keep records around anyway)
|
1209600 ; Expire (when refresh fails, how long secondary nameserver will keep records around anyway)
|
||||||
1800 ; Negative TTL (how long negative responses are cached)
|
86400 ; Negative TTL (how long negative responses are cached)
|
||||||
)
|
)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -445,6 +524,9 @@ $TTL 1800 ; default time to live
|
|||||||
value = v2
|
value = v2
|
||||||
zone += value + "\n"
|
zone += value + "\n"
|
||||||
|
|
||||||
|
# Append a stable hash of DNSSEC signing keys in a comment.
|
||||||
|
zone += "\n; DNSSEC signing keys hash: {}\n".format(hash_dnssec_keys(domain, env))
|
||||||
|
|
||||||
# DNSSEC requires re-signing a zone periodically. That requires
|
# DNSSEC requires re-signing a zone periodically. That requires
|
||||||
# bumping the serial number even if no other records have changed.
|
# bumping the serial number even if no other records have changed.
|
||||||
# We don't see the DNSSEC records yet, so we have to figure out
|
# We don't see the DNSSEC records yet, so we have to figure out
|
||||||
@@ -507,11 +589,22 @@ $TTL 1800 ; default time to live
|
|||||||
|
|
||||||
return True # file is updated
|
return True # file is updated
|
||||||
|
|
||||||
|
def get_dns_zonefile(zone, env):
|
||||||
|
for domain, fn in get_dns_zones(env):
|
||||||
|
if zone == domain:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
raise ValueError("%s is not a domain name that corresponds to a zone." % zone)
|
||||||
|
|
||||||
|
nsd_zonefile = "/etc/nsd/zones/" + fn
|
||||||
|
with open(nsd_zonefile, "r") as f:
|
||||||
|
return f.read()
|
||||||
|
|
||||||
########################################################################
|
########################################################################
|
||||||
|
|
||||||
def write_nsd_conf(zonefiles, additional_records, env):
|
def write_nsd_conf(zonefiles, additional_records, env):
|
||||||
# Write the list of zones to a configuration file.
|
# Write the list of zones to a configuration file.
|
||||||
nsd_conf_file = "/etc/nsd/zones.conf"
|
nsd_conf_file = "/etc/nsd/nsd.conf.d/zones.conf"
|
||||||
nsdconf = ""
|
nsdconf = ""
|
||||||
|
|
||||||
# Append the zones.
|
# Append the zones.
|
||||||
@@ -523,9 +616,11 @@ zone:
|
|||||||
""" % (domain, zonefile)
|
""" % (domain, zonefile)
|
||||||
|
|
||||||
# If custom secondary nameservers have been set, allow zone transfers
|
# If custom secondary nameservers have been set, allow zone transfers
|
||||||
# and notifies to them.
|
# and, if not a subnet, notifies to them.
|
||||||
for ipaddr in get_secondary_dns(additional_records, mode="xfr"):
|
for ipaddr in get_secondary_dns(additional_records, mode="xfr"):
|
||||||
nsdconf += "\n\tnotify: %s NOKEY\n\tprovide-xfr: %s NOKEY\n" % (ipaddr, ipaddr)
|
if "/" not in ipaddr:
|
||||||
|
nsdconf += "\n\tnotify: %s NOKEY" % (ipaddr)
|
||||||
|
nsdconf += "\n\tprovide-xfr: %s NOKEY\n" % (ipaddr)
|
||||||
|
|
||||||
# Check if the file is changing. If it isn't changing,
|
# Check if the file is changing. If it isn't changing,
|
||||||
# return False to flag that no change was made.
|
# return False to flag that no change was made.
|
||||||
@@ -542,53 +637,77 @@ zone:
|
|||||||
|
|
||||||
########################################################################
|
########################################################################
|
||||||
|
|
||||||
def dnssec_choose_algo(domain, env):
|
def find_dnssec_signing_keys(domain, env):
|
||||||
if '.' in domain and domain.rsplit('.')[-1] in \
|
# For key that we generated (one per algorithm)...
|
||||||
("email", "guide", "fund", "be", "lv"):
|
d = os.path.join(env['STORAGE_ROOT'], 'dns/dnssec')
|
||||||
# At GoDaddy, RSASHA256 is the only algorithm supported
|
keyconfs = [f for f in os.listdir(d) if f.endswith(".conf")]
|
||||||
# for .email and .guide.
|
for keyconf in keyconfs:
|
||||||
# A variety of algorithms are supported for .fund. This
|
# Load the file holding the KSK and ZSK key filenames.
|
||||||
# is preferred.
|
keyconf_fn = os.path.join(d, keyconf)
|
||||||
# Gandi tells me that .be does not support RSASHA1-NSEC3-SHA1
|
keyinfo = load_env_vars_from_file(keyconf_fn)
|
||||||
# Nic.lv does not support RSASHA1-NSEC3-SHA1 for .lv tld's
|
|
||||||
return "RSASHA256"
|
|
||||||
|
|
||||||
# For any domain we were able to sign before, don't change the algorithm
|
# Skip this key if the conf file has a setting named DOMAINS,
|
||||||
# on existing users. We'll probably want to migrate to SHA256 later.
|
# holding a comma-separated list of domain names, and if this
|
||||||
return "RSASHA1-NSEC3-SHA1"
|
# domain is not in the list. This allows easily disabling a
|
||||||
|
# key by setting "DOMAINS=" or "DOMAINS=none", other than
|
||||||
|
# deleting the key's .conf file, which might result in the key
|
||||||
|
# being regenerated next upgrade. Keys should be disabled if
|
||||||
|
# they are not needed to reduce the DNSSEC query response size.
|
||||||
|
if "DOMAINS" in keyinfo and domain not in [dd.strip() for dd in keyinfo["DOMAINS"].split(",")]:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for keytype in ("KSK", "ZSK"):
|
||||||
|
yield keytype, keyinfo[keytype]
|
||||||
|
|
||||||
|
def hash_dnssec_keys(domain, env):
|
||||||
|
# Create a stable (by sorting the items) hash of all of the private keys
|
||||||
|
# that will be used to sign this domain.
|
||||||
|
keydata = []
|
||||||
|
for keytype, keyfn in sorted(find_dnssec_signing_keys(domain, env)):
|
||||||
|
oldkeyfn = os.path.join(env['STORAGE_ROOT'], 'dns/dnssec', keyfn + ".private")
|
||||||
|
keydata.append(keytype)
|
||||||
|
keydata.append(keyfn)
|
||||||
|
with open(oldkeyfn, "r") as fr:
|
||||||
|
keydata.append( fr.read() )
|
||||||
|
keydata = "".join(keydata).encode("utf8")
|
||||||
|
return hashlib.sha1(keydata).hexdigest()
|
||||||
|
|
||||||
def sign_zone(domain, zonefile, env):
|
def sign_zone(domain, zonefile, env):
|
||||||
algo = dnssec_choose_algo(domain, env)
|
# Sign the zone with all of the keys that were generated during
|
||||||
dnssec_keys = load_env_vars_from_file(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/%s.conf' % algo))
|
# setup so that the user can choose which to use in their DS record at
|
||||||
|
# their registrar, and also to support migration to newer algorithms.
|
||||||
|
|
||||||
# In order to use the same keys for all domains, we have to generate
|
# In order to use the key files generated at setup which are for
|
||||||
# a new .key file with a DNSSEC record for the specific domain. We
|
# the domain _domain_, we have to re-write the files and place
|
||||||
# can reuse the same key, but it won't validate without a DNSSEC
|
# the actual domain name in it, so that ldns-signzone works.
|
||||||
# record specifically for the domain.
|
|
||||||
#
|
#
|
||||||
|
# Patch each key, storing the patched version in /tmp for now.
|
||||||
|
# Each key has a .key and .private file. Collect a list of filenames
|
||||||
|
# for all of the keys (and separately just the key-signing keys).
|
||||||
|
all_keys = []
|
||||||
|
ksk_keys = []
|
||||||
|
for keytype, keyfn in find_dnssec_signing_keys(domain, env):
|
||||||
|
newkeyfn = '/tmp/' + keyfn.replace("_domain_", domain)
|
||||||
|
|
||||||
|
for ext in (".private", ".key"):
|
||||||
# Copy the .key and .private files to /tmp to patch them up.
|
# Copy the .key and .private files to /tmp to patch them up.
|
||||||
#
|
#
|
||||||
# Use os.umask and open().write() to securely create a copy that only
|
# Use os.umask and open().write() to securely create a copy that only
|
||||||
# we (root) can read.
|
# we (root) can read.
|
||||||
files_to_kill = []
|
oldkeyfn = os.path.join(env['STORAGE_ROOT'], 'dns/dnssec', keyfn + ext)
|
||||||
for key in ("KSK", "ZSK"):
|
with open(oldkeyfn, "r") as fr:
|
||||||
if dnssec_keys.get(key, "").strip() == "": raise Exception("DNSSEC is not properly set up.")
|
|
||||||
oldkeyfn = os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/' + dnssec_keys[key])
|
|
||||||
newkeyfn = '/tmp/' + dnssec_keys[key].replace("_domain_", domain)
|
|
||||||
dnssec_keys[key] = newkeyfn
|
|
||||||
for ext in (".private", ".key"):
|
|
||||||
if not os.path.exists(oldkeyfn + ext): raise Exception("DNSSEC is not properly set up.")
|
|
||||||
with open(oldkeyfn + ext, "r") as fr:
|
|
||||||
keydata = fr.read()
|
keydata = fr.read()
|
||||||
keydata = keydata.replace("_domain_", domain) # trick ldns-signkey into letting our generic key be used by this zone
|
keydata = keydata.replace("_domain_", domain)
|
||||||
fn = newkeyfn + ext
|
|
||||||
prev_umask = os.umask(0o77) # ensure written file is not world-readable
|
prev_umask = os.umask(0o77) # ensure written file is not world-readable
|
||||||
try:
|
try:
|
||||||
with open(fn, "w") as fw:
|
with open(newkeyfn + ext, "w") as fw:
|
||||||
fw.write(keydata)
|
fw.write(keydata)
|
||||||
finally:
|
finally:
|
||||||
os.umask(prev_umask) # other files we write should be world-readable
|
os.umask(prev_umask) # other files we write should be world-readable
|
||||||
files_to_kill.append(fn)
|
|
||||||
|
# Put the patched key filename base (without extension) into the list of keys we'll sign with.
|
||||||
|
all_keys.append(newkeyfn)
|
||||||
|
if keytype == "KSK": ksk_keys.append(newkeyfn)
|
||||||
|
|
||||||
# Do the signing.
|
# Do the signing.
|
||||||
expiry_date = (datetime.datetime.now() + datetime.timedelta(days=30)).strftime("%Y%m%d")
|
expiry_date = (datetime.datetime.now() + datetime.timedelta(days=30)).strftime("%Y%m%d")
|
||||||
@@ -601,32 +720,34 @@ def sign_zone(domain, zonefile, env):
|
|||||||
|
|
||||||
# zonefile to sign
|
# zonefile to sign
|
||||||
"/etc/nsd/zones/" + zonefile,
|
"/etc/nsd/zones/" + zonefile,
|
||||||
|
]
|
||||||
# keys to sign with (order doesn't matter -- it'll figure it out)
|
# keys to sign with (order doesn't matter -- it'll figure it out)
|
||||||
dnssec_keys["KSK"],
|
+ all_keys
|
||||||
dnssec_keys["ZSK"],
|
)
|
||||||
])
|
|
||||||
|
|
||||||
# Create a DS record based on the patched-up key files. The DS record is specific to the
|
# Create a DS record based on the patched-up key files. The DS record is specific to the
|
||||||
# zone being signed, so we can't use the .ds files generated when we created the keys.
|
# zone being signed, so we can't use the .ds files generated when we created the keys.
|
||||||
# The DS record points to the KSK only. Write this next to the zone file so we can
|
# The DS record points to the KSK only. Write this next to the zone file so we can
|
||||||
# get it later to give to the user with instructions on what to do with it.
|
# get it later to give to the user with instructions on what to do with it.
|
||||||
#
|
#
|
||||||
# We want to be able to validate DS records too, but multiple forms may be valid depending
|
# Generate a DS record for each key. There are also several possible hash algorithms that may
|
||||||
# on the digest type. So we'll write all (both) valid records. Only one DS record should
|
# be used, so we'll pre-generate all for each key. One DS record per line. Only one
|
||||||
# actually be deployed. Preferebly the first.
|
# needs to actually be deployed at the registrar. We'll select the preferred one
|
||||||
|
# in the status checks.
|
||||||
with open("/etc/nsd/zones/" + zonefile + ".ds", "w") as f:
|
with open("/etc/nsd/zones/" + zonefile + ".ds", "w") as f:
|
||||||
for digest_type in ('2', '1'):
|
for key in ksk_keys:
|
||||||
|
for digest_type in ('1', '2', '4'):
|
||||||
rr_ds = shell('check_output', ["/usr/bin/ldns-key2ds",
|
rr_ds = shell('check_output', ["/usr/bin/ldns-key2ds",
|
||||||
"-n", # output to stdout
|
"-n", # output to stdout
|
||||||
"-" + digest_type, # 1=SHA1, 2=SHA256
|
"-" + digest_type, # 1=SHA1, 2=SHA256, 4=SHA384
|
||||||
dnssec_keys["KSK"] + ".key"
|
key + ".key"
|
||||||
])
|
])
|
||||||
f.write(rr_ds)
|
f.write(rr_ds)
|
||||||
|
|
||||||
# Remove our temporary file.
|
# Remove the temporary patched key files.
|
||||||
for fn in files_to_kill:
|
for fn in all_keys:
|
||||||
os.unlink(fn)
|
os.unlink(fn + ".private")
|
||||||
|
os.unlink(fn + ".key")
|
||||||
|
|
||||||
########################################################################
|
########################################################################
|
||||||
|
|
||||||
@@ -683,7 +804,7 @@ def write_opendkim_tables(domains, env):
|
|||||||
|
|
||||||
########################################################################
|
########################################################################
|
||||||
|
|
||||||
def get_custom_dns_config(env):
|
def get_custom_dns_config(env, only_real_records=False):
|
||||||
try:
|
try:
|
||||||
custom_dns = rtyaml.load(open(os.path.join(env['STORAGE_ROOT'], 'dns/custom.yaml')))
|
custom_dns = rtyaml.load(open(os.path.join(env['STORAGE_ROOT'], 'dns/custom.yaml')))
|
||||||
if not isinstance(custom_dns, dict): raise ValueError() # caught below
|
if not isinstance(custom_dns, dict): raise ValueError() # caught below
|
||||||
@@ -691,6 +812,8 @@ def get_custom_dns_config(env):
|
|||||||
return [ ]
|
return [ ]
|
||||||
|
|
||||||
for qname, value in custom_dns.items():
|
for qname, value in custom_dns.items():
|
||||||
|
if qname == "_secondary_nameserver" and only_real_records: continue # skip fake record
|
||||||
|
|
||||||
# Short form. Mapping a domain name to a string is short-hand
|
# Short form. Mapping a domain name to a string is short-hand
|
||||||
# for creating A records.
|
# for creating A records.
|
||||||
if isinstance(value, str):
|
if isinstance(value, str):
|
||||||
@@ -873,10 +996,15 @@ def get_secondary_dns(custom_dns, mode=None):
|
|||||||
|
|
||||||
# This is a hostname. Before including in zone xfr lines,
|
# This is a hostname. Before including in zone xfr lines,
|
||||||
# resolve to an IP address. Otherwise just return the hostname.
|
# resolve to an IP address. Otherwise just return the hostname.
|
||||||
|
# It may not resolve to IPv6, so don't throw an exception if it
|
||||||
|
# doesn't.
|
||||||
if not hostname.startswith("xfr:"):
|
if not hostname.startswith("xfr:"):
|
||||||
if mode == "xfr":
|
if mode == "xfr":
|
||||||
response = dns.resolver.query(hostname+'.', "A")
|
response = dns.resolver.query(hostname+'.', "A", raise_on_no_answer=False)
|
||||||
hostname = str(response[0])
|
values.extend(map(str, response))
|
||||||
|
response = dns.resolver.query(hostname+'.', "AAAA", raise_on_no_answer=False)
|
||||||
|
values.extend(map(str, response))
|
||||||
|
continue
|
||||||
values.append(hostname)
|
values.append(hostname)
|
||||||
|
|
||||||
# This is a zone-xfer-only IP address. Do not return if
|
# This is a zone-xfer-only IP address. Do not return if
|
||||||
@@ -898,15 +1026,20 @@ def set_secondary_dns(hostnames, env):
|
|||||||
# Resolve hostname.
|
# Resolve hostname.
|
||||||
try:
|
try:
|
||||||
response = resolver.query(item, "A")
|
response = resolver.query(item, "A")
|
||||||
|
except (dns.resolver.NoNameservers, dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
|
||||||
|
try:
|
||||||
|
response = resolver.query(item, "AAAA")
|
||||||
except (dns.resolver.NoNameservers, dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
|
except (dns.resolver.NoNameservers, dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
|
||||||
raise ValueError("Could not resolve the IP address of %s." % item)
|
raise ValueError("Could not resolve the IP address of %s." % item)
|
||||||
else:
|
else:
|
||||||
# Validate IP address.
|
# Validate IP address.
|
||||||
try:
|
try:
|
||||||
|
if "/" in item[4:]:
|
||||||
|
v = ipaddress.ip_network(item[4:]) # raises a ValueError if there's a problem
|
||||||
|
else:
|
||||||
v = ipaddress.ip_address(item[4:]) # raises a ValueError if there's a problem
|
v = ipaddress.ip_address(item[4:]) # raises a ValueError if there's a problem
|
||||||
if not isinstance(v, ipaddress.IPv4Address): raise ValueError("That's an IPv6 address.")
|
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise ValueError("'%s' is not an IPv4 address." % item[4:])
|
raise ValueError("'%s' is not an IPv4 or IPv6 address or subnet." % item[4:])
|
||||||
|
|
||||||
# Set.
|
# Set.
|
||||||
set_custom_dns_record("_secondary_nameserver", "A", " ".join(hostnames), "set", env)
|
set_custom_dns_record("_secondary_nameserver", "A", " ".join(hostnames), "set", env)
|
||||||
|
|||||||
@@ -18,13 +18,13 @@ import utils
|
|||||||
|
|
||||||
|
|
||||||
LOG_FILES = (
|
LOG_FILES = (
|
||||||
'/var/log/mail.log',
|
|
||||||
'/var/log/mail.log.1',
|
|
||||||
'/var/log/mail.log.2.gz',
|
|
||||||
'/var/log/mail.log.3.gz',
|
|
||||||
'/var/log/mail.log.4.gz',
|
|
||||||
'/var/log/mail.log.5.gz',
|
|
||||||
'/var/log/mail.log.6.gz',
|
'/var/log/mail.log.6.gz',
|
||||||
|
'/var/log/mail.log.5.gz',
|
||||||
|
'/var/log/mail.log.4.gz',
|
||||||
|
'/var/log/mail.log.3.gz',
|
||||||
|
'/var/log/mail.log.2.gz',
|
||||||
|
'/var/log/mail.log.1',
|
||||||
|
'/var/log/mail.log',
|
||||||
)
|
)
|
||||||
|
|
||||||
TIME_DELTAS = OrderedDict([
|
TIME_DELTAS = OrderedDict([
|
||||||
@@ -44,9 +44,8 @@ TIME_DELTAS = OrderedDict([
|
|||||||
('today', datetime.datetime.now() - datetime.datetime.now().replace(hour=0, minute=0, second=0))
|
('today', datetime.datetime.now() - datetime.datetime.now().replace(hour=0, minute=0, second=0))
|
||||||
])
|
])
|
||||||
|
|
||||||
# Start date > end date!
|
END_DATE = NOW = datetime.datetime.now()
|
||||||
START_DATE = datetime.datetime.now()
|
START_DATE = None
|
||||||
END_DATE = None
|
|
||||||
|
|
||||||
VERBOSE = False
|
VERBOSE = False
|
||||||
|
|
||||||
@@ -80,7 +79,7 @@ def scan_files(collector):
|
|||||||
print("Processing file", fn, "...")
|
print("Processing file", fn, "...")
|
||||||
fn = tmp_file.name if tmp_file else fn
|
fn = tmp_file.name if tmp_file else fn
|
||||||
|
|
||||||
for line in reverse_readline(fn):
|
for line in readline(fn):
|
||||||
if scan_mail_log_line(line.strip(), collector) is False:
|
if scan_mail_log_line(line.strip(), collector) is False:
|
||||||
if stop_scan:
|
if stop_scan:
|
||||||
return
|
return
|
||||||
@@ -121,7 +120,7 @@ def scan_mail_log(env):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
print("Scanning logs from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}".format(
|
print("Scanning logs from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}".format(
|
||||||
END_DATE, START_DATE)
|
START_DATE, END_DATE)
|
||||||
)
|
)
|
||||||
|
|
||||||
# Scan the lines in the log files until the date goes out of range
|
# Scan the lines in the log files until the date goes out of range
|
||||||
@@ -253,7 +252,7 @@ def scan_mail_log(env):
|
|||||||
|
|
||||||
if collector["postgrey"]:
|
if collector["postgrey"]:
|
||||||
msg = "Greylisted Email {:%Y-%m-%d %H:%M:%S} and {:%Y-%m-%d %H:%M:%S}"
|
msg = "Greylisted Email {:%Y-%m-%d %H:%M:%S} and {:%Y-%m-%d %H:%M:%S}"
|
||||||
print_header(msg.format(END_DATE, START_DATE))
|
print_header(msg.format(START_DATE, END_DATE))
|
||||||
|
|
||||||
print(textwrap.fill(
|
print(textwrap.fill(
|
||||||
"The following mail was greylisted, meaning the emails were temporarily rejected. "
|
"The following mail was greylisted, meaning the emails were temporarily rejected. "
|
||||||
@@ -291,7 +290,7 @@ def scan_mail_log(env):
|
|||||||
|
|
||||||
if collector["rejected"]:
|
if collector["rejected"]:
|
||||||
msg = "Blocked Email {:%Y-%m-%d %H:%M:%S} and {:%Y-%m-%d %H:%M:%S}"
|
msg = "Blocked Email {:%Y-%m-%d %H:%M:%S} and {:%Y-%m-%d %H:%M:%S}"
|
||||||
print_header(msg.format(END_DATE, START_DATE))
|
print_header(msg.format(START_DATE, END_DATE))
|
||||||
|
|
||||||
data = OrderedDict(sorted(collector["rejected"].items(), key=email_sort))
|
data = OrderedDict(sorted(collector["rejected"].items(), key=email_sort))
|
||||||
|
|
||||||
@@ -344,16 +343,22 @@ def scan_mail_log_line(line, collector):
|
|||||||
|
|
||||||
# Replaced the dateutil parser for a less clever way of parser that is roughly 4 times faster.
|
# Replaced the dateutil parser for a less clever way of parser that is roughly 4 times faster.
|
||||||
# date = dateutil.parser.parse(date)
|
# date = dateutil.parser.parse(date)
|
||||||
date = datetime.datetime.strptime(date, '%b %d %H:%M:%S')
|
|
||||||
date = date.replace(START_DATE.year)
|
# strptime fails on Feb 29 with ValueError: day is out of range for month if correct year is not provided.
|
||||||
|
# See https://bugs.python.org/issue26460
|
||||||
|
date = datetime.datetime.strptime(str(NOW.year) + ' ' + date, '%Y %b %d %H:%M:%S')
|
||||||
|
# if log date in future, step back a year
|
||||||
|
if date > NOW:
|
||||||
|
date = date.replace(year = NOW.year - 1)
|
||||||
|
#print("date:", date)
|
||||||
|
|
||||||
# Check if the found date is within the time span we are scanning
|
# Check if the found date is within the time span we are scanning
|
||||||
if date > START_DATE:
|
if date > END_DATE:
|
||||||
# Don't process, but continue
|
|
||||||
return True
|
|
||||||
elif date < END_DATE:
|
|
||||||
# Don't process, and halt
|
# Don't process, and halt
|
||||||
return False
|
return False
|
||||||
|
elif date < START_DATE:
|
||||||
|
# Don't process, but continue
|
||||||
|
return True
|
||||||
|
|
||||||
if service == "postfix/submission/smtpd":
|
if service == "postfix/submission/smtpd":
|
||||||
if SCAN_OUT:
|
if SCAN_OUT:
|
||||||
@@ -453,9 +458,9 @@ def scan_postfix_smtpd_line(date, log, collector):
|
|||||||
if m:
|
if m:
|
||||||
message = "domain blocked: " + m.group(2)
|
message = "domain blocked: " + m.group(2)
|
||||||
|
|
||||||
if data["latest"] is None:
|
if data["earliest"] is None:
|
||||||
data["latest"] = date
|
|
||||||
data["earliest"] = date
|
data["earliest"] = date
|
||||||
|
data["latest"] = date
|
||||||
data["blocked"].append((date, sender, message))
|
data["blocked"].append((date, sender, message))
|
||||||
|
|
||||||
collector["rejected"][user] = data
|
collector["rejected"][user] = data
|
||||||
@@ -487,9 +492,9 @@ def add_login(user, date, protocol_name, host, collector):
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
if data["latest"] is None:
|
if data["earliest"] is None:
|
||||||
data["latest"] = date
|
|
||||||
data["earliest"] = date
|
data["earliest"] = date
|
||||||
|
data["latest"] = date
|
||||||
|
|
||||||
data["totals_by_protocol"][protocol_name] += 1
|
data["totals_by_protocol"][protocol_name] += 1
|
||||||
data["totals_by_protocol_and_host"][(protocol_name, host)] += 1
|
data["totals_by_protocol_and_host"][(protocol_name, host)] += 1
|
||||||
@@ -528,9 +533,9 @@ def scan_postfix_lmtp_line(date, log, collector):
|
|||||||
data["received_count"] += 1
|
data["received_count"] += 1
|
||||||
data["activity-by-hour"][date.hour] += 1
|
data["activity-by-hour"][date.hour] += 1
|
||||||
|
|
||||||
if data["latest"] is None:
|
if data["earliest"] is None:
|
||||||
data["latest"] = date
|
|
||||||
data["earliest"] = date
|
data["earliest"] = date
|
||||||
|
data["latest"] = date
|
||||||
|
|
||||||
collector["received_mail"][user] = data
|
collector["received_mail"][user] = data
|
||||||
|
|
||||||
@@ -544,8 +549,9 @@ def scan_postfix_submission_line(date, log, collector):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
# Match both the 'plain' and 'login' sasl methods, since both authentication methods are
|
# Match both the 'plain' and 'login' sasl methods, since both authentication methods are
|
||||||
# allowed by Dovecot
|
# allowed by Dovecot. Exclude trailing comma after the username when additional fields
|
||||||
m = re.match("([A-Z0-9]+): client=(\S+), sasl_method=(PLAIN|LOGIN), sasl_username=(\S+)", log)
|
# follow after.
|
||||||
|
m = re.match("([A-Z0-9]+): client=(\S+), sasl_method=(PLAIN|LOGIN), sasl_username=(\S+)(?<!,)", log)
|
||||||
|
|
||||||
if m:
|
if m:
|
||||||
_, client, method, user = m.groups()
|
_, client, method, user = m.groups()
|
||||||
@@ -567,9 +573,9 @@ def scan_postfix_submission_line(date, log, collector):
|
|||||||
data["hosts"].add(client)
|
data["hosts"].add(client)
|
||||||
data["activity-by-hour"][date.hour] += 1
|
data["activity-by-hour"][date.hour] += 1
|
||||||
|
|
||||||
if data["latest"] is None:
|
if data["earliest"] is None:
|
||||||
data["latest"] = date
|
|
||||||
data["earliest"] = date
|
data["earliest"] = date
|
||||||
|
data["latest"] = date
|
||||||
|
|
||||||
collector["sent_mail"][user] = data
|
collector["sent_mail"][user] = data
|
||||||
|
|
||||||
@@ -578,42 +584,15 @@ def scan_postfix_submission_line(date, log, collector):
|
|||||||
|
|
||||||
# Utility functions
|
# Utility functions
|
||||||
|
|
||||||
def reverse_readline(filename, buf_size=8192):
|
def readline(filename):
|
||||||
""" A generator that returns the lines of a file in reverse order
|
""" A generator that returns the lines of a file
|
||||||
|
|
||||||
http://stackoverflow.com/a/23646049/801870
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
with open(filename, errors='replace') as file:
|
||||||
with open(filename) as fh:
|
while True:
|
||||||
segment = None
|
line = file.readline()
|
||||||
offset = 0
|
if not line:
|
||||||
fh.seek(0, os.SEEK_END)
|
break
|
||||||
file_size = remaining_size = fh.tell()
|
yield line
|
||||||
while remaining_size > 0:
|
|
||||||
offset = min(file_size, offset + buf_size)
|
|
||||||
fh.seek(file_size - offset)
|
|
||||||
buff = fh.read(min(remaining_size, buf_size))
|
|
||||||
remaining_size -= buf_size
|
|
||||||
lines = buff.split('\n')
|
|
||||||
# the first line of the buffer is probably not a complete line so
|
|
||||||
# we'll save it and append it to the last line of the next buffer
|
|
||||||
# we read
|
|
||||||
if segment is not None:
|
|
||||||
# if the previous chunk starts right from the beginning of line
|
|
||||||
# do not concat the segment to the last line of new chunk
|
|
||||||
# instead, yield the segment first
|
|
||||||
if buff[-1] is not '\n':
|
|
||||||
lines[-1] += segment
|
|
||||||
else:
|
|
||||||
yield segment
|
|
||||||
segment = lines[0]
|
|
||||||
for index in range(len(lines) - 1, 0, -1):
|
|
||||||
if len(lines[index]):
|
|
||||||
yield lines[index]
|
|
||||||
# Don't yield None if the file was empty
|
|
||||||
if segment is not None:
|
|
||||||
yield segment
|
|
||||||
|
|
||||||
|
|
||||||
def user_match(user):
|
def user_match(user):
|
||||||
@@ -627,7 +606,7 @@ def email_sort(email):
|
|||||||
|
|
||||||
|
|
||||||
def valid_date(string):
|
def valid_date(string):
|
||||||
""" Validate the given date string fetched from the --startdate argument """
|
""" Validate the given date string fetched from the --enddate argument """
|
||||||
try:
|
try:
|
||||||
date = dateutil.parser.parse(string)
|
date = dateutil.parser.parse(string)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
@@ -841,12 +820,14 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
parser.add_argument("-t", "--timespan", choices=TIME_DELTAS.keys(), default='today',
|
parser.add_argument("-t", "--timespan", choices=TIME_DELTAS.keys(), default='today',
|
||||||
metavar='<time span>',
|
metavar='<time span>',
|
||||||
help="Time span to scan, going back from the start date. Possible values: "
|
help="Time span to scan, going back from the end date. Possible values: "
|
||||||
"{}. Defaults to 'today'.".format(", ".join(list(TIME_DELTAS.keys()))))
|
"{}. Defaults to 'today'.".format(", ".join(list(TIME_DELTAS.keys()))))
|
||||||
parser.add_argument("-d", "--startdate", action="store", dest="startdate",
|
# keep the --startdate arg for backward compatibility
|
||||||
type=valid_date, metavar='<start date>',
|
parser.add_argument("-d", "--enddate", "--startdate", action="store", dest="enddate",
|
||||||
help="Date and time to start scanning the log file from. If no date is "
|
type=valid_date, metavar='<end date>',
|
||||||
"provided, scanning will start from the current date and time.")
|
help="Date and time to end scanning the log file. If no date is "
|
||||||
|
"provided, scanning will end at the current date and time. "
|
||||||
|
"Alias --startdate is for compatibility.")
|
||||||
parser.add_argument("-u", "--users", action="store", dest="users",
|
parser.add_argument("-u", "--users", action="store", dest="users",
|
||||||
metavar='<email1,email2,email...>',
|
metavar='<email1,email2,email...>',
|
||||||
help="Comma separated list of (partial) email addresses to filter the "
|
help="Comma separated list of (partial) email addresses to filter the "
|
||||||
@@ -858,13 +839,13 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
if args.startdate is not None:
|
if args.enddate is not None:
|
||||||
START_DATE = args.startdate
|
END_DATE = args.enddate
|
||||||
if args.timespan == 'today':
|
if args.timespan == 'today':
|
||||||
args.timespan = 'day'
|
args.timespan = 'day'
|
||||||
print("Setting start date to {}".format(START_DATE))
|
print("Setting end date to {}".format(END_DATE))
|
||||||
|
|
||||||
END_DATE = START_DATE - TIME_DELTAS[args.timespan]
|
START_DATE = END_DATE - TIME_DELTAS[args.timespan]
|
||||||
|
|
||||||
VERBOSE = args.verbose
|
VERBOSE = args.verbose
|
||||||
|
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ import idna
|
|||||||
|
|
||||||
def validate_email(email, mode=None):
|
def validate_email(email, mode=None):
|
||||||
# Checks that an email address is syntactically valid. Returns True/False.
|
# Checks that an email address is syntactically valid. Returns True/False.
|
||||||
# Until Postfix supports SMTPUTF8, an email address may contain ASCII
|
# An email address may contain ASCII characters only because Dovecot's
|
||||||
# characters only; IDNs must be IDNA-encoded.
|
# authentication mechanism gets confused with other character encodings.
|
||||||
#
|
#
|
||||||
# When mode=="user", we're checking that this can be a user account name.
|
# When mode=="user", we're checking that this can be a user account name.
|
||||||
# Dovecot has tighter restrictions - letters, numbers, underscore, and
|
# Dovecot has tighter restrictions - letters, numbers, underscore, and
|
||||||
@@ -186,9 +186,9 @@ def get_admins(env):
|
|||||||
return users
|
return users
|
||||||
|
|
||||||
def get_mail_aliases(env):
|
def get_mail_aliases(env):
|
||||||
# Returns a sorted list of tuples of (address, forward-tos, permitted-senders).
|
# Returns a sorted list of tuples of (address, forward-tos, permitted-senders, auto).
|
||||||
c = open_database(env)
|
c = open_database(env)
|
||||||
c.execute('SELECT source, destination, permitted_senders FROM aliases')
|
c.execute('SELECT source, destination, permitted_senders, 0 as auto FROM aliases UNION SELECT source, destination, permitted_senders, 1 as auto FROM auto_aliases')
|
||||||
aliases = { row[0]: row for row in c.fetchall() } # make dict
|
aliases = { row[0]: row for row in c.fetchall() } # make dict
|
||||||
|
|
||||||
# put in a canonical order: sort by domain, then by email address lexicographically
|
# put in a canonical order: sort by domain, then by email address lexicographically
|
||||||
@@ -208,7 +208,7 @@ def get_mail_aliases_ex(env):
|
|||||||
# address_display: "name@domain.tld", # full Unicode
|
# address_display: "name@domain.tld", # full Unicode
|
||||||
# forwards_to: ["user1@domain.com", "receiver-only1@domain.com", ...],
|
# forwards_to: ["user1@domain.com", "receiver-only1@domain.com", ...],
|
||||||
# permitted_senders: ["user1@domain.com", "sender-only1@domain.com", ...] OR null,
|
# permitted_senders: ["user1@domain.com", "sender-only1@domain.com", ...] OR null,
|
||||||
# required: True|False
|
# auto: True|False
|
||||||
# },
|
# },
|
||||||
# ...
|
# ...
|
||||||
# ]
|
# ]
|
||||||
@@ -216,12 +216,13 @@ def get_mail_aliases_ex(env):
|
|||||||
# ...
|
# ...
|
||||||
# ]
|
# ]
|
||||||
|
|
||||||
required_aliases = get_required_aliases(env)
|
|
||||||
domains = {}
|
domains = {}
|
||||||
for address, forwards_to, permitted_senders in get_mail_aliases(env):
|
for address, forwards_to, permitted_senders, auto in get_mail_aliases(env):
|
||||||
|
# skip auto domain maps since these are not informative in the control panel's aliases list
|
||||||
|
if auto and address.startswith("@"): continue
|
||||||
|
|
||||||
# get alias info
|
# get alias info
|
||||||
domain = get_domain(address)
|
domain = get_domain(address)
|
||||||
required = (address in required_aliases)
|
|
||||||
|
|
||||||
# add to list
|
# add to list
|
||||||
if not domain in domains:
|
if not domain in domains:
|
||||||
@@ -234,7 +235,7 @@ def get_mail_aliases_ex(env):
|
|||||||
"address_display": prettify_idn_email_address(address),
|
"address_display": prettify_idn_email_address(address),
|
||||||
"forwards_to": [prettify_idn_email_address(r.strip()) for r in forwards_to.split(",")],
|
"forwards_to": [prettify_idn_email_address(r.strip()) for r in forwards_to.split(",")],
|
||||||
"permitted_senders": [prettify_idn_email_address(s.strip()) for s in permitted_senders.split(",")] if permitted_senders is not None else None,
|
"permitted_senders": [prettify_idn_email_address(s.strip()) for s in permitted_senders.split(",")] if permitted_senders is not None else None,
|
||||||
"required": required,
|
"auto": bool(auto),
|
||||||
})
|
})
|
||||||
|
|
||||||
# Sort domains.
|
# Sort domains.
|
||||||
@@ -242,7 +243,7 @@ def get_mail_aliases_ex(env):
|
|||||||
|
|
||||||
# Sort aliases within each domain first by required-ness then lexicographically by address.
|
# Sort aliases within each domain first by required-ness then lexicographically by address.
|
||||||
for domain in domains:
|
for domain in domains:
|
||||||
domain["aliases"].sort(key = lambda alias : (alias["required"], alias["address"]))
|
domain["aliases"].sort(key = lambda alias : (alias["auto"], alias["address"]))
|
||||||
return domains
|
return domains
|
||||||
|
|
||||||
def get_domain(emailaddr, as_unicode=True):
|
def get_domain(emailaddr, as_unicode=True):
|
||||||
@@ -258,13 +259,16 @@ def get_domain(emailaddr, as_unicode=True):
|
|||||||
pass
|
pass
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
def get_mail_domains(env, filter_aliases=lambda alias : True):
|
def get_mail_domains(env, filter_aliases=lambda alias : True, users_only=False):
|
||||||
# Returns the domain names (IDNA-encoded) of all of the email addresses
|
# Returns the domain names (IDNA-encoded) of all of the email addresses
|
||||||
# configured on the system.
|
# configured on the system. If users_only is True, only return domains
|
||||||
return set(
|
# with email addresses that correspond to user accounts. Exclude Unicode
|
||||||
[get_domain(login, as_unicode=False) for login in get_mail_users(env)]
|
# forms of domain names listed in the automatic aliases table.
|
||||||
+ [get_domain(address, as_unicode=False) for address, *_ in get_mail_aliases(env) if filter_aliases(address) ]
|
domains = []
|
||||||
)
|
domains.extend([get_domain(login, as_unicode=False) for login in get_mail_users(env)])
|
||||||
|
if not users_only:
|
||||||
|
domains.extend([get_domain(address, as_unicode=False) for address, _, _, auto in get_mail_aliases(env) if filter_aliases(address) and not auto ])
|
||||||
|
return set(domains)
|
||||||
|
|
||||||
def add_mail_user(email, pw, privs, env):
|
def add_mail_user(email, pw, privs, env):
|
||||||
# validate email
|
# validate email
|
||||||
@@ -510,6 +514,13 @@ def remove_mail_alias(address, env, do_kick=True):
|
|||||||
# Update things in case any domains are removed.
|
# Update things in case any domains are removed.
|
||||||
return kick(env, "alias removed")
|
return kick(env, "alias removed")
|
||||||
|
|
||||||
|
def add_auto_aliases(aliases, env):
|
||||||
|
conn, c = open_database(env, with_connection=True)
|
||||||
|
c.execute("DELETE FROM auto_aliases");
|
||||||
|
for source, destination in aliases.items():
|
||||||
|
c.execute("INSERT INTO auto_aliases (source, destination) VALUES (?, ?)", (source, destination))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
def get_system_administrator(env):
|
def get_system_administrator(env):
|
||||||
return "administrator@" + env['PRIMARY_HOSTNAME']
|
return "administrator@" + env['PRIMARY_HOSTNAME']
|
||||||
|
|
||||||
@@ -553,39 +564,34 @@ def kick(env, mail_result=None):
|
|||||||
if mail_result is not None:
|
if mail_result is not None:
|
||||||
results.append(mail_result + "\n")
|
results.append(mail_result + "\n")
|
||||||
|
|
||||||
# Ensure every required alias exists.
|
auto_aliases = { }
|
||||||
|
|
||||||
existing_users = get_mail_users(env)
|
# Mape required aliases to the administrator alias (which should be created manually).
|
||||||
existing_alias_records = get_mail_aliases(env)
|
|
||||||
existing_aliases = set(a for a, *_ in existing_alias_records) # just first entry in tuple
|
|
||||||
required_aliases = get_required_aliases(env)
|
|
||||||
|
|
||||||
def ensure_admin_alias_exists(address):
|
|
||||||
# If a user account exists with that address, we're good.
|
|
||||||
if address in existing_users:
|
|
||||||
return
|
|
||||||
|
|
||||||
# If the alias already exists, we're good.
|
|
||||||
if address in existing_aliases:
|
|
||||||
return
|
|
||||||
|
|
||||||
# Doesn't exist.
|
|
||||||
administrator = get_system_administrator(env)
|
administrator = get_system_administrator(env)
|
||||||
if address == administrator: return # don't make an alias from the administrator to itself --- this alias must be created manually
|
required_aliases = get_required_aliases(env)
|
||||||
add_mail_alias(address, administrator, "", env, do_kick=False)
|
for alias in required_aliases:
|
||||||
if administrator not in existing_aliases: return # don't report the alias in output if the administrator alias isn't in yet -- this is a hack to supress confusing output on initial setup
|
if alias == administrator: continue # don't make an alias from the administrator to itself --- this alias must be created manually
|
||||||
results.append("added alias %s (=> %s)\n" % (address, administrator))
|
auto_aliases[alias] = administrator
|
||||||
|
|
||||||
for address in required_aliases:
|
# Add domain maps from Unicode forms of IDNA domains to the ASCII forms stored in the alias table.
|
||||||
ensure_admin_alias_exists(address)
|
for domain in get_mail_domains(env):
|
||||||
|
try:
|
||||||
|
domain_unicode = idna.decode(domain.encode("ascii"))
|
||||||
|
if domain == domain_unicode: continue # not an IDNA/Unicode domain
|
||||||
|
auto_aliases["@" + domain_unicode] = "@" + domain
|
||||||
|
except (ValueError, UnicodeError, idna.IDNAError):
|
||||||
|
continue
|
||||||
|
|
||||||
# Remove auto-generated postmaster/admin on domains we no
|
add_auto_aliases(auto_aliases, env)
|
||||||
# longer have any other email addresses for.
|
|
||||||
for address, forwards_to, *_ in existing_alias_records:
|
# Remove auto-generated postmaster/admin/abuse alises from the main aliases table.
|
||||||
|
# They are now stored in the auto_aliases table.
|
||||||
|
for address, forwards_to, permitted_senders, auto in get_mail_aliases(env):
|
||||||
user, domain = address.split("@")
|
user, domain = address.split("@")
|
||||||
if user in ("postmaster", "admin", "abuse") \
|
if user in ("postmaster", "admin", "abuse") \
|
||||||
and address not in required_aliases \
|
and address not in required_aliases \
|
||||||
and forwards_to == get_system_administrator(env):
|
and forwards_to == get_system_administrator(env) \
|
||||||
|
and not auto:
|
||||||
remove_mail_alias(address, env, do_kick=False)
|
remove_mail_alias(address, env, do_kick=False)
|
||||||
results.append("removed alias %s (was to %s; domain no longer used for email)\n" % (address, forwards_to))
|
results.append("removed alias %s (was to %s; domain no longer used for email)\n" % (address, forwards_to))
|
||||||
|
|
||||||
@@ -603,12 +609,9 @@ def validate_password(pw):
|
|||||||
# validate password
|
# validate password
|
||||||
if pw.strip() == "":
|
if pw.strip() == "":
|
||||||
raise ValueError("No password provided.")
|
raise ValueError("No password provided.")
|
||||||
if re.search(r"[\s]", pw):
|
|
||||||
raise ValueError("Passwords cannot contain spaces.")
|
|
||||||
if len(pw) < 8:
|
if len(pw) < 8:
|
||||||
raise ValueError("Passwords must be at least eight characters.")
|
raise ValueError("Passwords must be at least eight characters.")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import sys
|
import sys
|
||||||
if len(sys.argv) > 2 and sys.argv[1] == "validate-email":
|
if len(sys.argv) > 2 and sys.argv[1] == "validate-email":
|
||||||
|
|||||||
141
management/mfa.py
Normal file
141
management/mfa.py
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
import base64
|
||||||
|
import hmac
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import pyotp
|
||||||
|
import qrcode
|
||||||
|
|
||||||
|
from mailconfig import open_database
|
||||||
|
|
||||||
|
def get_user_id(email, c):
|
||||||
|
c.execute('SELECT id FROM users WHERE email=?', (email,))
|
||||||
|
r = c.fetchone()
|
||||||
|
if not r: raise ValueError("User does not exist.")
|
||||||
|
return r[0]
|
||||||
|
|
||||||
|
def get_mfa_state(email, env):
|
||||||
|
c = open_database(env)
|
||||||
|
c.execute('SELECT id, type, secret, mru_token, label FROM mfa WHERE user_id=?', (get_user_id(email, c),))
|
||||||
|
return [
|
||||||
|
{ "id": r[0], "type": r[1], "secret": r[2], "mru_token": r[3], "label": r[4] }
|
||||||
|
for r in c.fetchall()
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_public_mfa_state(email, env):
|
||||||
|
mfa_state = get_mfa_state(email, env)
|
||||||
|
return [
|
||||||
|
{ "id": s["id"], "type": s["type"], "label": s["label"] }
|
||||||
|
for s in mfa_state
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_hash_mfa_state(email, env):
|
||||||
|
mfa_state = get_mfa_state(email, env)
|
||||||
|
return [
|
||||||
|
{ "id": s["id"], "type": s["type"], "secret": s["secret"] }
|
||||||
|
for s in mfa_state
|
||||||
|
]
|
||||||
|
|
||||||
|
def enable_mfa(email, type, secret, token, label, env):
|
||||||
|
if type == "totp":
|
||||||
|
validate_totp_secret(secret)
|
||||||
|
# Sanity check with the provide current token.
|
||||||
|
totp = pyotp.TOTP(secret)
|
||||||
|
if not totp.verify(token, valid_window=1):
|
||||||
|
raise ValueError("Invalid token.")
|
||||||
|
else:
|
||||||
|
raise ValueError("Invalid MFA type.")
|
||||||
|
|
||||||
|
conn, c = open_database(env, with_connection=True)
|
||||||
|
c.execute('INSERT INTO mfa (user_id, type, secret, label) VALUES (?, ?, ?, ?)', (get_user_id(email, c), type, secret, label))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
def set_mru_token(email, mfa_id, token, env):
|
||||||
|
conn, c = open_database(env, with_connection=True)
|
||||||
|
c.execute('UPDATE mfa SET mru_token=? WHERE user_id=? AND id=?', (token, get_user_id(email, c), mfa_id))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
def disable_mfa(email, mfa_id, env):
|
||||||
|
conn, c = open_database(env, with_connection=True)
|
||||||
|
if mfa_id is None:
|
||||||
|
# Disable all MFA for a user.
|
||||||
|
c.execute('DELETE FROM mfa WHERE user_id=?', (get_user_id(email, c),))
|
||||||
|
else:
|
||||||
|
# Disable a particular MFA mode for a user.
|
||||||
|
c.execute('DELETE FROM mfa WHERE user_id=? AND id=?', (get_user_id(email, c), mfa_id))
|
||||||
|
conn.commit()
|
||||||
|
return c.rowcount > 0
|
||||||
|
|
||||||
|
def validate_totp_secret(secret):
|
||||||
|
if type(secret) != str or secret.strip() == "":
|
||||||
|
raise ValueError("No secret provided.")
|
||||||
|
if len(secret) != 32:
|
||||||
|
raise ValueError("Secret should be a 32 characters base32 string")
|
||||||
|
|
||||||
|
def provision_totp(email, env):
|
||||||
|
# Make a new secret.
|
||||||
|
secret = base64.b32encode(os.urandom(20)).decode('utf-8')
|
||||||
|
validate_totp_secret(secret) # sanity check
|
||||||
|
|
||||||
|
# Make a URI that we encode within a QR code.
|
||||||
|
uri = pyotp.TOTP(secret).provisioning_uri(
|
||||||
|
name=email,
|
||||||
|
issuer_name=env["PRIMARY_HOSTNAME"] + " Mail-in-a-Box Control Panel"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Generate a QR code as a base64-encode PNG image.
|
||||||
|
qr = qrcode.make(uri)
|
||||||
|
byte_arr = io.BytesIO()
|
||||||
|
qr.save(byte_arr, format='PNG')
|
||||||
|
png_b64 = base64.b64encode(byte_arr.getvalue()).decode('utf-8')
|
||||||
|
|
||||||
|
return {
|
||||||
|
"type": "totp",
|
||||||
|
"secret": secret,
|
||||||
|
"qr_code_base64": png_b64
|
||||||
|
}
|
||||||
|
|
||||||
|
def validate_auth_mfa(email, request, env):
|
||||||
|
# Validates that a login request satisfies any MFA modes
|
||||||
|
# that have been enabled for the user's account. Returns
|
||||||
|
# a tuple (status, [hints]). status is True for a successful
|
||||||
|
# MFA login, False for a missing token. If status is False,
|
||||||
|
# hints is an array of codes that indicate what the user
|
||||||
|
# can try. Possible codes are:
|
||||||
|
# "missing-totp-token"
|
||||||
|
# "invalid-totp-token"
|
||||||
|
|
||||||
|
mfa_state = get_mfa_state(email, env)
|
||||||
|
|
||||||
|
# If no MFA modes are added, return True.
|
||||||
|
if len(mfa_state) == 0:
|
||||||
|
return (True, [])
|
||||||
|
|
||||||
|
# Try the enabled MFA modes.
|
||||||
|
hints = set()
|
||||||
|
for mfa_mode in mfa_state:
|
||||||
|
if mfa_mode["type"] == "totp":
|
||||||
|
# Check that a token is present in the X-Auth-Token header.
|
||||||
|
# If not, give a hint that one can be supplied.
|
||||||
|
token = request.headers.get('x-auth-token')
|
||||||
|
if not token:
|
||||||
|
hints.add("missing-totp-token")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Check for a replay attack.
|
||||||
|
if hmac.compare_digest(token, mfa_mode['mru_token'] or ""):
|
||||||
|
# If the token fails, skip this MFA mode.
|
||||||
|
hints.add("invalid-totp-token")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Check the token.
|
||||||
|
totp = pyotp.TOTP(mfa_mode["secret"])
|
||||||
|
if not totp.verify(token, valid_window=1):
|
||||||
|
hints.add("invalid-totp-token")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# On success, record the token to prevent a replay attack.
|
||||||
|
set_mru_token(email, mfa_mode['id'], token, env)
|
||||||
|
return (True, [])
|
||||||
|
|
||||||
|
# On a failed login, indicate failure and any hints for what the user can do instead.
|
||||||
|
return (False, list(hints))
|
||||||
@@ -180,7 +180,7 @@ def get_certificates_to_provision(env, limit_domains=None, show_valid_certs=True
|
|||||||
# for and subtract:
|
# for and subtract:
|
||||||
# * domains not in limit_domains if limit_domains is not empty
|
# * domains not in limit_domains if limit_domains is not empty
|
||||||
# * domains with custom "A" records, i.e. they are hosted elsewhere
|
# * domains with custom "A" records, i.e. they are hosted elsewhere
|
||||||
# * domains with actual "A" records that point elsewhere
|
# * domains with actual "A" records that point elsewhere (misconfiguration)
|
||||||
# * domains that already have certificates that will be valid for a while
|
# * domains that already have certificates that will be valid for a while
|
||||||
|
|
||||||
from web_update import get_web_domains
|
from web_update import get_web_domains
|
||||||
@@ -256,15 +256,41 @@ def provision_certificates(env, limit_domains):
|
|||||||
"result": "skipped",
|
"result": "skipped",
|
||||||
})
|
})
|
||||||
|
|
||||||
|
# Break into groups by DNS zone: Group every domain with its parent domain, if
|
||||||
|
# its parent domain is in the list of domains to request a certificate for.
|
||||||
|
# Start with the zones so that if the zone doesn't need a certificate itself,
|
||||||
|
# its children will still be grouped together. Sort the provision domains to
|
||||||
|
# put parents ahead of children.
|
||||||
|
# Since Let's Encrypt requests are limited to 100 domains at a time,
|
||||||
|
# we'll create a list of lists of domains where the inner lists have
|
||||||
|
# at most 100 items. By sorting we also get the DNS zone domain as the first
|
||||||
|
# entry in each list (unless we overflow beyond 100) which ends up as the
|
||||||
|
# primary domain listed in each certificate.
|
||||||
|
from dns_update import get_dns_zones
|
||||||
|
certs = { }
|
||||||
|
for zone, zonefile in get_dns_zones(env):
|
||||||
|
certs[zone] = [[]]
|
||||||
|
for domain in sort_domains(domains, env):
|
||||||
|
# Does the domain end with any domain we've seen so far.
|
||||||
|
for parent in certs.keys():
|
||||||
|
if domain.endswith("." + parent):
|
||||||
|
# Add this to the parent's list of domains.
|
||||||
|
# Start a new group if the list already has
|
||||||
|
# 100 items.
|
||||||
|
if len(certs[parent][-1]) == 100:
|
||||||
|
certs[parent].append([])
|
||||||
|
certs[parent][-1].append(domain)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
# This domain is not a child of any domain we've seen yet, so
|
||||||
|
# start a new group. This shouldn't happen since every zone
|
||||||
|
# was already added.
|
||||||
|
certs[domain] = [[domain]]
|
||||||
|
|
||||||
# Break into groups of up to 100 certificates at a time, which is Let's Encrypt's
|
# Flatten to a list of lists of domains (from a mapping). Remove empty
|
||||||
# limit for a single certificate. We'll sort to put related domains together.
|
# lists (zones with no domains that need certs).
|
||||||
max_domains_per_group = 100
|
certs = sum(certs.values(), [])
|
||||||
domains = sort_domains(domains, env)
|
certs = [_ for _ in certs if len(_) > 0]
|
||||||
certs = []
|
|
||||||
while len(domains) > 0:
|
|
||||||
certs.append( domains[:max_domains_per_group] )
|
|
||||||
domains = domains[max_domains_per_group:]
|
|
||||||
|
|
||||||
# Prepare to provision.
|
# Prepare to provision.
|
||||||
|
|
||||||
@@ -580,10 +606,10 @@ def check_certificate(domain, ssl_certificate, ssl_private_key, warn_if_expiring
|
|||||||
ndays = (cert_expiration_date-now).days
|
ndays = (cert_expiration_date-now).days
|
||||||
if not rounded_time or ndays <= 10:
|
if not rounded_time or ndays <= 10:
|
||||||
# Yikes better renew soon!
|
# Yikes better renew soon!
|
||||||
expiry_info = "The certificate expires in %d days on %s." % (ndays, cert_expiration_date.strftime("%x"))
|
expiry_info = "The certificate expires in %d days on %s." % (ndays, cert_expiration_date.date().isoformat())
|
||||||
else:
|
else:
|
||||||
# We'll renew it with Lets Encrypt.
|
# We'll renew it with Lets Encrypt.
|
||||||
expiry_info = "The certificate expires on %s." % cert_expiration_date.strftime("%x")
|
expiry_info = "The certificate expires on %s." % cert_expiration_date.date().isoformat()
|
||||||
|
|
||||||
if warn_if_expiring_soon and ndays <= warn_if_expiring_soon:
|
if warn_if_expiring_soon and ndays <= warn_if_expiring_soon:
|
||||||
# Warn on day 10 to give 4 days for us to automatically renew the
|
# Warn on day 10 to give 4 days for us to automatically renew the
|
||||||
|
|||||||
@@ -5,11 +5,13 @@
|
|||||||
# what to do next.
|
# what to do next.
|
||||||
|
|
||||||
import sys, os, os.path, re, subprocess, datetime, multiprocessing.pool
|
import sys, os, os.path, re, subprocess, datetime, multiprocessing.pool
|
||||||
|
import asyncio
|
||||||
|
|
||||||
import dns.reversename, dns.resolver
|
import dns.reversename, dns.resolver
|
||||||
import dateutil.parser, dateutil.tz
|
import dateutil.parser, dateutil.tz
|
||||||
import idna
|
import idna
|
||||||
import psutil
|
import psutil
|
||||||
|
import postfix_mta_sts_resolver.resolver
|
||||||
|
|
||||||
from dns_update import get_dns_zones, build_tlsa_record, get_custom_dns_config, get_secondary_dns, get_custom_dns_records
|
from dns_update import get_dns_zones, build_tlsa_record, get_custom_dns_config, get_secondary_dns, get_custom_dns_records
|
||||||
from web_update import get_web_domains, get_domains_with_a_records
|
from web_update import get_web_domains, get_domains_with_a_records
|
||||||
@@ -32,6 +34,7 @@ def get_services():
|
|||||||
{ "name": "SSH Login (ssh)", "port": get_ssh_port(), "public": True, },
|
{ "name": "SSH Login (ssh)", "port": get_ssh_port(), "public": True, },
|
||||||
{ "name": "Public DNS (nsd4)", "port": 53, "public": True, },
|
{ "name": "Public DNS (nsd4)", "port": 53, "public": True, },
|
||||||
{ "name": "Incoming Mail (SMTP/postfix)", "port": 25, "public": True, },
|
{ "name": "Incoming Mail (SMTP/postfix)", "port": 25, "public": True, },
|
||||||
|
{ "name": "Outgoing Mail (SMTP 465/postfix)", "port": 465, "public": True, },
|
||||||
{ "name": "Outgoing Mail (SMTP 587/postfix)", "port": 587, "public": True, },
|
{ "name": "Outgoing Mail (SMTP 587/postfix)", "port": 587, "public": True, },
|
||||||
#{ "name": "Postfix/master", "port": 10587, "public": True, },
|
#{ "name": "Postfix/master", "port": 10587, "public": True, },
|
||||||
{ "name": "IMAPS (dovecot)", "port": 993, "public": True, },
|
{ "name": "IMAPS (dovecot)", "port": 993, "public": True, },
|
||||||
@@ -40,7 +43,7 @@ def get_services():
|
|||||||
{ "name": "HTTPS Web (nginx)", "port": 443, "public": True, },
|
{ "name": "HTTPS Web (nginx)", "port": 443, "public": True, },
|
||||||
]
|
]
|
||||||
|
|
||||||
def run_checks(rounded_values, env, output, pool):
|
def run_checks(rounded_values, env, output, pool, domains_to_check=None):
|
||||||
# run systems checks
|
# run systems checks
|
||||||
output.add_heading("System")
|
output.add_heading("System")
|
||||||
|
|
||||||
@@ -61,7 +64,7 @@ def run_checks(rounded_values, env, output, pool):
|
|||||||
# perform other checks asynchronously
|
# perform other checks asynchronously
|
||||||
|
|
||||||
run_network_checks(env, output)
|
run_network_checks(env, output)
|
||||||
run_domain_checks(rounded_values, env, output, pool)
|
run_domain_checks(rounded_values, env, output, pool, domains_to_check=domains_to_check)
|
||||||
|
|
||||||
def get_ssh_port():
|
def get_ssh_port():
|
||||||
# Returns ssh port
|
# Returns ssh port
|
||||||
@@ -132,7 +135,7 @@ def check_service(i, service, env):
|
|||||||
|
|
||||||
# IPv4 ok but IPv6 failed. Try the PRIVATE_IPV6 address to see if the service is bound to the interface.
|
# IPv4 ok but IPv6 failed. Try the PRIVATE_IPV6 address to see if the service is bound to the interface.
|
||||||
elif service["port"] != 53 and try_connect(env["PRIVATE_IPV6"]):
|
elif service["port"] != 53 and try_connect(env["PRIVATE_IPV6"]):
|
||||||
output.print_error("%s is running (and available over IPv4 and the local IPv6 address), but it is not publicly accessible at %s:%d." % (service['name'], env['PUBLIC_IP'], service['port']))
|
output.print_error("%s is running (and available over IPv4 and the local IPv6 address), but it is not publicly accessible at %s:%d." % (service['name'], env['PUBLIC_IPV6'], service['port']))
|
||||||
else:
|
else:
|
||||||
output.print_error("%s is running and available over IPv4 but is not accessible over IPv6 at %s port %d." % (service['name'], env['PUBLIC_IPV6'], service['port']))
|
output.print_error("%s is running and available over IPv4 but is not accessible over IPv6 at %s port %d." % (service['name'], env['PUBLIC_IPV6'], service['port']))
|
||||||
|
|
||||||
@@ -250,6 +253,18 @@ def check_free_disk_space(rounded_values, env, output):
|
|||||||
if rounded_values: disk_msg = "The disk has less than 15% free space."
|
if rounded_values: disk_msg = "The disk has less than 15% free space."
|
||||||
output.print_error(disk_msg)
|
output.print_error(disk_msg)
|
||||||
|
|
||||||
|
# Check that there's only one duplicity cache. If there's more than one,
|
||||||
|
# it's probably no longer in use, and we can recommend clearing the cache
|
||||||
|
# to save space. The cache directory may not exist yet, which is OK.
|
||||||
|
backup_cache_path = os.path.join(env['STORAGE_ROOT'], 'backup/cache')
|
||||||
|
try:
|
||||||
|
backup_cache_count = len(os.listdir(backup_cache_path))
|
||||||
|
except:
|
||||||
|
backup_cache_count = 0
|
||||||
|
if backup_cache_count > 1:
|
||||||
|
output.print_warning("The backup cache directory {} has more than one backup target cache. Consider clearing this directory to save disk space."
|
||||||
|
.format(backup_cache_path))
|
||||||
|
|
||||||
def check_free_memory(rounded_values, env, output):
|
def check_free_memory(rounded_values, env, output):
|
||||||
# Check free memory.
|
# Check free memory.
|
||||||
percent_free = 100 - psutil.virtual_memory().percent
|
percent_free = 100 - psutil.virtual_memory().percent
|
||||||
@@ -291,12 +306,14 @@ def run_network_checks(env, output):
|
|||||||
zen = query_dns(rev_ip4+'.zen.spamhaus.org', 'A', nxdomain=None)
|
zen = query_dns(rev_ip4+'.zen.spamhaus.org', 'A', nxdomain=None)
|
||||||
if zen is None:
|
if zen is None:
|
||||||
output.print_ok("IP address is not blacklisted by zen.spamhaus.org.")
|
output.print_ok("IP address is not blacklisted by zen.spamhaus.org.")
|
||||||
|
elif zen == "[timeout]":
|
||||||
|
output.print_warning("Connection to zen.spamhaus.org timed out. We could not determine whether your server's IP address is blacklisted. Please try again later.")
|
||||||
else:
|
else:
|
||||||
output.print_error("""The IP address of this machine %s is listed in the Spamhaus Block List (code %s),
|
output.print_error("""The IP address of this machine %s is listed in the Spamhaus Block List (code %s),
|
||||||
which may prevent recipients from receiving your email. See http://www.spamhaus.org/query/ip/%s."""
|
which may prevent recipients from receiving your email. See http://www.spamhaus.org/query/ip/%s."""
|
||||||
% (env['PUBLIC_IP'], zen, env['PUBLIC_IP']))
|
% (env['PUBLIC_IP'], zen, env['PUBLIC_IP']))
|
||||||
|
|
||||||
def run_domain_checks(rounded_time, env, output, pool):
|
def run_domain_checks(rounded_time, env, output, pool, domains_to_check=None):
|
||||||
# Get the list of domains we handle mail for.
|
# Get the list of domains we handle mail for.
|
||||||
mail_domains = get_mail_domains(env)
|
mail_domains = get_mail_domains(env)
|
||||||
|
|
||||||
@@ -307,8 +324,20 @@ def run_domain_checks(rounded_time, env, output, pool):
|
|||||||
# Get the list of domains we serve HTTPS for.
|
# Get the list of domains we serve HTTPS for.
|
||||||
web_domains = set(get_web_domains(env))
|
web_domains = set(get_web_domains(env))
|
||||||
|
|
||||||
|
if domains_to_check is None:
|
||||||
domains_to_check = mail_domains | dns_domains | web_domains
|
domains_to_check = mail_domains | dns_domains | web_domains
|
||||||
|
|
||||||
|
# Remove "www", "autoconfig", "autodiscover", and "mta-sts" subdomains, which we group with their parent,
|
||||||
|
# if their parent is in the domains to check list.
|
||||||
|
domains_to_check = [
|
||||||
|
d for d in domains_to_check
|
||||||
|
if not (
|
||||||
|
d.split(".", 1)[0] in ("www", "autoconfig", "autodiscover", "mta-sts")
|
||||||
|
and len(d.split(".", 1)) == 2
|
||||||
|
and d.split(".", 1)[1] in domains_to_check
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
# Get the list of domains that we don't serve web for because of a custom CNAME/A record.
|
# Get the list of domains that we don't serve web for because of a custom CNAME/A record.
|
||||||
domains_with_a_records = get_domains_with_a_records(env)
|
domains_with_a_records = get_domains_with_a_records(env)
|
||||||
|
|
||||||
@@ -327,6 +356,11 @@ def run_domain_checks(rounded_time, env, output, pool):
|
|||||||
def run_domain_checks_on_domain(domain, rounded_time, env, dns_domains, dns_zonefiles, mail_domains, web_domains, domains_with_a_records):
|
def run_domain_checks_on_domain(domain, rounded_time, env, dns_domains, dns_zonefiles, mail_domains, web_domains, domains_with_a_records):
|
||||||
output = BufferedOutput()
|
output = BufferedOutput()
|
||||||
|
|
||||||
|
# When running inside Flask, the worker threads don't get a thread pool automatically.
|
||||||
|
# Also this method is called in a forked worker pool, so creating a new loop is probably
|
||||||
|
# a good idea.
|
||||||
|
asyncio.set_event_loop(asyncio.new_event_loop())
|
||||||
|
|
||||||
# we'd move this up, but this returns non-pickleable values
|
# we'd move this up, but this returns non-pickleable values
|
||||||
ssl_certificates = get_ssl_certificates(env)
|
ssl_certificates = get_ssl_certificates(env)
|
||||||
|
|
||||||
@@ -354,6 +388,26 @@ def run_domain_checks_on_domain(domain, rounded_time, env, dns_domains, dns_zone
|
|||||||
if domain in dns_domains:
|
if domain in dns_domains:
|
||||||
check_dns_zone_suggestions(domain, env, output, dns_zonefiles, domains_with_a_records)
|
check_dns_zone_suggestions(domain, env, output, dns_zonefiles, domains_with_a_records)
|
||||||
|
|
||||||
|
# Check auto-configured subdomains. See run_domain_checks.
|
||||||
|
# Skip mta-sts because we check the policy directly.
|
||||||
|
for label in ("www", "autoconfig", "autodiscover"):
|
||||||
|
subdomain = label + "." + domain
|
||||||
|
if subdomain in web_domains or subdomain in mail_domains:
|
||||||
|
# Run checks.
|
||||||
|
subdomain_output = run_domain_checks_on_domain(subdomain, rounded_time, env, dns_domains, dns_zonefiles, mail_domains, web_domains, domains_with_a_records)
|
||||||
|
|
||||||
|
# Prepend the domain name to the start of each check line, and then add to the
|
||||||
|
# checks for this domain.
|
||||||
|
for attr, args, kwargs in subdomain_output[1].buf:
|
||||||
|
if attr == "add_heading":
|
||||||
|
# Drop the heading, but use its text as the subdomain name in
|
||||||
|
# each line since it is in Unicode form.
|
||||||
|
subdomain = args[0]
|
||||||
|
continue
|
||||||
|
if len(args) == 1 and isinstance(args[0], str):
|
||||||
|
args = [ subdomain + ": " + args[0] ]
|
||||||
|
getattr(output, attr)(*args, **kwargs)
|
||||||
|
|
||||||
return (domain, output)
|
return (domain, output)
|
||||||
|
|
||||||
def check_primary_hostname_dns(domain, env, output, dns_domains, dns_zonefiles):
|
def check_primary_hostname_dns(domain, env, output, dns_domains, dns_zonefiles):
|
||||||
@@ -486,10 +540,12 @@ def check_dns_zone(domain, env, output, dns_zonefiles):
|
|||||||
if custom_secondary_ns and not probably_external_dns:
|
if custom_secondary_ns and not probably_external_dns:
|
||||||
for ns in custom_secondary_ns:
|
for ns in custom_secondary_ns:
|
||||||
# We must first resolve the nameserver to an IP address so we can query it.
|
# We must first resolve the nameserver to an IP address so we can query it.
|
||||||
ns_ip = query_dns(ns, "A")
|
ns_ips = query_dns(ns, "A")
|
||||||
if not ns_ip:
|
if not ns_ips:
|
||||||
output.print_error("Secondary nameserver %s is not valid (it doesn't resolve to an IP address)." % ns)
|
output.print_error("Secondary nameserver %s is not valid (it doesn't resolve to an IP address)." % ns)
|
||||||
continue
|
continue
|
||||||
|
# Choose the first IP if nameserver returns multiple
|
||||||
|
ns_ip = ns_ips.split('; ')[0]
|
||||||
|
|
||||||
# Now query it to see what it says about this domain.
|
# Now query it to see what it says about this domain.
|
||||||
ip = query_dns(domain, "A", at=ns_ip, nxdomain=None)
|
ip = query_dns(domain, "A", at=ns_ip, nxdomain=None)
|
||||||
@@ -515,61 +571,107 @@ def check_dns_zone_suggestions(domain, env, output, dns_zonefiles, domains_with_
|
|||||||
|
|
||||||
|
|
||||||
def check_dnssec(domain, env, output, dns_zonefiles, is_checking_primary=False):
|
def check_dnssec(domain, env, output, dns_zonefiles, is_checking_primary=False):
|
||||||
# See if the domain has a DS record set at the registrar. The DS record may have
|
# See if the domain has a DS record set at the registrar. The DS record must
|
||||||
# several forms. We have to be prepared to check for any valid record. We've
|
# match one of the keys that we've used to sign the zone. It may use one of
|
||||||
# pre-generated all of the valid digests --- read them in.
|
# several hashing algorithms. We've pre-generated all possible valid DS
|
||||||
|
# records, although some will be preferred.
|
||||||
|
|
||||||
|
alg_name_map = { '7': 'RSASHA1-NSEC3-SHA1', '8': 'RSASHA256', '13': 'ECDSAP256SHA256' }
|
||||||
|
digalg_name_map = { '1': 'SHA-1', '2': 'SHA-256', '4': 'SHA-384' }
|
||||||
|
|
||||||
|
# Read in the pre-generated DS records
|
||||||
|
expected_ds_records = { }
|
||||||
ds_file = '/etc/nsd/zones/' + dns_zonefiles[domain] + '.ds'
|
ds_file = '/etc/nsd/zones/' + dns_zonefiles[domain] + '.ds'
|
||||||
if not os.path.exists(ds_file): return # Domain is in our database but DNS has not yet been updated.
|
if not os.path.exists(ds_file): return # Domain is in our database but DNS has not yet been updated.
|
||||||
ds_correct = open(ds_file).read().strip().split("\n")
|
with open(ds_file) as f:
|
||||||
digests = { }
|
for rr_ds in f:
|
||||||
for rr_ds in ds_correct:
|
rr_ds = rr_ds.rstrip()
|
||||||
ds_keytag, ds_alg, ds_digalg, ds_digest = rr_ds.split("\t")[4].split(" ")
|
ds_keytag, ds_alg, ds_digalg, ds_digest = rr_ds.split("\t")[4].split(" ")
|
||||||
digests[ds_digalg] = ds_digest
|
|
||||||
|
|
||||||
# Some registrars may want the public key so they can compute the digest. The DS
|
# Some registrars may want the public key so they can compute the digest. The DS
|
||||||
# record that we suggest using is for the KSK (and that's how the DS records were generated).
|
# record that we suggest using is for the KSK (and that's how the DS records were generated).
|
||||||
alg_name_map = { '7': 'RSASHA1-NSEC3-SHA1', '8': 'RSASHA256' }
|
# We'll also give the nice name for the key algorithm.
|
||||||
dnssec_keys = load_env_vars_from_file(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/%s.conf' % alg_name_map[ds_alg]))
|
dnssec_keys = load_env_vars_from_file(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/%s.conf' % alg_name_map[ds_alg]))
|
||||||
dnsssec_pubkey = open(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/' + dnssec_keys['KSK'] + '.key')).read().split("\t")[3].split(" ")[3]
|
dnsssec_pubkey = open(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/' + dnssec_keys['KSK'] + '.key')).read().split("\t")[3].split(" ")[3]
|
||||||
|
|
||||||
|
expected_ds_records[ (ds_keytag, ds_alg, ds_digalg, ds_digest) ] = {
|
||||||
|
"record": rr_ds,
|
||||||
|
"keytag": ds_keytag,
|
||||||
|
"alg": ds_alg,
|
||||||
|
"alg_name": alg_name_map[ds_alg],
|
||||||
|
"digalg": ds_digalg,
|
||||||
|
"digalg_name": digalg_name_map[ds_digalg],
|
||||||
|
"digest": ds_digest,
|
||||||
|
"pubkey": dnsssec_pubkey,
|
||||||
|
}
|
||||||
|
|
||||||
# Query public DNS for the DS record at the registrar.
|
# Query public DNS for the DS record at the registrar.
|
||||||
ds = query_dns(domain, "DS", nxdomain=None)
|
ds = query_dns(domain, "DS", nxdomain=None, as_list=True)
|
||||||
ds_looks_valid = ds and len(ds.split(" ")) == 4
|
if ds is None or isinstance(ds, str): ds = []
|
||||||
if ds_looks_valid: ds = ds.split(" ")
|
|
||||||
if ds_looks_valid and ds[0] == ds_keytag and ds[1] == ds_alg and ds[3] == digests.get(ds[2]):
|
# There may be more that one record, so we get the result as a list.
|
||||||
if is_checking_primary: return
|
# Filter out records that don't look valid, just in case, and split
|
||||||
output.print_ok("DNSSEC 'DS' record is set correctly at registrar.")
|
# each record on spaces.
|
||||||
|
ds = [tuple(str(rr).split(" ")) for rr in ds if len(str(rr).split(" ")) == 4]
|
||||||
|
|
||||||
|
if len(ds) == 0:
|
||||||
|
output.print_warning("""This domain's DNSSEC DS record is not set. The DS record is optional. The DS record activates DNSSEC. See below for instructions.""")
|
||||||
else:
|
else:
|
||||||
if ds == None:
|
matched_ds = set(ds) & set(expected_ds_records)
|
||||||
if is_checking_primary: return
|
if matched_ds:
|
||||||
output.print_warning("""This domain's DNSSEC DS record is not set. The DS record is optional. The DS record activates DNSSEC.
|
# At least one DS record matches one that corresponds with one of the ways we signed
|
||||||
To set a DS record, you must follow the instructions provided by your domain name registrar and provide to them this information:""")
|
# the zone, so it is valid.
|
||||||
|
#
|
||||||
|
# But it may not be preferred. Only algorithm 13 is preferred. Warn if any of the
|
||||||
|
# matched zones uses a different algorithm.
|
||||||
|
if set(r[1] for r in matched_ds) == { '13' } and set(r[2] for r in matched_ds) <= { '2', '4' }: # all are alg 13 and digest type 2 or 4
|
||||||
|
output.print_ok("DNSSEC 'DS' record is set correctly at registrar.")
|
||||||
|
return
|
||||||
|
elif len([r for r in matched_ds if r[1] == '13' and r[2] in ( '2', '4' )]) > 0: # some but not all are alg 13
|
||||||
|
output.print_ok("DNSSEC 'DS' record is set correctly at registrar. (Records using algorithm other than ECDSAP256SHA256 and digest types other than SHA-256/384 should be removed.)")
|
||||||
|
return
|
||||||
|
else: # no record uses alg 13
|
||||||
|
output.print_warning("""DNSSEC 'DS' record set at registrar is valid but should be updated to ECDSAP256SHA256 and SHA-256 (see below).
|
||||||
|
IMPORTANT: Do not delete existing DNSSEC 'DS' records for this domain until confirmation that the new DNSSEC 'DS' record
|
||||||
|
for this domain is valid.""")
|
||||||
else:
|
else:
|
||||||
if is_checking_primary:
|
if is_checking_primary:
|
||||||
output.print_error("""The DNSSEC 'DS' record for %s is incorrect. See further details below.""" % domain)
|
output.print_error("""The DNSSEC 'DS' record for %s is incorrect. See further details below.""" % domain)
|
||||||
return
|
return
|
||||||
output.print_error("""This domain's DNSSEC DS record is incorrect. The chain of trust is broken between the public DNS system
|
output.print_error("""This domain's DNSSEC DS record is incorrect. The chain of trust is broken between the public DNS system
|
||||||
and this machine's DNS server. It may take several hours for public DNS to update after a change. If you did not recently
|
and this machine's DNS server. It may take several hours for public DNS to update after a change. If you did not recently
|
||||||
make a change, you must resolve this immediately by following the instructions provided by your domain name registrar and
|
make a change, you must resolve this immediately (see below).""")
|
||||||
provide to them this information:""")
|
|
||||||
|
output.print_line("""Follow the instructions provided by your domain name registrar to set a DS record.
|
||||||
|
Registrars support different sorts of DS records. Use the first option that works:""")
|
||||||
|
preferred_ds_order = [(7, 2), (8, 4), (13, 4), (8, 2), (13, 2)] # low to high, see https://github.com/mail-in-a-box/mailinabox/issues/1998
|
||||||
|
|
||||||
|
def preferred_ds_order_func(ds_suggestion):
|
||||||
|
k = (int(ds_suggestion['alg']), int(ds_suggestion['digalg']))
|
||||||
|
if k in preferred_ds_order:
|
||||||
|
return preferred_ds_order.index(k)
|
||||||
|
return -1 # index before first item
|
||||||
output.print_line("")
|
output.print_line("")
|
||||||
output.print_line("Key Tag: " + ds_keytag + ("" if not ds_looks_valid or ds[0] == ds_keytag else " (Got '%s')" % ds[0]))
|
for i, ds_suggestion in enumerate(sorted(expected_ds_records.values(), key=preferred_ds_order_func, reverse=True)):
|
||||||
output.print_line("Key Flags: KSK")
|
if preferred_ds_order_func(ds_suggestion) == -1: continue # don't offer record types that the RFC says we must not offer
|
||||||
output.print_line(
|
output.print_line("")
|
||||||
("Algorithm: %s / %s" % (ds_alg, alg_name_map[ds_alg]))
|
output.print_line("Option " + str(i+1) + ":")
|
||||||
+ ("" if not ds_looks_valid or ds[1] == ds_alg else " (Got '%s')" % ds[1]))
|
output.print_line("----------")
|
||||||
# see http://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml
|
output.print_line("Key Tag: " + ds_suggestion['keytag'])
|
||||||
output.print_line("Digest Type: 2 / SHA-256")
|
output.print_line("Key Flags: KSK / 257")
|
||||||
# http://www.ietf.org/assignments/ds-rr-types/ds-rr-types.xml
|
output.print_line("Algorithm: %s / %s" % (ds_suggestion['alg'], ds_suggestion['alg_name']))
|
||||||
output.print_line("Digest: " + digests['2'])
|
output.print_line("Digest Type: %s / %s" % (ds_suggestion['digalg'], ds_suggestion['digalg_name']))
|
||||||
if ds_looks_valid and ds[3] != digests.get(ds[2]):
|
output.print_line("Digest: " + ds_suggestion['digest'])
|
||||||
output.print_line("(Got digest type %s and digest %s which do not match.)" % (ds[2], ds[3]))
|
|
||||||
output.print_line("Public Key: ")
|
output.print_line("Public Key: ")
|
||||||
output.print_line(dnsssec_pubkey, monospace=True)
|
output.print_line(ds_suggestion['pubkey'], monospace=True)
|
||||||
output.print_line("")
|
output.print_line("")
|
||||||
output.print_line("Bulk/Record Format:")
|
output.print_line("Bulk/Record Format:")
|
||||||
output.print_line("" + ds_correct[0])
|
output.print_line(ds_suggestion['record'], monospace=True)
|
||||||
|
if len(ds) > 0:
|
||||||
output.print_line("")
|
output.print_line("")
|
||||||
|
output.print_line("The DS record is currently set to:")
|
||||||
|
for rr in sorted(ds):
|
||||||
|
output.print_line("Key Tag: {0}, Algorithm: {1}, Digest Type: {2}, Digest: {3}".format(*rr))
|
||||||
|
|
||||||
def check_mail_domain(domain, env, output):
|
def check_mail_domain(domain, env, output):
|
||||||
# Check the MX record.
|
# Check the MX record.
|
||||||
@@ -579,6 +681,8 @@ def check_mail_domain(domain, env, output):
|
|||||||
|
|
||||||
if mx is None:
|
if mx is None:
|
||||||
mxhost = None
|
mxhost = None
|
||||||
|
elif mx == "[timeout]":
|
||||||
|
mxhost = None
|
||||||
else:
|
else:
|
||||||
# query_dns returns a semicolon-delimited list
|
# query_dns returns a semicolon-delimited list
|
||||||
# of priority-host pairs.
|
# of priority-host pairs.
|
||||||
@@ -609,6 +713,19 @@ def check_mail_domain(domain, env, output):
|
|||||||
if mx != recommended_mx:
|
if mx != recommended_mx:
|
||||||
good_news += " This configuration is non-standard. The recommended configuration is '%s'." % (recommended_mx,)
|
good_news += " This configuration is non-standard. The recommended configuration is '%s'." % (recommended_mx,)
|
||||||
output.print_ok(good_news)
|
output.print_ok(good_news)
|
||||||
|
|
||||||
|
# Check MTA-STS policy.
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
sts_resolver = postfix_mta_sts_resolver.resolver.STSResolver(loop=loop)
|
||||||
|
valid, policy = loop.run_until_complete(sts_resolver.resolve(domain))
|
||||||
|
if valid == postfix_mta_sts_resolver.resolver.STSFetchResult.VALID:
|
||||||
|
if policy[1].get("mx") == [env['PRIMARY_HOSTNAME']] and policy[1].get("mode") == "enforce": # policy[0] is the policyid
|
||||||
|
output.print_ok("MTA-STS policy is present.")
|
||||||
|
else:
|
||||||
|
output.print_error("MTA-STS policy is present but has unexpected settings. [{}]".format(policy[1]))
|
||||||
|
else:
|
||||||
|
output.print_error("MTA-STS policy is missing: {}".format(valid))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
output.print_error("""This domain's DNS MX record is incorrect. It is currently set to '%s' but should be '%s'. Mail will not
|
output.print_error("""This domain's DNS MX record is incorrect. It is currently set to '%s' but should be '%s'. Mail will not
|
||||||
be delivered to this box. It may take several hours for public DNS to update after a change. This problem may result from
|
be delivered to this box. It may take several hours for public DNS to update after a change. This problem may result from
|
||||||
@@ -625,6 +742,8 @@ def check_mail_domain(domain, env, output):
|
|||||||
dbl = query_dns(domain+'.dbl.spamhaus.org', "A", nxdomain=None)
|
dbl = query_dns(domain+'.dbl.spamhaus.org', "A", nxdomain=None)
|
||||||
if dbl is None:
|
if dbl is None:
|
||||||
output.print_ok("Domain is not blacklisted by dbl.spamhaus.org.")
|
output.print_ok("Domain is not blacklisted by dbl.spamhaus.org.")
|
||||||
|
elif dbl == "[timeout]":
|
||||||
|
output.print_warning("Connection to dbl.spamhaus.org timed out. We could not determine whether the domain {} is blacklisted. Please try again later.".format(domain))
|
||||||
else:
|
else:
|
||||||
output.print_error("""This domain is listed in the Spamhaus Domain Block List (code %s),
|
output.print_error("""This domain is listed in the Spamhaus Domain Block List (code %s),
|
||||||
which may prevent recipients from receiving your mail.
|
which may prevent recipients from receiving your mail.
|
||||||
@@ -656,7 +775,7 @@ def check_web_domain(domain, rounded_time, ssl_certificates, env, output):
|
|||||||
# website for also needs a signed certificate.
|
# website for also needs a signed certificate.
|
||||||
check_ssl_cert(domain, rounded_time, ssl_certificates, env, output)
|
check_ssl_cert(domain, rounded_time, ssl_certificates, env, output)
|
||||||
|
|
||||||
def query_dns(qname, rtype, nxdomain='[Not Set]', at=None):
|
def query_dns(qname, rtype, nxdomain='[Not Set]', at=None, as_list=False):
|
||||||
# Make the qname absolute by appending a period. Without this, dns.resolver.query
|
# Make the qname absolute by appending a period. Without this, dns.resolver.query
|
||||||
# will fall back a failed lookup to a second query with this machine's hostname
|
# will fall back a failed lookup to a second query with this machine's hostname
|
||||||
# appended. This has been causing some false-positive Spamhaus reports. The
|
# appended. This has been causing some false-positive Spamhaus reports. The
|
||||||
@@ -693,6 +812,9 @@ def query_dns(qname, rtype, nxdomain='[Not Set]', at=None):
|
|||||||
if rtype in ("A", "AAAA"):
|
if rtype in ("A", "AAAA"):
|
||||||
response = [normalize_ip(str(r)) for r in response]
|
response = [normalize_ip(str(r)) for r in response]
|
||||||
|
|
||||||
|
if as_list:
|
||||||
|
return response
|
||||||
|
|
||||||
# There may be multiple answers; concatenate the response. Remove trailing
|
# There may be multiple answers; concatenate the response. Remove trailing
|
||||||
# periods from responses since that's how qnames are encoded in DNS but is
|
# periods from responses since that's how qnames are encoded in DNS but is
|
||||||
# confusing for us. The order of the answers doesn't matter, so sort so we
|
# confusing for us. The order of the answers doesn't matter, so sort so we
|
||||||
@@ -968,12 +1090,13 @@ if __name__ == "__main__":
|
|||||||
from utils import load_environment
|
from utils import load_environment
|
||||||
|
|
||||||
env = load_environment()
|
env = load_environment()
|
||||||
pool = multiprocessing.pool.Pool(processes=10)
|
|
||||||
|
|
||||||
if len(sys.argv) == 1:
|
if len(sys.argv) == 1:
|
||||||
|
with multiprocessing.pool.Pool(processes=10) as pool:
|
||||||
run_checks(False, env, ConsoleOutput(), pool)
|
run_checks(False, env, ConsoleOutput(), pool)
|
||||||
|
|
||||||
elif sys.argv[1] == "--show-changes":
|
elif sys.argv[1] == "--show-changes":
|
||||||
|
with multiprocessing.pool.Pool(processes=10) as pool:
|
||||||
run_and_output_changes(env, pool)
|
run_and_output_changes(env, pool)
|
||||||
|
|
||||||
elif sys.argv[1] == "--check-primary-hostname":
|
elif sys.argv[1] == "--check-primary-hostname":
|
||||||
@@ -992,3 +1115,7 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
elif sys.argv[1] == "--version":
|
elif sys.argv[1] == "--version":
|
||||||
print(what_version_is_this(env))
|
print(what_version_is_this(env))
|
||||||
|
|
||||||
|
elif sys.argv[1] == "--only":
|
||||||
|
with multiprocessing.pool.Pool(processes=10) as pool:
|
||||||
|
run_checks(False, env, ConsoleOutput(), pool, domains_to_check=sys.argv[2:])
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<style>
|
<style>
|
||||||
#alias_table .actions > * { padding-right: 3px; }
|
#alias_table .actions > * { padding-right: 3px; }
|
||||||
#alias_table .alias-required .remove { display: none }
|
#alias_table .alias-auto .actions > * { display: none }
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<h2>Aliases</h2>
|
<h2>Aliases</h2>
|
||||||
@@ -153,8 +153,8 @@ function show_aliases() {
|
|||||||
function(r) {
|
function(r) {
|
||||||
$('#alias_table tbody').html("");
|
$('#alias_table tbody').html("");
|
||||||
for (var i = 0; i < r.length; i++) {
|
for (var i = 0; i < r.length; i++) {
|
||||||
var hdr = $("<tr><td colspan='3'><h4/></td></tr>");
|
var hdr = $("<tr><th colspan='4' style='background-color: #EEE'></th></tr>");
|
||||||
hdr.find('h4').text(r[i].domain);
|
hdr.find('th').text(r[i].domain);
|
||||||
$('#alias_table tbody').append(hdr);
|
$('#alias_table tbody').append(hdr);
|
||||||
|
|
||||||
for (var k = 0; k < r[i].aliases.length; k++) {
|
for (var k = 0; k < r[i].aliases.length; k++) {
|
||||||
@@ -163,7 +163,7 @@ function show_aliases() {
|
|||||||
var n = $("#alias-template").clone();
|
var n = $("#alias-template").clone();
|
||||||
n.attr('id', '');
|
n.attr('id', '');
|
||||||
|
|
||||||
if (alias.required) n.addClass('alias-required');
|
if (alias.auto) n.addClass('alias-auto');
|
||||||
n.attr('data-address', alias.address_display); // this is decoded from IDNA, but will get re-coded to IDNA on the backend
|
n.attr('data-address', alias.address_display); // this is decoded from IDNA, but will get re-coded to IDNA on the backend
|
||||||
n.find('td.address').text(alias.address_display)
|
n.find('td.address').text(alias.address_display)
|
||||||
for (var j = 0; j < alias.forwards_to.length; j++)
|
for (var j = 0; j < alias.forwards_to.length; j++)
|
||||||
@@ -288,7 +288,7 @@ function aliases_remove(elem) {
|
|||||||
},
|
},
|
||||||
function(r) {
|
function(r) {
|
||||||
// Responses are multiple lines of pre-formatted text.
|
// Responses are multiple lines of pre-formatted text.
|
||||||
show_modal_error("Remove User", $("<pre/>").text(r));
|
show_modal_error("Remove Alias", $("<pre/>").text(r));
|
||||||
show_aliases();
|
show_aliases();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -57,7 +57,13 @@
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<table id="custom-dns-current" class="table" style="width: auto; display: none">
|
<div style="text-align: right; font-size; 90%; margin-top: 1em;">
|
||||||
|
sort by:
|
||||||
|
<a href="#" onclick="window.miab_custom_dns_data_sort_order='qname'; show_current_custom_dns_update_after_sort(); return false;">domain name</a>
|
||||||
|
|
|
||||||
|
<a href="#" onclick="window.miab_custom_dns_data_sort_order='created'; show_current_custom_dns_update_after_sort(); return false;">created</a>
|
||||||
|
</div>
|
||||||
|
<table id="custom-dns-current" class="table" style="width: auto; display: none; margin-top: 0;">
|
||||||
<thead>
|
<thead>
|
||||||
<th>Domain Name</th>
|
<th>Domain Name</th>
|
||||||
<th>Record Type</th>
|
<th>Record Type</th>
|
||||||
@@ -90,7 +96,7 @@
|
|||||||
<div class="col-sm-offset-1 col-sm-11">
|
<div class="col-sm-offset-1 col-sm-11">
|
||||||
<p class="small">
|
<p class="small">
|
||||||
Multiple secondary servers can be separated with commas or spaces (i.e., <code>ns2.hostingcompany.com ns3.hostingcompany.com</code>).
|
Multiple secondary servers can be separated with commas or spaces (i.e., <code>ns2.hostingcompany.com ns3.hostingcompany.com</code>).
|
||||||
To enable zone transfers to additional servers without listing them as secondary nameservers, add <code>xfr:IPADDRESS</code>.
|
To enable zone transfers to additional servers without listing them as secondary nameservers, add an IP address or subnet using <code>xfr:10.20.30.40</code> or <code>xfr:10.0.0.0/8</code>.
|
||||||
</p>
|
</p>
|
||||||
<p id="secondarydns-clear-instructions" style="display: none" class="small">
|
<p id="secondarydns-clear-instructions" style="display: none" class="small">
|
||||||
Clear the input field above and click Update to use this machine itself as secondary DNS, which is the default/normal setup.
|
Clear the input field above and click Update to use this machine itself as secondary DNS, which is the default/normal setup.
|
||||||
@@ -192,20 +198,38 @@ function show_current_custom_dns() {
|
|||||||
$('#custom-dns-current').fadeIn();
|
$('#custom-dns-current').fadeIn();
|
||||||
else
|
else
|
||||||
$('#custom-dns-current').fadeOut();
|
$('#custom-dns-current').fadeOut();
|
||||||
|
window.miab_custom_dns_data = data;
|
||||||
|
show_current_custom_dns_update_after_sort();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
$('#custom-dns-current').find("tbody").text('');
|
function show_current_custom_dns_update_after_sort() {
|
||||||
|
var data = window.miab_custom_dns_data;
|
||||||
|
var sort_key = window.miab_custom_dns_data_sort_order || "qname";
|
||||||
|
|
||||||
|
data.sort(function(a, b) { return a["sort-order"][sort_key] - b["sort-order"][sort_key] });
|
||||||
|
|
||||||
|
var tbody = $('#custom-dns-current').find("tbody");
|
||||||
|
tbody.text('');
|
||||||
|
var last_zone = null;
|
||||||
for (var i = 0; i < data.length; i++) {
|
for (var i = 0; i < data.length; i++) {
|
||||||
|
if (sort_key == "qname" && data[i].zone != last_zone) {
|
||||||
|
var r = $("<tr><th colspan=4 style='background-color: #EEE'></th></tr>");
|
||||||
|
r.find("th").text(data[i].zone);
|
||||||
|
tbody.append(r);
|
||||||
|
last_zone = data[i].zone;
|
||||||
|
}
|
||||||
|
|
||||||
var tr = $("<tr/>");
|
var tr = $("<tr/>");
|
||||||
$('#custom-dns-current').find("tbody").append(tr);
|
tbody.append(tr);
|
||||||
tr.attr('data-qname', data[i].qname);
|
tr.attr('data-qname', data[i].qname);
|
||||||
tr.attr('data-rtype', data[i].rtype);
|
tr.attr('data-rtype', data[i].rtype);
|
||||||
tr.attr('data-value', data[i].value);
|
tr.attr('data-value', data[i].value);
|
||||||
tr.append($('<td class="long"/>').text(data[i].qname));
|
tr.append($('<td class="long"/>').text(data[i].qname));
|
||||||
tr.append($('<td/>').text(data[i].rtype));
|
tr.append($('<td/>').text(data[i].rtype));
|
||||||
tr.append($('<td class="long"/>').text(data[i].value));
|
tr.append($('<td class="long" style="max-width: 40em"/>').text(data[i].value));
|
||||||
tr.append($('<td>[<a href="#" onclick="return delete_custom_dns_record(this)">delete</a>]</td>'));
|
tr.append($('<td>[<a href="#" onclick="return delete_custom_dns_record(this)">delete</a>]</td>'));
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function delete_custom_dns_record(elem) {
|
function delete_custom_dns_record(elem) {
|
||||||
|
|||||||
@@ -38,10 +38,23 @@
|
|||||||
<p class="alert" role="alert">
|
<p class="alert" role="alert">
|
||||||
<span class="glyphicon glyphicon-info-sign"></span>
|
<span class="glyphicon glyphicon-info-sign"></span>
|
||||||
You may encounter zone file errors when attempting to create a TXT record with a long string.
|
You may encounter zone file errors when attempting to create a TXT record with a long string.
|
||||||
<a href="http://tools.ietf.org/html/rfc4408#section-3.1.3">RFC 4408</a> states a TXT record is allowed to contain multiple strings, and this technique can be used to construct records that would exceed the 255-byte maximum length.
|
<a href="https://tools.ietf.org/html/rfc4408#section-3.1.3">RFC 4408</a> states a TXT record is allowed to contain multiple strings, and this technique can be used to construct records that would exceed the 255-byte maximum length.
|
||||||
You may need to adopt this technique when adding DomainKeys. Use a tool like <code>named-checkzone</code> to validate your zone file.
|
You may need to adopt this technique when adding DomainKeys. Use a tool like <code>named-checkzone</code> to validate your zone file.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
<h3>Download zonefile</h3>
|
||||||
|
<p>You can download your zonefiles here or use the table of records below.</p>
|
||||||
|
<form class="form-inline" role="form" onsubmit="do_download_zonefile(); return false;">
|
||||||
|
<div class="form-group">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="downloadZonefile" class="control-label sr-only">Zone</label>
|
||||||
|
<select id="downloadZonefile" class="form-control" style="width: auto"> </select>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-primary">Download</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<h3>Records</h3>
|
||||||
|
|
||||||
<table id="external_dns_settings" class="table">
|
<table id="external_dns_settings" class="table">
|
||||||
<thead>
|
<thead>
|
||||||
@@ -57,6 +70,18 @@
|
|||||||
|
|
||||||
<script>
|
<script>
|
||||||
function show_external_dns() {
|
function show_external_dns() {
|
||||||
|
api(
|
||||||
|
"/dns/zones",
|
||||||
|
"GET",
|
||||||
|
{ },
|
||||||
|
function(data) {
|
||||||
|
var zones = $('#downloadZonefile');
|
||||||
|
zones.text('');
|
||||||
|
for (var j = 0; j < data.length; j++) {
|
||||||
|
zones.append($('<option/>').text(data[j]));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
$('#external_dns_settings tbody').html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
|
$('#external_dns_settings tbody').html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
|
||||||
api(
|
api(
|
||||||
"/dns/dump",
|
"/dns/dump",
|
||||||
@@ -84,4 +109,19 @@ function show_external_dns() {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function do_download_zonefile() {
|
||||||
|
var zone = $('#downloadZonefile').val();
|
||||||
|
|
||||||
|
api(
|
||||||
|
"/dns/zonefile/"+ zone,
|
||||||
|
"GET",
|
||||||
|
{},
|
||||||
|
function(data) {
|
||||||
|
show_modal_error("Download Zonefile", $("<pre/>").text(data));
|
||||||
|
},
|
||||||
|
function(err) {
|
||||||
|
show_modal_error("Download Zonefile (Error)", $("<pre/>").text(err));
|
||||||
|
});
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -62,6 +62,37 @@
|
|||||||
ol li {
|
ol li {
|
||||||
margin-bottom: 1em;
|
margin-bottom: 1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.if-logged-in { display: none; }
|
||||||
|
.if-logged-in-admin { display: none; }
|
||||||
|
|
||||||
|
/* The below only gets used if it is supported */
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
/* Invert invert lightness but not hue */
|
||||||
|
html {
|
||||||
|
filter: invert(100%) hue-rotate(180deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Set explicit background color (necessary for Firefox) */
|
||||||
|
html {
|
||||||
|
background-color: #111;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Override Boostrap theme here to give more contrast. The black turns to white by the filter. */
|
||||||
|
.form-control {
|
||||||
|
color: black !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Revert the invert for the navbar */
|
||||||
|
button, div.navbar {
|
||||||
|
filter: invert(100%) hue-rotate(180deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Revert the revert for the dropdowns */
|
||||||
|
ul.dropdown-menu {
|
||||||
|
filter: invert(100%) hue-rotate(180deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
<link rel="stylesheet" href="/admin/assets/bootstrap/css/bootstrap-theme.min.css">
|
<link rel="stylesheet" href="/admin/assets/bootstrap/css/bootstrap-theme.min.css">
|
||||||
</head>
|
</head>
|
||||||
@@ -83,7 +114,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="navbar-collapse collapse">
|
<div class="navbar-collapse collapse">
|
||||||
<ul class="nav navbar-nav">
|
<ul class="nav navbar-nav">
|
||||||
<li class="dropdown">
|
<li class="dropdown if-logged-in-admin">
|
||||||
<a href="#" class="dropdown-toggle" data-toggle="dropdown">System <b class="caret"></b></a>
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">System <b class="caret"></b></a>
|
||||||
<ul class="dropdown-menu">
|
<ul class="dropdown-menu">
|
||||||
<li><a href="#system_status" onclick="return show_panel(this);">Status Checks</a></li>
|
<li><a href="#system_status" onclick="return show_panel(this);">Status Checks</a></li>
|
||||||
@@ -93,28 +124,36 @@
|
|||||||
<li class="dropdown-header">Advanced Pages</li>
|
<li class="dropdown-header">Advanced Pages</li>
|
||||||
<li><a href="#custom_dns" onclick="return show_panel(this);">Custom DNS</a></li>
|
<li><a href="#custom_dns" onclick="return show_panel(this);">Custom DNS</a></li>
|
||||||
<li><a href="#external_dns" onclick="return show_panel(this);">External DNS</a></li>
|
<li><a href="#external_dns" onclick="return show_panel(this);">External DNS</a></li>
|
||||||
<li><a href="/admin/munin" target="_blank">Munin Monitoring</a></li>
|
<li><a href="#munin" onclick="return show_panel(this);">Munin Monitoring</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
<li class="dropdown">
|
<li><a href="#mail-guide" onclick="return show_panel(this);" class="if-logged-in-not-admin">Mail</a></li>
|
||||||
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Mail <b class="caret"></b></a>
|
<li class="dropdown if-logged-in-admin">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Mail & Users <b class="caret"></b></a>
|
||||||
<ul class="dropdown-menu">
|
<ul class="dropdown-menu">
|
||||||
<li><a href="#mail-guide" onclick="return show_panel(this);">Instructions</a></li>
|
<li><a href="#mail-guide" onclick="return show_panel(this);">Instructions</a></li>
|
||||||
<li><a href="#users" onclick="return show_panel(this);">Users</a></li>
|
<li><a href="#users" onclick="return show_panel(this);">Users</a></li>
|
||||||
<li><a href="#aliases" onclick="return show_panel(this);">Aliases</a></li>
|
<li><a href="#aliases" onclick="return show_panel(this);">Aliases</a></li>
|
||||||
|
<li class="divider"></li>
|
||||||
|
<li class="dropdown-header">Your Account</li>
|
||||||
|
<li><a href="#mfa" onclick="return show_panel(this);">Two-Factor Authentication</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="#sync_guide" onclick="return show_panel(this);">Contacts/Calendar</a></li>
|
<li><a href="#sync_guide" onclick="return show_panel(this);" class="if-logged-in">Contacts/Calendar</a></li>
|
||||||
<li><a href="#web" onclick="return show_panel(this);">Web</a></li>
|
<li><a href="#web" onclick="return show_panel(this);" class="if-logged-in-admin">Web</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
<ul class="nav navbar-nav navbar-right">
|
<ul class="nav navbar-nav navbar-right">
|
||||||
<li><a href="#" onclick="do_logout(); return false;" style="color: white">Log out</a></li>
|
<li class="if-logged-in"><a href="#" onclick="do_logout(); return false;" style="color: white">Log out</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</div><!--/.navbar-collapse -->
|
</div><!--/.navbar-collapse -->
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="container">
|
<div class="container">
|
||||||
|
<div id="panel_welcome" class="admin_panel">
|
||||||
|
{% include "welcome.html" %}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div id="panel_system_status" class="admin_panel">
|
<div id="panel_system_status" class="admin_panel">
|
||||||
{% include "system-status.html" %}
|
{% include "system-status.html" %}
|
||||||
</div>
|
</div>
|
||||||
@@ -131,6 +170,10 @@
|
|||||||
{% include "custom-dns.html" %}
|
{% include "custom-dns.html" %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div id="panel_mfa" class="admin_panel">
|
||||||
|
{% include "mfa.html" %}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div id="panel_login" class="admin_panel">
|
<div id="panel_login" class="admin_panel">
|
||||||
{% include "login.html" %}
|
{% include "login.html" %}
|
||||||
</div>
|
</div>
|
||||||
@@ -159,6 +202,10 @@
|
|||||||
{% include "ssl.html" %}
|
{% include "ssl.html" %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div id="panel_munin" class="admin_panel">
|
||||||
|
{% include "munin.html" %}
|
||||||
|
</div>
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
@@ -291,8 +338,8 @@ function ajax_with_indicator(options) {
|
|||||||
return false; // handy when called from onclick
|
return false; // handy when called from onclick
|
||||||
}
|
}
|
||||||
|
|
||||||
var api_credentials = ["", ""];
|
var api_credentials = null;
|
||||||
function api(url, method, data, callback, callback_error) {
|
function api(url, method, data, callback, callback_error, headers) {
|
||||||
// from http://www.webtoolkit.info/javascript-base64.html
|
// from http://www.webtoolkit.info/javascript-base64.html
|
||||||
function base64encode(input) {
|
function base64encode(input) {
|
||||||
_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
|
_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
|
||||||
@@ -330,7 +377,7 @@ function api(url, method, data, callback, callback_error) {
|
|||||||
method: method,
|
method: method,
|
||||||
cache: false,
|
cache: false,
|
||||||
data: data,
|
data: data,
|
||||||
|
headers: headers,
|
||||||
// the custom DNS api sends raw POST/PUT bodies --- prevent URL-encoding
|
// the custom DNS api sends raw POST/PUT bodies --- prevent URL-encoding
|
||||||
processData: typeof data != "string",
|
processData: typeof data != "string",
|
||||||
mimeType: typeof data == "string" ? "text/plain; charset=ascii" : null,
|
mimeType: typeof data == "string" ? "text/plain; charset=ascii" : null,
|
||||||
@@ -339,9 +386,10 @@ function api(url, method, data, callback, callback_error) {
|
|||||||
// We don't store user credentials in a cookie to avoid the hassle of CSRF
|
// We don't store user credentials in a cookie to avoid the hassle of CSRF
|
||||||
// attacks. The Authorization header only gets set in our AJAX calls triggered
|
// attacks. The Authorization header only gets set in our AJAX calls triggered
|
||||||
// by user actions.
|
// by user actions.
|
||||||
|
if (api_credentials)
|
||||||
xhr.setRequestHeader(
|
xhr.setRequestHeader(
|
||||||
'Authorization',
|
'Authorization',
|
||||||
'Basic ' + base64encode(api_credentials[0] + ':' + api_credentials[1]));
|
'Basic ' + base64encode(api_credentials.username + ':' + api_credentials.session_key));
|
||||||
},
|
},
|
||||||
success: callback,
|
success: callback,
|
||||||
error: callback_error || default_error,
|
error: callback_error || default_error,
|
||||||
@@ -358,6 +406,25 @@ function api(url, method, data, callback, callback_error) {
|
|||||||
|
|
||||||
var current_panel = null;
|
var current_panel = null;
|
||||||
var switch_back_to_panel = null;
|
var switch_back_to_panel = null;
|
||||||
|
|
||||||
|
function do_logout() {
|
||||||
|
// Clear the session from the backend.
|
||||||
|
api("/logout", "POST");
|
||||||
|
|
||||||
|
// Forget the token.
|
||||||
|
api_credentials = null;
|
||||||
|
if (typeof localStorage != 'undefined')
|
||||||
|
localStorage.removeItem("miab-cp-credentials");
|
||||||
|
if (typeof sessionStorage != 'undefined')
|
||||||
|
sessionStorage.removeItem("miab-cp-credentials");
|
||||||
|
|
||||||
|
// Return to the start.
|
||||||
|
show_panel('login');
|
||||||
|
|
||||||
|
// Reset menus.
|
||||||
|
show_hide_menus();
|
||||||
|
}
|
||||||
|
|
||||||
function show_panel(panelid) {
|
function show_panel(panelid) {
|
||||||
if (panelid.getAttribute)
|
if (panelid.getAttribute)
|
||||||
// we might be passed an HTMLElement <a>.
|
// we might be passed an HTMLElement <a>.
|
||||||
@@ -378,14 +445,22 @@ function show_panel(panelid) {
|
|||||||
|
|
||||||
$(function() {
|
$(function() {
|
||||||
// Recall saved user credentials.
|
// Recall saved user credentials.
|
||||||
|
try {
|
||||||
if (typeof sessionStorage != 'undefined' && sessionStorage.getItem("miab-cp-credentials"))
|
if (typeof sessionStorage != 'undefined' && sessionStorage.getItem("miab-cp-credentials"))
|
||||||
api_credentials = sessionStorage.getItem("miab-cp-credentials").split(":");
|
api_credentials = JSON.parse(sessionStorage.getItem("miab-cp-credentials"));
|
||||||
else if (typeof localStorage != 'undefined' && localStorage.getItem("miab-cp-credentials"))
|
else if (typeof localStorage != 'undefined' && localStorage.getItem("miab-cp-credentials"))
|
||||||
api_credentials = localStorage.getItem("miab-cp-credentials").split(":");
|
api_credentials = JSON.parse(localStorage.getItem("miab-cp-credentials"));
|
||||||
|
} catch (_) {
|
||||||
|
}
|
||||||
|
|
||||||
|
// Toggle menu state.
|
||||||
|
show_hide_menus();
|
||||||
|
|
||||||
// Recall what the user was last looking at.
|
// Recall what the user was last looking at.
|
||||||
if (typeof localStorage != 'undefined' && localStorage.getItem("miab-cp-lastpanel")) {
|
if (api_credentials != null && typeof localStorage != 'undefined' && localStorage.getItem("miab-cp-lastpanel")) {
|
||||||
show_panel(localStorage.getItem("miab-cp-lastpanel"));
|
show_panel(localStorage.getItem("miab-cp-lastpanel"));
|
||||||
|
} else if (api_credentials != null) {
|
||||||
|
show_panel('welcome');
|
||||||
} else {
|
} else {
|
||||||
show_panel('login');
|
show_panel('login');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,29 @@
|
|||||||
<h1 style="margin: 1em; text-align: center">{{hostname}}</h1>
|
<style>
|
||||||
|
.title {
|
||||||
|
margin: 1em;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.subtitle {
|
||||||
|
margin: 2em;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login {
|
||||||
|
margin: 0 auto;
|
||||||
|
max-width: 32em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login #loginOtp {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
#loginForm.is-twofactor #loginOtp {
|
||||||
|
display: block
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<h1 class="title">{{hostname}}</h1>
|
||||||
|
|
||||||
{% if no_users_exist or no_admins_exist %}
|
{% if no_users_exist or no_admins_exist %}
|
||||||
<div class="row">
|
<div class="row">
|
||||||
@@ -7,23 +32,23 @@
|
|||||||
<p class="text-danger">There are no users on this system! To make an administrative user,
|
<p class="text-danger">There are no users on this system! To make an administrative user,
|
||||||
log into this machine using SSH (like when you first set it up) and run:</p>
|
log into this machine using SSH (like when you first set it up) and run:</p>
|
||||||
<pre>cd mailinabox
|
<pre>cd mailinabox
|
||||||
sudo tools/mail.py user add me@{{hostname}}
|
sudo management/cli.py user add me@{{hostname}}
|
||||||
sudo tools/mail.py user make-admin me@{{hostname}}</pre>
|
sudo management/cli.py user make-admin me@{{hostname}}</pre>
|
||||||
{% else %}
|
{% else %}
|
||||||
<p class="text-danger">There are no administrative users on this system! To make an administrative user,
|
<p class="text-danger">There are no administrative users on this system! To make an administrative user,
|
||||||
log into this machine using SSH (like when you first set it up) and run:</p>
|
log into this machine using SSH (like when you first set it up) and run:</p>
|
||||||
<pre>cd mailinabox
|
<pre>cd mailinabox
|
||||||
sudo tools/mail.py user make-admin me@{{hostname}}</pre>
|
sudo management/cli.py user make-admin me@{{hostname}}</pre>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<hr>
|
<hr>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<p style="margin: 2em; text-align: center;">Log in here for your Mail-in-a-Box control panel.</p>
|
<p class="subtitle">Log in here for your Mail-in-a-Box control panel.</p>
|
||||||
|
|
||||||
<div style="margin: 0 auto; max-width: 32em;">
|
<div class="login">
|
||||||
<form class="form-horizontal" role="form" onsubmit="do_login(); return false;" method="get">
|
<form id="loginForm" class="form-horizontal" role="form" onsubmit="do_login(); return false;" method="get">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="inputEmail3" class="col-sm-3 control-label">Email</label>
|
<label for="inputEmail3" class="col-sm-3 control-label">Email</label>
|
||||||
<div class="col-sm-9">
|
<div class="col-sm-9">
|
||||||
@@ -36,6 +61,13 @@ sudo tools/mail.py user make-admin me@{{hostname}}</pre>
|
|||||||
<input name="password" type="password" class="form-control" id="loginPassword" placeholder="Password">
|
<input name="password" type="password" class="form-control" id="loginPassword" placeholder="Password">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="form-group" id="loginOtp">
|
||||||
|
<label for="loginOtpInput" class="col-sm-3 control-label">Code</label>
|
||||||
|
<div class="col-sm-9">
|
||||||
|
<input type="text" class="form-control" id="loginOtpInput" placeholder="6-digit code" autocomplete="off">
|
||||||
|
<div class="help-block" style="margin-top: 5px; font-size: 90%">Enter the six-digit code generated by your two factor authentication app.</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<div class="col-sm-offset-3 col-sm-9">
|
<div class="col-sm-offset-3 col-sm-9">
|
||||||
<div class="checkbox">
|
<div class="checkbox">
|
||||||
@@ -53,7 +85,6 @@ sudo tools/mail.py user make-admin me@{{hostname}}</pre>
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
function do_login() {
|
function do_login() {
|
||||||
if ($('#loginEmail').val() == "") {
|
if ($('#loginEmail').val() == "") {
|
||||||
@@ -62,6 +93,7 @@ function do_login() {
|
|||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($('#loginPassword').val() == "") {
|
if ($('#loginPassword').val() == "") {
|
||||||
show_modal_error("Login Failed", "Enter your email password.", function() {
|
show_modal_error("Login Failed", "Enter your email password.", function() {
|
||||||
$('#loginPassword').focus();
|
$('#loginPassword').focus();
|
||||||
@@ -70,22 +102,34 @@ function do_login() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Exchange the email address & password for an API key.
|
// Exchange the email address & password for an API key.
|
||||||
api_credentials = [$('#loginEmail').val(), $('#loginPassword').val()]
|
api_credentials = { username: $('#loginEmail').val(), session_key: $('#loginPassword').val() }
|
||||||
|
|
||||||
api(
|
api(
|
||||||
"/me",
|
"/login",
|
||||||
"GET",
|
"POST",
|
||||||
{},
|
{},
|
||||||
function(response) {
|
function(response) {
|
||||||
// This API call always succeeds. It returns a JSON object indicating
|
// This API call always succeeds. It returns a JSON object indicating
|
||||||
// whether the request was authenticated or not.
|
// whether the request was authenticated or not.
|
||||||
if (response.status != "ok") {
|
if (response.status != 'ok') {
|
||||||
|
if (response.status === 'missing-totp-token' || (response.status === 'invalid' && response.reason == 'invalid-totp-token')) {
|
||||||
|
$('#loginForm').addClass('is-twofactor');
|
||||||
|
if (response.reason === "invalid-totp-token") {
|
||||||
|
show_modal_error("Login Failed", "Incorrect two factor authentication token.");
|
||||||
|
} else {
|
||||||
|
setTimeout(() => {
|
||||||
|
$('#loginOtpInput').focus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$('#loginForm').removeClass('is-twofactor');
|
||||||
|
|
||||||
// Show why the login failed.
|
// Show why the login failed.
|
||||||
show_modal_error("Login Failed", response.reason)
|
show_modal_error("Login Failed", response.reason)
|
||||||
|
|
||||||
// Reset any saved credentials.
|
// Reset any saved credentials.
|
||||||
do_logout();
|
do_logout();
|
||||||
|
}
|
||||||
} else if (!("api_key" in response)) {
|
} else if (!("api_key" in response)) {
|
||||||
// Login succeeded but user might not be authorized!
|
// Login succeeded but user might not be authorized!
|
||||||
show_modal_error("Login Failed", "You are not an administrator on this system.")
|
show_modal_error("Login Failed", "You are not an administrator on this system.")
|
||||||
@@ -97,41 +141,45 @@ function do_login() {
|
|||||||
// Login succeeded.
|
// Login succeeded.
|
||||||
|
|
||||||
// Save the new credentials.
|
// Save the new credentials.
|
||||||
api_credentials = [response.email, response.api_key];
|
api_credentials = { username: response.email,
|
||||||
|
session_key: response.api_key,
|
||||||
|
privileges: response.privileges };
|
||||||
|
|
||||||
// Try to wipe the username/password information.
|
// Try to wipe the username/password information.
|
||||||
$('#loginEmail').val('');
|
$('#loginEmail').val('');
|
||||||
$('#loginPassword').val('');
|
$('#loginPassword').val('');
|
||||||
|
$('#loginOtpInput').val('');
|
||||||
|
$('#loginForm').removeClass('is-twofactor');
|
||||||
|
|
||||||
// Remember the credentials.
|
// Remember the credentials.
|
||||||
if (typeof localStorage != 'undefined' && typeof sessionStorage != 'undefined') {
|
if (typeof localStorage != 'undefined' && typeof sessionStorage != 'undefined') {
|
||||||
if ($('#loginRemember').val()) {
|
if ($('#loginRemember').val()) {
|
||||||
localStorage.setItem("miab-cp-credentials", api_credentials.join(":"));
|
localStorage.setItem("miab-cp-credentials", JSON.stringify(api_credentials));
|
||||||
sessionStorage.removeItem("miab-cp-credentials");
|
sessionStorage.removeItem("miab-cp-credentials");
|
||||||
} else {
|
} else {
|
||||||
localStorage.removeItem("miab-cp-credentials");
|
localStorage.removeItem("miab-cp-credentials");
|
||||||
sessionStorage.setItem("miab-cp-credentials", api_credentials.join(":"));
|
sessionStorage.setItem("miab-cp-credentials", JSON.stringify(api_credentials));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Toggle menus.
|
||||||
|
show_hide_menus();
|
||||||
|
|
||||||
// Open the next panel the user wants to go to. Do this after the XHR response
|
// Open the next panel the user wants to go to. Do this after the XHR response
|
||||||
// is over so that we don't start a new XHR request while this one is finishing,
|
// is over so that we don't start a new XHR request while this one is finishing,
|
||||||
// which confuses the loading indicator.
|
// which confuses the loading indicator.
|
||||||
setTimeout(function() { show_panel(!switch_back_to_panel || switch_back_to_panel == "login" ? 'system_status' : switch_back_to_panel) }, 300);
|
setTimeout(function() { show_panel(!switch_back_to_panel || switch_back_to_panel == "login" ? 'welcome' : switch_back_to_panel) }, 300);
|
||||||
}
|
}
|
||||||
})
|
},
|
||||||
}
|
undefined,
|
||||||
|
{
|
||||||
function do_logout() {
|
'x-auth-token': $('#loginOtpInput').val()
|
||||||
api_credentials = ["", ""];
|
});
|
||||||
if (typeof localStorage != 'undefined')
|
|
||||||
localStorage.removeItem("miab-cp-credentials");
|
|
||||||
if (typeof sessionStorage != 'undefined')
|
|
||||||
sessionStorage.removeItem("miab-cp-credentials");
|
|
||||||
show_panel('login');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function show_login() {
|
function show_login() {
|
||||||
|
$('#loginForm').removeClass('is-twofactor');
|
||||||
|
$('#loginOtpInput').val('');
|
||||||
$('#loginEmail,#loginPassword').each(function() {
|
$('#loginEmail,#loginPassword').each(function() {
|
||||||
var input = $(this);
|
var input = $(this);
|
||||||
if (!$.trim(input.val())) {
|
if (!$.trim(input.val())) {
|
||||||
@@ -140,4 +188,19 @@ function show_login() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function show_hide_menus() {
|
||||||
|
var is_logged_in = (api_credentials != null);
|
||||||
|
var privs = api_credentials ? api_credentials.privileges : [];
|
||||||
|
$('.if-logged-in').toggle(is_logged_in);
|
||||||
|
$('.if-logged-in-admin, .if-logged-in-not-admin').toggle(false);
|
||||||
|
if (is_logged_in) {
|
||||||
|
$('.if-logged-in-not-admin').toggle(true);
|
||||||
|
privs.forEach(function(priv) {
|
||||||
|
$('.if-logged-in-' + priv).toggle(true);
|
||||||
|
$('.if-logged-in-not-' + priv).toggle(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
$('.if-not-logged-in').toggle(!is_logged_in);
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -30,8 +30,8 @@
|
|||||||
<tr><th>Mail server</th> <td>{{hostname}}</td>
|
<tr><th>Mail server</th> <td>{{hostname}}</td>
|
||||||
<tr><th>IMAP Port</th> <td>993</td></tr>
|
<tr><th>IMAP Port</th> <td>993</td></tr>
|
||||||
<tr><th>IMAP Security</th> <td>SSL or TLS</td></tr>
|
<tr><th>IMAP Security</th> <td>SSL or TLS</td></tr>
|
||||||
<tr><th>SMTP Port</th> <td>587</td></tr>
|
<tr><th>SMTP Port</th> <td>465</td></tr>
|
||||||
<tr><th>SMTP Security</td> <td>STARTTLS <small>(“always” or “required”, if prompted)</small></td></tr>
|
<tr><th>SMTP Security</td> <td>SSL or TLS</td></tr>
|
||||||
<tr><th>Username:</th> <td>Your whole email address.</td></tr>
|
<tr><th>Username:</th> <td>Your whole email address.</td></tr>
|
||||||
<tr><th>Password:</th> <td>Your mail password.</td></tr>
|
<tr><th>Password:</th> <td>Your mail password.</td></tr>
|
||||||
</table>
|
</table>
|
||||||
|
|||||||
242
management/templates/mfa.html
Normal file
242
management/templates/mfa.html
Normal file
@@ -0,0 +1,242 @@
|
|||||||
|
<style>
|
||||||
|
.twofactor #totp-setup,
|
||||||
|
.twofactor #disable-2fa,
|
||||||
|
.twofactor #output-2fa {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.twofactor.loaded .loading-indicator {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.twofactor.disabled #disable-2fa,
|
||||||
|
.twofactor.enabled #totp-setup {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.twofactor.disabled #totp-setup,
|
||||||
|
.twofactor.enabled #disable-2fa {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.twofactor #totp-setup-qr img {
|
||||||
|
display: block;
|
||||||
|
width: 256px;
|
||||||
|
max-width: 100%;
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.twofactor #output-2fa.visible {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<h2>Two-Factor Authentication</h2>
|
||||||
|
|
||||||
|
<p>When two-factor authentication is enabled, you will be prompted to enter a six digit code from an
|
||||||
|
authenticator app (usually on your phone) when you log into this control panel.</p>
|
||||||
|
|
||||||
|
<div class="panel panel-danger">
|
||||||
|
<div class="panel-heading">
|
||||||
|
Enabling two-factor authentication does not protect access to your email
|
||||||
|
</div>
|
||||||
|
<div class="panel-body">
|
||||||
|
Enabling two-factor authentication on this page only limits access to this control panel. Remember that most websites allow you to
|
||||||
|
reset your password by checking your email, so anyone with access to your email can typically take over
|
||||||
|
your other accounts. Additionally, if your email address or any alias that forwards to your email
|
||||||
|
address is a typical domain control validation address (e.g admin@, administrator@, postmaster@, hostmaster@,
|
||||||
|
webmaster@, abuse@), extra care should be taken to protect the account. <strong>Always use a strong password,
|
||||||
|
and ensure every administrator account for this control panel does the same.</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="twofactor">
|
||||||
|
<div class="loading-indicator">Loading...</div>
|
||||||
|
|
||||||
|
<form id="totp-setup">
|
||||||
|
<h3>Setup Instructions</h3>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<p>1. Install <a href="https://freeotp.github.io/">FreeOTP</a> or <a href="https://www.pcworld.com/article/3225913/what-is-two-factor-authentication-and-which-2fa-apps-are-best.html">any
|
||||||
|
other two-factor authentication app</a> that supports TOTP.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<p style="margin-bottom: 0">2. Scan the QR code in the app or directly enter the secret into the app:</p>
|
||||||
|
<div id="totp-setup-qr"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="otp-label" style="font-weight: normal">3. Optionally, give your device a label so that you can remember what device you set it up on:</label>
|
||||||
|
<input type="text" id="totp-setup-label" class="form-control" placeholder="my phone" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="otp" style="font-weight: normal">4. Use the app to generate your first six-digit code and enter it here:</label>
|
||||||
|
<input type="text" id="totp-setup-token" class="form-control" placeholder="6-digit code" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input type="hidden" id="totp-setup-secret" />
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<p>When you click Enable Two-Factor Authentication, you will be logged out of the control panel and will have to log in
|
||||||
|
again, now using your two-factor authentication app.</p>
|
||||||
|
<button id="totp-setup-submit" disabled type="submit" class="btn">Enable Two-Factor Authentication</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form id="disable-2fa">
|
||||||
|
<div class="form-group">
|
||||||
|
<p>Two-factor authentication is active for your account<span id="mfa-device-label"></span>.</p>
|
||||||
|
<p>You will have to log into the admin panel again after disabling two-factor authentication.</p>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<button type="submit" class="btn btn-danger">Disable Two-Factor Authentication</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div id="output-2fa" class="panel panel-danger">
|
||||||
|
<div class="panel-body"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var el = {
|
||||||
|
disableForm: document.getElementById('disable-2fa'),
|
||||||
|
output: document.getElementById('output-2fa'),
|
||||||
|
totpSetupForm: document.getElementById('totp-setup'),
|
||||||
|
totpSetupToken: document.getElementById('totp-setup-token'),
|
||||||
|
totpSetupSecret: document.getElementById('totp-setup-secret'),
|
||||||
|
totpSetupLabel: document.getElementById('totp-setup-label'),
|
||||||
|
totpQr: document.getElementById('totp-setup-qr'),
|
||||||
|
totpSetupSubmit: document.querySelector('#totp-setup-submit'),
|
||||||
|
wrapper: document.querySelector('.twofactor')
|
||||||
|
}
|
||||||
|
|
||||||
|
function update_setup_disabled(evt) {
|
||||||
|
var val = evt.target.value.trim();
|
||||||
|
|
||||||
|
if (
|
||||||
|
typeof val !== 'string' ||
|
||||||
|
typeof el.totpSetupSecret.value !== 'string' ||
|
||||||
|
val.length !== 6 ||
|
||||||
|
el.totpSetupSecret.value.length !== 32 ||
|
||||||
|
!(/^\+?\d+$/.test(val))
|
||||||
|
) {
|
||||||
|
el.totpSetupSubmit.setAttribute('disabled', '');
|
||||||
|
} else {
|
||||||
|
el.totpSetupSubmit.removeAttribute('disabled');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render_totp_setup(provisioned_totp) {
|
||||||
|
var img = document.createElement('img');
|
||||||
|
img.src = "data:image/png;base64," + provisioned_totp.qr_code_base64;
|
||||||
|
|
||||||
|
var code = document.createElement('div');
|
||||||
|
code.innerHTML = `Secret: ${provisioned_totp.secret}`;
|
||||||
|
|
||||||
|
el.totpQr.appendChild(img);
|
||||||
|
el.totpQr.appendChild(code);
|
||||||
|
|
||||||
|
el.totpSetupToken.addEventListener('input', update_setup_disabled);
|
||||||
|
el.totpSetupForm.addEventListener('submit', do_enable_totp);
|
||||||
|
|
||||||
|
el.totpSetupSecret.setAttribute('value', provisioned_totp.secret);
|
||||||
|
|
||||||
|
el.wrapper.classList.add('disabled');
|
||||||
|
}
|
||||||
|
|
||||||
|
function render_disable(mfa) {
|
||||||
|
el.disableForm.addEventListener('submit', do_disable);
|
||||||
|
el.wrapper.classList.add('enabled');
|
||||||
|
if (mfa.label)
|
||||||
|
$("#mfa-device-label").text(" on device '" + mfa.label + "'");
|
||||||
|
}
|
||||||
|
|
||||||
|
function hide_error() {
|
||||||
|
el.output.querySelector('.panel-body').innerHTML = '';
|
||||||
|
el.output.classList.remove('visible');
|
||||||
|
}
|
||||||
|
|
||||||
|
function render_error(msg) {
|
||||||
|
el.output.querySelector('.panel-body').innerHTML = msg;
|
||||||
|
el.output.classList.add('visible');
|
||||||
|
}
|
||||||
|
|
||||||
|
function reset_view() {
|
||||||
|
el.wrapper.classList.remove('loaded', 'disabled', 'enabled');
|
||||||
|
|
||||||
|
el.disableForm.removeEventListener('submit', do_disable);
|
||||||
|
|
||||||
|
hide_error();
|
||||||
|
|
||||||
|
el.totpSetupForm.reset();
|
||||||
|
el.totpSetupForm.removeEventListener('submit', do_enable_totp);
|
||||||
|
|
||||||
|
el.totpSetupSecret.setAttribute('value', '');
|
||||||
|
el.totpSetupToken.removeEventListener('input', update_setup_disabled);
|
||||||
|
|
||||||
|
el.totpSetupSubmit.setAttribute('disabled', '');
|
||||||
|
el.totpQr.innerHTML = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function show_mfa() {
|
||||||
|
reset_view();
|
||||||
|
|
||||||
|
api(
|
||||||
|
'/mfa/status',
|
||||||
|
'POST',
|
||||||
|
{},
|
||||||
|
function(res) {
|
||||||
|
el.wrapper.classList.add('loaded');
|
||||||
|
|
||||||
|
var has_mfa = false;
|
||||||
|
res.enabled_mfa.forEach(function(mfa) {
|
||||||
|
if (mfa.type == "totp") {
|
||||||
|
render_disable(mfa);
|
||||||
|
has_mfa = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!has_mfa)
|
||||||
|
render_totp_setup(res.new_mfa.totp);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function do_disable(evt) {
|
||||||
|
evt.preventDefault();
|
||||||
|
hide_error();
|
||||||
|
|
||||||
|
api(
|
||||||
|
'/mfa/disable',
|
||||||
|
'POST',
|
||||||
|
{ type: 'totp' },
|
||||||
|
function() {
|
||||||
|
do_logout();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function do_enable_totp(evt) {
|
||||||
|
evt.preventDefault();
|
||||||
|
hide_error();
|
||||||
|
|
||||||
|
api(
|
||||||
|
'/mfa/totp/enable',
|
||||||
|
'POST',
|
||||||
|
{
|
||||||
|
token: $(el.totpSetupToken).val(),
|
||||||
|
secret: $(el.totpSetupSecret).val(),
|
||||||
|
label: $(el.totpSetupLabel).val()
|
||||||
|
},
|
||||||
|
function(res) { do_logout(); },
|
||||||
|
function(res) { render_error(res); }
|
||||||
|
);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
20
management/templates/munin.html
Normal file
20
management/templates/munin.html
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<h2>Munin Monitoring</h2>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<p>Opening munin in a new tab... You may need to allow pop-ups for this site.</p>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function show_munin() {
|
||||||
|
// Set the cookie.
|
||||||
|
api(
|
||||||
|
"/munin",
|
||||||
|
"GET",
|
||||||
|
{ },
|
||||||
|
function(r) {
|
||||||
|
// Redirect.
|
||||||
|
window.open("/admin/munin/index.html", "_blank");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -30,9 +30,9 @@
|
|||||||
|
|
||||||
<table class="table">
|
<table class="table">
|
||||||
<thead><tr><th>For...</th> <th>Use...</th></tr></thead>
|
<thead><tr><th>For...</th> <th>Use...</th></tr></thead>
|
||||||
<tr><td>Contacts and Calendar</td> <td><a href="https://play.google.com/store/apps/details?id=at.bitfire.davdroid">DAVdroid</a> ($3.69; free <a href="https://f-droid.org/packages/at.bitfire.davdroid/">here</a>)</td></tr>
|
<tr><td>Contacts and Calendar</td> <td><a href="https://play.google.com/store/apps/details?id=at.bitfire.davdroid">DAVx⁵</a> ($5.99; free <a href="https://f-droid.org/packages/at.bitfire.davdroid/">here</a>)</td></tr>
|
||||||
<tr><td>Only Contacts</td> <td><a href="https://play.google.com/store/apps/details?id=org.dmfs.carddav.sync">CardDAV-Sync free beta</a> (free)</td></tr>
|
<tr><td>Only Contacts</td> <td><a href="https://play.google.com/store/apps/details?id=org.dmfs.carddav.sync">CardDAV-Sync free</a> (free)</td></tr>
|
||||||
<tr><td>Only Calendar</td> <td><a href="https://play.google.com/store/apps/details?id=org.dmfs.caldav.lib">CalDAV-Sync</a> ($2.89)</td></tr>
|
<tr><td>Only Calendar</td> <td><a href="https://play.google.com/store/apps/details?id=org.dmfs.caldav.lib">CalDAV-Sync</a> ($2.99)</td></tr>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
<p>Use the following settings:</p>
|
<p>Use the following settings:</p>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
<h2>Backup Status</h2>
|
<h2>Backup Status</h2>
|
||||||
|
|
||||||
<p>The box makes an incremental backup each night. By default the backup is stored on the machine itself, but you can also have it stored on Amazon S3.</p>
|
<p>The box makes an incremental backup each night. By default the backup is stored on the machine itself, but you can also store it on S3-compatible services like Amazon Web Services (AWS).</p>
|
||||||
|
|
||||||
<h3>Configuration</h3>
|
<h3>Configuration</h3>
|
||||||
|
|
||||||
@@ -17,7 +17,8 @@
|
|||||||
<option value="off">Nowhere (Disable Backups)</option>
|
<option value="off">Nowhere (Disable Backups)</option>
|
||||||
<option value="local">{{hostname}}</option>
|
<option value="local">{{hostname}}</option>
|
||||||
<option value="rsync">rsync</option>
|
<option value="rsync">rsync</option>
|
||||||
<option value="s3">Amazon S3</option>
|
<option value="s3">S3 (Amazon or compatible) </option>
|
||||||
|
<option value="b2">Backblaze B2</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -72,8 +73,8 @@
|
|||||||
<!-- S3 BACKUP -->
|
<!-- S3 BACKUP -->
|
||||||
<div class="form-group backup-target-s3">
|
<div class="form-group backup-target-s3">
|
||||||
<div class="col-sm-10 col-sm-offset-2">
|
<div class="col-sm-10 col-sm-offset-2">
|
||||||
<p>Backups are stored in an Amazon Web Services S3 bucket. You must have an AWS account already.</p>
|
<p>Backups are stored in an S3-compatible bucket. You must have an AWS or other S3 service account already.</p>
|
||||||
<p>You MUST manually copy the encryption password from <tt class="backup-encpassword-file"></tt> to a safe and secure location. You will need this file to decrypt backup files. It is NOT stored in your Amazon S3 bucket.</p>
|
<p>You MUST manually copy the encryption password from <tt class="backup-encpassword-file"></tt> to a safe and secure location. You will need this file to decrypt backup files. It is <b>NOT</b> stored in your S3 bucket.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group backup-target-s3">
|
<div class="form-group backup-target-s3">
|
||||||
@@ -83,7 +84,7 @@
|
|||||||
{% for name, host in backup_s3_hosts %}
|
{% for name, host in backup_s3_hosts %}
|
||||||
<option value="{{host}}">{{name}}</option>
|
<option value="{{host}}">{{name}}</option>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
<option value="other">Other</option>
|
<option value="other">Other (non AWS)</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -111,12 +112,37 @@
|
|||||||
<input type="text" class="form-control" rows="1" id="backup-target-pass">
|
<input type="text" class="form-control" rows="1" id="backup-target-pass">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- Backblaze -->
|
||||||
|
<div class="form-group backup-target-b2">
|
||||||
|
<div class="col-sm-10 col-sm-offset-2">
|
||||||
|
<p>Backups are stored in a <a href="https://www.backblaze.com/" target="_blank" rel="noreferrer">Backblaze</a> B2 bucket. You must have a Backblaze account already.</p>
|
||||||
|
<p>You MUST manually copy the encryption password from <tt class="backup-encpassword-file"></tt> to a safe and secure location. You will need this file to decrypt backup files. It is NOT stored in your Backblaze B2 bucket.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group backup-target-b2">
|
||||||
|
<label for="backup-target-b2-user" class="col-sm-2 control-label">B2 Application KeyID</label>
|
||||||
|
<div class="col-sm-8">
|
||||||
|
<input type="text" class="form-control" rows="1" id="backup-target-b2-user">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group backup-target-b2">
|
||||||
|
<label for="backup-target-b2-pass" class="col-sm-2 control-label">B2 Application Key</label>
|
||||||
|
<div class="col-sm-8">
|
||||||
|
<input type="text" class="form-control" rows="1" id="backup-target-b2-pass">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group backup-target-b2">
|
||||||
|
<label for="backup-target-b2-bucket" class="col-sm-2 control-label">B2 Bucket</label>
|
||||||
|
<div class="col-sm-8">
|
||||||
|
<input type="text" class="form-control" rows="1" id="backup-target-b2-bucket">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<!-- Common -->
|
<!-- Common -->
|
||||||
<div class="form-group backup-target-local backup-target-rsync backup-target-s3">
|
<div class="form-group backup-target-local backup-target-rsync backup-target-s3 backup-target-b2">
|
||||||
<label for="min-age" class="col-sm-2 control-label">Days:</label>
|
<label for="min-age" class="col-sm-2 control-label">Retention Days:</label>
|
||||||
<div class="col-sm-8">
|
<div class="col-sm-8">
|
||||||
<input type="number" class="form-control" rows="1" id="min-age">
|
<input type="number" class="form-control" rows="1" id="min-age">
|
||||||
<div class="small" style="margin-top: 2px">This is the <i>minimum</i> number of days backup data is kept for. The box makes an incremental backup, so backup data is often kept much longer. An incremental backup file that is less than this number of days old requires that all previous increments back to the most recent full backup, plus that full backup, remain available.</div>
|
<div class="small" style="margin-top: 2px">This is the minimum time backup data is kept for. The box makes an incremental backup most nights, which requires that previous backups back to the most recent full backup be preserved, so backup data is often kept much longer than this setting. Full backups are made periodically when the incremental backup data size exceeds a limit.</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
@@ -144,7 +170,7 @@
|
|||||||
|
|
||||||
function toggle_form() {
|
function toggle_form() {
|
||||||
var target_type = $("#backup-target-type").val();
|
var target_type = $("#backup-target-type").val();
|
||||||
$(".backup-target-local, .backup-target-rsync, .backup-target-s3").hide();
|
$(".backup-target-local, .backup-target-rsync, .backup-target-s3, .backup-target-b2").hide();
|
||||||
$(".backup-target-" + target_type).show();
|
$(".backup-target-" + target_type).show();
|
||||||
|
|
||||||
init_inputs(target_type);
|
init_inputs(target_type);
|
||||||
@@ -215,7 +241,7 @@ function show_system_backup() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function show_custom_backup() {
|
function show_custom_backup() {
|
||||||
$(".backup-target-local, .backup-target-rsync, .backup-target-s3").hide();
|
$(".backup-target-local, .backup-target-rsync, .backup-target-s3, .backup-target-b2").hide();
|
||||||
api(
|
api(
|
||||||
"/system/backup/config",
|
"/system/backup/config",
|
||||||
"GET",
|
"GET",
|
||||||
@@ -245,6 +271,15 @@ function show_custom_backup() {
|
|||||||
var host = hostpath.shift();
|
var host = hostpath.shift();
|
||||||
$("#backup-target-s3-host").val(host);
|
$("#backup-target-s3-host").val(host);
|
||||||
$("#backup-target-s3-path").val(hostpath.join('/'));
|
$("#backup-target-s3-path").val(hostpath.join('/'));
|
||||||
|
} else if (r.target.substring(0, 5) == "b2://") {
|
||||||
|
$("#backup-target-type").val("b2");
|
||||||
|
var targetPath = r.target.substring(5);
|
||||||
|
var b2_application_keyid = targetPath.split(':')[0];
|
||||||
|
var b2_applicationkey = targetPath.split(':')[1].split('@')[0];
|
||||||
|
var b2_bucket = targetPath.split('@')[1];
|
||||||
|
$("#backup-target-b2-user").val(b2_application_keyid);
|
||||||
|
$("#backup-target-b2-pass").val(b2_applicationkey);
|
||||||
|
$("#backup-target-b2-bucket").val(b2_bucket);
|
||||||
}
|
}
|
||||||
toggle_form()
|
toggle_form()
|
||||||
})
|
})
|
||||||
@@ -264,6 +299,11 @@ function set_custom_backup() {
|
|||||||
target = "rsync://" + $("#backup-target-rsync-user").val() + "@" + $("#backup-target-rsync-host").val()
|
target = "rsync://" + $("#backup-target-rsync-user").val() + "@" + $("#backup-target-rsync-host").val()
|
||||||
+ "/" + $("#backup-target-rsync-path").val();
|
+ "/" + $("#backup-target-rsync-path").val();
|
||||||
target_user = '';
|
target_user = '';
|
||||||
|
} else if (target_type == "b2") {
|
||||||
|
target = 'b2://' + $('#backup-target-b2-user').val() + ':' + $('#backup-target-b2-pass').val()
|
||||||
|
+ '@' + $('#backup-target-b2-bucket').val()
|
||||||
|
target_user = '';
|
||||||
|
target_pass = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
<h2>Users</h2>
|
<h2>Users</h2>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
#user_table h4 { margin: 1em 0 0 0; }
|
|
||||||
#user_table tr.account_inactive td.address { color: #888; text-decoration: line-through; }
|
#user_table tr.account_inactive td.address { color: #888; text-decoration: line-through; }
|
||||||
#user_table .actions { margin-top: .33em; font-size: 95%; }
|
#user_table .actions { margin-top: .33em; font-size: 95%; }
|
||||||
#user_table .account_inactive .if_active { display: none; }
|
#user_table .account_inactive .if_active { display: none; }
|
||||||
@@ -31,7 +30,7 @@
|
|||||||
<button type="submit" class="btn btn-primary">Add User</button>
|
<button type="submit" class="btn btn-primary">Add User</button>
|
||||||
</form>
|
</form>
|
||||||
<ul style="margin-top: 1em; padding-left: 1.5em; font-size: 90%;">
|
<ul style="margin-top: 1em; padding-left: 1.5em; font-size: 90%;">
|
||||||
<li>Passwords must be at least eight characters consisting of English lettters and numbers only. For best results, <a href="#" onclick="return generate_random_password()">generate a random password</a>.</li>
|
<li>Passwords must be at least eight characters consisting of English letters and numbers only. For best results, <a href="#" onclick="return generate_random_password()">generate a random password</a>.</li>
|
||||||
<li>Use <a href="#" onclick="return show_panel('aliases')">aliases</a> to create email addresses that forward to existing accounts.</li>
|
<li>Use <a href="#" onclick="return show_panel('aliases')">aliases</a> to create email addresses that forward to existing accounts.</li>
|
||||||
<li>Administrators get access to this control panel.</li>
|
<li>Administrators get access to this control panel.</li>
|
||||||
<li>User accounts cannot contain any international (non-ASCII) characters, but <a href="#" onclick="return show_panel('aliases');">aliases</a> can.</li>
|
<li>User accounts cannot contain any international (non-ASCII) characters, but <a href="#" onclick="return show_panel('aliases');">aliases</a> can.</li>
|
||||||
@@ -99,7 +98,7 @@
|
|||||||
<thead><th>Verb</th> <th>Action</th><th></th></thead>
|
<thead><th>Verb</th> <th>Action</th><th></th></thead>
|
||||||
<tr><td>GET</td><td><i>(none)</i></td> <td>Returns a list of existing mail users. Adding <code>?format=json</code> to the URL will give JSON-encoded results.</td></tr>
|
<tr><td>GET</td><td><i>(none)</i></td> <td>Returns a list of existing mail users. Adding <code>?format=json</code> to the URL will give JSON-encoded results.</td></tr>
|
||||||
<tr><td>POST</td><td>/add</td> <td>Adds a new mail user. Required POST-body parameters are <code>email</code> and <code>password</code>.</td></tr>
|
<tr><td>POST</td><td>/add</td> <td>Adds a new mail user. Required POST-body parameters are <code>email</code> and <code>password</code>.</td></tr>
|
||||||
<tr><td>POST</td><td>/remove</td> <td>Removes a mail user. Required POST-by parameter is <code>email</code>.</td></tr>
|
<tr><td>POST</td><td>/remove</td> <td>Removes a mail user. Required POST-body parameter is <code>email</code>.</td></tr>
|
||||||
<tr><td>POST</td><td>/privileges/add</td> <td>Used to make a mail user an admin. Required POST-body parameters are <code>email</code> and <code>privilege=admin</code>.</td></tr>
|
<tr><td>POST</td><td>/privileges/add</td> <td>Used to make a mail user an admin. Required POST-body parameters are <code>email</code> and <code>privilege=admin</code>.</td></tr>
|
||||||
<tr><td>POST</td><td>/privileges/remove</td> <td>Used to remove the admin privilege from a mail user. Required POST-body parameter is <code>email</code>.</td></tr>
|
<tr><td>POST</td><td>/privileges/remove</td> <td>Used to remove the admin privilege from a mail user. Required POST-body parameter is <code>email</code>.</td></tr>
|
||||||
</table>
|
</table>
|
||||||
@@ -134,8 +133,8 @@ function show_users() {
|
|||||||
function(r) {
|
function(r) {
|
||||||
$('#user_table tbody').html("");
|
$('#user_table tbody').html("");
|
||||||
for (var i = 0; i < r.length; i++) {
|
for (var i = 0; i < r.length; i++) {
|
||||||
var hdr = $("<tr><td colspan='3'><h4/></td></tr>");
|
var hdr = $("<tr><th colspan='2' style='background-color: #EEE'></th></tr>");
|
||||||
hdr.find('h4').text(r[i].domain);
|
hdr.find('th').text(r[i].domain);
|
||||||
$('#user_table tbody').append(hdr);
|
$('#user_table tbody').append(hdr);
|
||||||
|
|
||||||
for (var k = 0; k < r[i].users.length; k++) {
|
for (var k = 0; k < r[i].users.length; k++) {
|
||||||
@@ -204,7 +203,7 @@ function users_set_password(elem) {
|
|||||||
var email = $(elem).parents('tr').attr('data-email');
|
var email = $(elem).parents('tr').attr('data-email');
|
||||||
|
|
||||||
var yourpw = "";
|
var yourpw = "";
|
||||||
if (api_credentials != null && email == api_credentials[0])
|
if (api_credentials != null && email == api_credentials.username)
|
||||||
yourpw = "<p class='text-danger'>If you change your own password, you will be logged out of this control panel and will need to log in again.</p>";
|
yourpw = "<p class='text-danger'>If you change your own password, you will be logged out of this control panel and will need to log in again.</p>";
|
||||||
|
|
||||||
show_modal_confirm(
|
show_modal_confirm(
|
||||||
@@ -233,7 +232,7 @@ function users_remove(elem) {
|
|||||||
var email = $(elem).parents('tr').attr('data-email');
|
var email = $(elem).parents('tr').attr('data-email');
|
||||||
|
|
||||||
// can't remove yourself
|
// can't remove yourself
|
||||||
if (api_credentials != null && email == api_credentials[0]) {
|
if (api_credentials != null && email == api_credentials.username) {
|
||||||
show_modal_error("Archive User", "You cannot archive your own account.");
|
show_modal_error("Archive User", "You cannot archive your own account.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -265,7 +264,7 @@ function mod_priv(elem, add_remove) {
|
|||||||
var priv = $(elem).parents('td').find('.name').text();
|
var priv = $(elem).parents('td').find('.name').text();
|
||||||
|
|
||||||
// can't remove your own admin access
|
// can't remove your own admin access
|
||||||
if (priv == "admin" && add_remove == "remove" && api_credentials != null && email == api_credentials[0]) {
|
if (priv == "admin" && add_remove == "remove" && api_credentials != null && email == api_credentials.username) {
|
||||||
show_modal_error("Modify Privileges", "You cannot remove the admin privilege from yourself.");
|
show_modal_error("Modify Privileges", "You cannot remove the admin privilege from yourself.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
16
management/templates/welcome.html
Normal file
16
management/templates/welcome.html
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<style>
|
||||||
|
.title {
|
||||||
|
margin: 1em;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.subtitle {
|
||||||
|
margin: 2em;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<h1 class="title">{{hostname}}</h1>
|
||||||
|
|
||||||
|
<p class="subtitle">Welcome to your Mail-in-a-Box control panel.</p>
|
||||||
|
|
||||||
@@ -9,7 +9,7 @@ from dns_update import get_custom_dns_config, get_dns_zones
|
|||||||
from ssl_certificates import get_ssl_certificates, get_domain_ssl_files, check_certificate
|
from ssl_certificates import get_ssl_certificates, get_domain_ssl_files, check_certificate
|
||||||
from utils import shell, safe_domain_name, sort_domains
|
from utils import shell, safe_domain_name, sort_domains
|
||||||
|
|
||||||
def get_web_domains(env, include_www_redirects=True, exclude_dns_elsewhere=True):
|
def get_web_domains(env, include_www_redirects=True, include_auto=True, exclude_dns_elsewhere=True):
|
||||||
# What domains should we serve HTTP(S) for?
|
# What domains should we serve HTTP(S) for?
|
||||||
domains = set()
|
domains = set()
|
||||||
|
|
||||||
@@ -18,23 +18,27 @@ def get_web_domains(env, include_www_redirects=True, exclude_dns_elsewhere=True)
|
|||||||
# if the user wants to make one.
|
# if the user wants to make one.
|
||||||
domains |= get_mail_domains(env)
|
domains |= get_mail_domains(env)
|
||||||
|
|
||||||
if include_www_redirects:
|
if include_www_redirects and include_auto:
|
||||||
# Add 'www.' subdomains that we want to provide default redirects
|
# Add 'www.' subdomains that we want to provide default redirects
|
||||||
# to the main domain for. We'll add 'www.' to any DNS zones, i.e.
|
# to the main domain for. We'll add 'www.' to any DNS zones, i.e.
|
||||||
# the topmost of each domain we serve.
|
# the topmost of each domain we serve.
|
||||||
domains |= set('www.' + zone for zone, zonefile in get_dns_zones(env))
|
domains |= set('www.' + zone for zone, zonefile in get_dns_zones(env))
|
||||||
|
|
||||||
|
if include_auto:
|
||||||
|
# Add Autoconfiguration domains for domains that there are user accounts at:
|
||||||
|
# 'autoconfig.' for Mozilla Thunderbird auto setup.
|
||||||
|
# 'autodiscover.' for ActiveSync autodiscovery (Z-Push).
|
||||||
|
domains |= set('autoconfig.' + maildomain for maildomain in get_mail_domains(env, users_only=True))
|
||||||
|
domains |= set('autodiscover.' + maildomain for maildomain in get_mail_domains(env, users_only=True))
|
||||||
|
|
||||||
|
# 'mta-sts.' for MTA-STS support for all domains that have email addresses.
|
||||||
|
domains |= set('mta-sts.' + maildomain for maildomain in get_mail_domains(env))
|
||||||
|
|
||||||
if exclude_dns_elsewhere:
|
if exclude_dns_elsewhere:
|
||||||
# ...Unless the domain has an A/AAAA record that maps it to a different
|
# ...Unless the domain has an A/AAAA record that maps it to a different
|
||||||
# IP address than this box. Remove those domains from our list.
|
# IP address than this box. Remove those domains from our list.
|
||||||
domains -= get_domains_with_a_records(env)
|
domains -= get_domains_with_a_records(env)
|
||||||
|
|
||||||
# Add Autoconfiguration domains, allowing us to serve correct SSL certs.
|
|
||||||
# 'autoconfig.' for Mozilla Thunderbird auto setup.
|
|
||||||
# 'autodiscover.' for Activesync autodiscovery.
|
|
||||||
domains |= set('autoconfig.' + maildomain for maildomain in get_mail_domains(env))
|
|
||||||
domains |= set('autodiscover.' + maildomain for maildomain in get_mail_domains(env))
|
|
||||||
|
|
||||||
# Ensure the PRIMARY_HOSTNAME is in the list so we can serve webmail
|
# Ensure the PRIMARY_HOSTNAME is in the list so we can serve webmail
|
||||||
# as well as Z-Push for Exchange ActiveSync. This can't be removed
|
# as well as Z-Push for Exchange ActiveSync. This can't be removed
|
||||||
# by a custom A/AAAA record and is never a 'www.' redirect.
|
# by a custom A/AAAA record and is never a 'www.' redirect.
|
||||||
@@ -143,7 +147,7 @@ def make_domain_config(domain, templates, ssl_certificates, env):
|
|||||||
finally:
|
finally:
|
||||||
f.close()
|
f.close()
|
||||||
return sha1.hexdigest()
|
return sha1.hexdigest()
|
||||||
nginx_conf_extra += "# ssl files sha1: %s / %s\n" % (hashfile(tls_cert["private-key"]), hashfile(tls_cert["certificate"]))
|
nginx_conf_extra += "\t# ssl files sha1: %s / %s\n" % (hashfile(tls_cert["private-key"]), hashfile(tls_cert["certificate"]))
|
||||||
|
|
||||||
# Add in any user customizations in YAML format.
|
# Add in any user customizations in YAML format.
|
||||||
hsts = "yes"
|
hsts = "yes"
|
||||||
@@ -155,9 +159,37 @@ def make_domain_config(domain, templates, ssl_certificates, env):
|
|||||||
|
|
||||||
# any proxy or redirect here?
|
# any proxy or redirect here?
|
||||||
for path, url in yaml.get("proxies", {}).items():
|
for path, url in yaml.get("proxies", {}).items():
|
||||||
|
# Parse some flags in the fragment of the URL.
|
||||||
|
pass_http_host_header = False
|
||||||
|
proxy_redirect_off = False
|
||||||
|
frame_options_header_sameorigin = False
|
||||||
|
m = re.search("#(.*)$", url)
|
||||||
|
if m:
|
||||||
|
for flag in m.group(1).split(","):
|
||||||
|
if flag == "pass-http-host":
|
||||||
|
pass_http_host_header = True
|
||||||
|
elif flag == "no-proxy-redirect":
|
||||||
|
proxy_redirect_off = True
|
||||||
|
elif flag == "frame-options-sameorigin":
|
||||||
|
frame_options_header_sameorigin = True
|
||||||
|
url = re.sub("#(.*)$", "", url)
|
||||||
|
|
||||||
nginx_conf_extra += "\tlocation %s {" % path
|
nginx_conf_extra += "\tlocation %s {" % path
|
||||||
nginx_conf_extra += "\n\t\tproxy_pass %s;" % url
|
nginx_conf_extra += "\n\t\tproxy_pass %s;" % url
|
||||||
|
if proxy_redirect_off:
|
||||||
|
nginx_conf_extra += "\n\t\tproxy_redirect off;"
|
||||||
|
if pass_http_host_header:
|
||||||
|
nginx_conf_extra += "\n\t\tproxy_set_header Host $http_host;"
|
||||||
|
if frame_options_header_sameorigin:
|
||||||
|
nginx_conf_extra += "\n\t\tproxy_set_header X-Frame-Options SAMEORIGIN;"
|
||||||
nginx_conf_extra += "\n\t\tproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;"
|
nginx_conf_extra += "\n\t\tproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;"
|
||||||
|
nginx_conf_extra += "\n\t\tproxy_set_header X-Forwarded-Host $http_host;"
|
||||||
|
nginx_conf_extra += "\n\t\tproxy_set_header X-Forwarded-Proto $scheme;"
|
||||||
|
nginx_conf_extra += "\n\t\tproxy_set_header X-Real-IP $remote_addr;"
|
||||||
|
nginx_conf_extra += "\n\t}\n"
|
||||||
|
for path, alias in yaml.get("aliases", {}).items():
|
||||||
|
nginx_conf_extra += "\tlocation %s {" % path
|
||||||
|
nginx_conf_extra += "\n\t\talias %s;" % alias
|
||||||
nginx_conf_extra += "\n\t}\n"
|
nginx_conf_extra += "\n\t}\n"
|
||||||
for path, url in yaml.get("redirects", {}).items():
|
for path, url in yaml.get("redirects", {}).items():
|
||||||
nginx_conf_extra += "\trewrite %s %s permanent;\n" % (path, url)
|
nginx_conf_extra += "\trewrite %s %s permanent;\n" % (path, url)
|
||||||
@@ -167,9 +199,9 @@ def make_domain_config(domain, templates, ssl_certificates, env):
|
|||||||
|
|
||||||
# Add the HSTS header.
|
# Add the HSTS header.
|
||||||
if hsts == "yes":
|
if hsts == "yes":
|
||||||
nginx_conf_extra += "add_header Strict-Transport-Security max-age=15768000;\n"
|
nginx_conf_extra += "\tadd_header Strict-Transport-Security \"max-age=15768000\" always;\n"
|
||||||
elif hsts == "preload":
|
elif hsts == "preload":
|
||||||
nginx_conf_extra += "add_header Strict-Transport-Security \"max-age=15768000; includeSubDomains; preload\";\n"
|
nginx_conf_extra += "\tadd_header Strict-Transport-Security \"max-age=15768000; includeSubDomains; preload\" always;\n"
|
||||||
|
|
||||||
# Add in any user customizations in the includes/ folder.
|
# Add in any user customizations in the includes/ folder.
|
||||||
nginx_conf_custom_include = os.path.join(env["STORAGE_ROOT"], "www", safe_domain_name(domain) + ".conf")
|
nginx_conf_custom_include = os.path.join(env["STORAGE_ROOT"], "www", safe_domain_name(domain) + ".conf")
|
||||||
@@ -230,3 +262,4 @@ def get_web_domains_info(env):
|
|||||||
}
|
}
|
||||||
for domain in get_web_domains(env)
|
for domain in get_web_domains(env)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
34
security.md
34
security.md
@@ -3,7 +3,12 @@ Mail-in-a-Box Security Guide
|
|||||||
|
|
||||||
Mail-in-a-Box turns a fresh Ubuntu 18.04 LTS 64-bit machine into a mail server appliance by installing and configuring various components.
|
Mail-in-a-Box turns a fresh Ubuntu 18.04 LTS 64-bit machine into a mail server appliance by installing and configuring various components.
|
||||||
|
|
||||||
This page documents the security features of Mail-in-a-Box. The term “box” is used below to mean a configured Mail-in-a-Box.
|
This page documents the security posture of Mail-in-a-Box. The term “box” is used below to mean a configured Mail-in-a-Box.
|
||||||
|
|
||||||
|
Reporting Security Vulnerabilities
|
||||||
|
----------------------------------
|
||||||
|
|
||||||
|
Security vulnerabilities should be reported to the [project's maintainer](https://joshdata.me) via email.
|
||||||
|
|
||||||
Threat Model
|
Threat Model
|
||||||
------------
|
------------
|
||||||
@@ -32,27 +37,24 @@ The box's administrator and its (non-administrative) mail users must sometimes c
|
|||||||
|
|
||||||
These services are protected by [TLS](https://en.wikipedia.org/wiki/Transport_Layer_Security):
|
These services are protected by [TLS](https://en.wikipedia.org/wiki/Transport_Layer_Security):
|
||||||
|
|
||||||
* SMTP Submission (port 587). Mail users submit outbound mail through SMTP with STARTTLS on port 587.
|
* SMTP Submission (ports 465/587). Mail users submit outbound mail through SMTP with TLS (port 465) or STARTTLS (port 587).
|
||||||
* IMAP/POP (ports 993, 995). Mail users check for incoming mail through IMAP or POP over TLS.
|
* IMAP/POP (ports 993, 995). Mail users check for incoming mail through IMAP or POP over TLS.
|
||||||
* HTTPS (port 443). Webmail, the Exchange/ActiveSync protocol, the administrative control panel, and any static hosted websites are accessed over HTTPS.
|
* HTTPS (port 443). Webmail, the Exchange/ActiveSync protocol, the administrative control panel, and any static hosted websites are accessed over HTTPS.
|
||||||
|
|
||||||
The services all follow these rules:
|
The services all follow these rules:
|
||||||
|
|
||||||
* TLS certificates are generated with 2048-bit RSA keys and SHA-256 fingerprints. The box provides a self-signed certificate by default. The [setup guide](https://mailinabox.email/guide.html) explains how to verify the certificate fingerprint on first login. Users are encouraged to replace the certificate with a proper CA-signed one. ([source](setup/ssl.sh))
|
* TLS certificates are generated with 2048-bit RSA keys and SHA-256 fingerprints. The box provides a self-signed certificate by default. The [setup guide](https://mailinabox.email/guide.html) explains how to verify the certificate fingerprint on first login. Users are encouraged to replace the certificate with a proper CA-signed one. ([source](setup/ssl.sh))
|
||||||
* Only TLSv1, TLSv1.1 and TLSv1.2 are offered (the older SSL protocols are not offered).
|
* Only TLSv1.2+ are offered (the older SSL protocols are not offered).
|
||||||
* HTTPS, IMAP, and POP track the [Mozilla Intermediate Ciphers Recommendation](https://wiki.mozilla.org/Security/Server_Side_TLS), balancing security with supporting a wide range of mail clients. Diffie-Hellman ciphers use a 2048-bit key for forward secrecy. For more details, see the [output of SSLyze for these ports](tests/tls_results.txt).
|
* We track the [Mozilla Intermediate Ciphers Recommendation](https://wiki.mozilla.org/Security/Server_Side_TLS), balancing security with supporting a wide range of mail clients. Diffie-Hellman ciphers use a 2048-bit key for forward secrecy. For more details, see the [output of SSLyze for these ports](tests/tls_results.txt).
|
||||||
* SMTP (port 25) uses the Postfix medium grade ciphers and SMTP Submission (port 587) uses the Postfix high grade ciphers ([more info](http://www.postfix.org/postconf.5.html#smtpd_tls_mandatory_ciphers)).
|
|
||||||
|
|
||||||
Additionally:
|
Additionally:
|
||||||
|
|
||||||
* SMTP Submission (port 587) will not accept user credentials without STARTTLS (true also of SMTP on port 25 in case of client misconfiguration), and the submission port won't accept mail without encryption. The minimum cipher key length is 128 bits. (The box is of course configured not to be an open relay. User credentials are required to send outbound mail.) ([source](setup/mail-postfix.sh))
|
* SMTP Submission on port 587 will not accept user credentials without STARTTLS (true also of SMTP on port 25 in case of client misconfiguration), and the submission port won't accept mail without encryption. The minimum cipher key length is 128 bits. (The box is of course configured not to be an open relay. User credentials are required to send outbound mail.) ([source](setup/mail-postfix.sh))
|
||||||
* HTTPS (port 443): The HTTPS Strict Transport Security header is set. A redirect from HTTP to HTTPS is offered. The [Qualys SSL Labs test](https://www.ssllabs.com/ssltest) should report an A+ grade. ([source 1](conf/nginx-ssl.conf), [source 2](conf/nginx.conf))
|
* HTTPS (port 443): The HTTPS Strict Transport Security header is set. A redirect from HTTP to HTTPS is offered. The [Qualys SSL Labs test](https://www.ssllabs.com/ssltest) should report an A+ grade. ([source 1](conf/nginx-ssl.conf), [source 2](conf/nginx.conf))
|
||||||
|
|
||||||
### Password Storage
|
### Password Storage
|
||||||
|
|
||||||
The passwords for mail users are stored on disk using the [SHA512-CRYPT](http://man7.org/linux/man-pages/man3/crypt.3.html) hashing scheme. ([source](management/mailconfig.py))
|
The passwords for mail users are stored on disk using the [SHA512-CRYPT](http://man7.org/linux/man-pages/man3/crypt.3.html) hashing scheme. ([source](management/mailconfig.py)) Password changes (as well as changes to control panel two-factor authentication settings) expire any control panel login sessions.
|
||||||
|
|
||||||
When using the web-based administrative control panel, after logging in an API key is placed in the browser's local storage (rather than, say, the user's actual password). The API key is an HMAC based on the user's email address and current password, and it is keyed by a secret known only to the control panel service. By resetting an administrator's password, any HMACs previously generated for that user will expire.
|
|
||||||
|
|
||||||
### Console access
|
### Console access
|
||||||
|
|
||||||
@@ -66,12 +68,10 @@ If DNSSEC is enabled at the box's domain name's registrar, the SSHFP record that
|
|||||||
|
|
||||||
`fail2ban` provides some protection from brute-force login attacks (repeated logins that guess account passwords) by blocking offending IP addresses at the network level.
|
`fail2ban` provides some protection from brute-force login attacks (repeated logins that guess account passwords) by blocking offending IP addresses at the network level.
|
||||||
|
|
||||||
The following services are protected: SSH, IMAP (dovecot), SMTP submission (postfix), webmail (roundcube), Nextcloud/CalDAV/CardDAV (over HTTP), and the Mail-in-a-Box control panel & munin (over HTTP).
|
The following services are protected: SSH, IMAP (dovecot), SMTP submission (postfix), webmail (roundcube), Nextcloud/CalDAV/CardDAV (over HTTP), and the Mail-in-a-Box control panel (over HTTP).
|
||||||
|
|
||||||
Some other services running on the box may be missing fail2ban filters.
|
Some other services running on the box may be missing fail2ban filters.
|
||||||
|
|
||||||
`fail2ban` only blocks IPv4 addresses, however. If the box has a public IPv6 address, it is not protected from these attacks.
|
|
||||||
|
|
||||||
Outbound Mail
|
Outbound Mail
|
||||||
-------------
|
-------------
|
||||||
|
|
||||||
@@ -95,16 +95,20 @@ Domain policy records allow recipient MTAs to detect when the _domain_ part of o
|
|||||||
|
|
||||||
### User Policy
|
### User Policy
|
||||||
|
|
||||||
While domain policy records prevent other servers from sending mail with a "From:" header that matches a domain hosted on the box (see above), those policy records do not guarnatee that the user portion of the sender email address matches the actual sender. In enterprise environments where the box may host the mail of untrusted users, it is important to guard against users impersonating other users.
|
While domain policy records prevent other servers from sending mail with a "From:" header that matches a domain hosted on the box (see above), those policy records do not guarantee that the user portion of the sender email address matches the actual sender. In enterprise environments where the box may host the mail of untrusted users, it is important to guard against users impersonating other users.
|
||||||
|
|
||||||
The box restricts the envelope sender address (also called the return path or MAIL FROM address --- this is different from the "From:" header) that users may put into outbound mail. The envelope sender address must be either their own email address (their SMTP login username) or any alias that they are listed as a permitted sender of. (There is currently no restriction on the contents of the "From:" header.)
|
The box restricts the envelope sender address (also called the return path or MAIL FROM address --- this is different from the "From:" header) that users may put into outbound mail. The envelope sender address must be either their own email address (their SMTP login username) or any alias that they are listed as a permitted sender of. (There is currently no restriction on the contents of the "From:" header.)
|
||||||
|
|
||||||
Incoming Mail
|
Incoming Mail
|
||||||
-------------
|
-------------
|
||||||
|
|
||||||
### Encryption
|
### Encryption Settings
|
||||||
|
|
||||||
As discussed above, there is no way to require on-the-wire encryption of mail. When the box receives an incoming email (SMTP on port 25), it offers encryption (STARTTLS) but cannot require that senders use it because some senders may not support STARTTLS at all and other senders may support STARTTLS but not with the latest protocols/ciphers. To give senders the best chance at making use of encryption, the box offers protocols back to TLSv1 and ciphers with key lengths as low as 112 bits. Modern clients (senders) will make use of the 256-bit ciphers and Diffie-Hellman ciphers with a 2048-bit key for perfect forward secrecy, however. ([source](setup/mail-postfix.sh))
|
As with outbound email, there is no way to require on-the-wire encryption of incoming mail from all senders. When the box receives an incoming email (SMTP on port 25), it offers encryption (STARTTLS) but cannot require that senders use it because some senders may not support STARTTLS at all and other senders may support STARTTLS but not with the latest protocols/ciphers. To give senders the best chance at making use of encryption, the box offers protocols back to TLSv1 and ciphers with key lengths as low as 112 bits. Modern clients (senders) will make use of the 256-bit ciphers and Diffie-Hellman ciphers with a 2048-bit key for perfect forward secrecy, however. ([source](setup/mail-postfix.sh))
|
||||||
|
|
||||||
|
### MTA-STS
|
||||||
|
|
||||||
|
The box publishes a SMTP MTA Strict Transport Security ([SMTP MTA-STS](https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol#SMTP_MTA_Strict_Transport_Security)) policy (via DNS and HTTPS) in "enforce" mode. Senders that support MTA-STS will use a secure SMTP connection. (MTA-STS tells senders to connect and expect a signed TLS certificate for the "MX" domain without permitting a fallback to an unencrypted connection.)
|
||||||
|
|
||||||
### DANE
|
### DANE
|
||||||
|
|
||||||
|
|||||||
@@ -18,11 +18,11 @@ if [ -z "$TAG" ]; then
|
|||||||
# space, but if we put it in a comment it would confuse the status checks!)
|
# space, but if we put it in a comment it would confuse the status checks!)
|
||||||
# to get the latest version, so the first such line must be the one that we
|
# to get the latest version, so the first such line must be the one that we
|
||||||
# want to display in status checks.
|
# want to display in status checks.
|
||||||
if [ "`lsb_release -d | sed 's/.*:\s*//' | sed 's/18\.04\.[0-9]/18.04/' `" == "Ubuntu 18.04 LTS" ]; then
|
if [ "$(lsb_release -d | sed 's/.*:\s*//' | sed 's/18\.04\.[0-9]/18.04/' )" == "Ubuntu 18.04 LTS" ]; then
|
||||||
# This machine is running Ubuntu 18.04.
|
# This machine is running Ubuntu 18.04.
|
||||||
TAG=v0.42b
|
TAG=v57
|
||||||
|
|
||||||
elif [ "`lsb_release -d | sed 's/.*:\s*//' | sed 's/14\.04\.[0-9]/14.04/' `" == "Ubuntu 14.04 LTS" ]; then
|
elif [ "$(lsb_release -d | sed 's/.*:\s*//' | sed 's/14\.04\.[0-9]/14.04/' )" == "Ubuntu 14.04 LTS" ]; then
|
||||||
# This machine is running Ubuntu 14.04.
|
# This machine is running Ubuntu 14.04.
|
||||||
echo "You are installing the last version of Mail-in-a-Box that will"
|
echo "You are installing the last version of Mail-in-a-Box that will"
|
||||||
echo "support Ubuntu 14.04. If this is a new installation of Mail-in-a-Box,"
|
echo "support Ubuntu 14.04. If this is a new installation of Mail-in-a-Box,"
|
||||||
@@ -35,14 +35,14 @@ if [ -z "$TAG" ]; then
|
|||||||
|
|
||||||
else
|
else
|
||||||
echo "This script must be run on a system running Ubuntu 18.04 or Ubuntu 14.04."
|
echo "This script must be run on a system running Ubuntu 18.04 or Ubuntu 14.04."
|
||||||
exit
|
exit 1
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Are we running as root?
|
# Are we running as root?
|
||||||
if [[ $EUID -ne 0 ]]; then
|
if [[ $EUID -ne 0 ]]; then
|
||||||
echo "This script must be run as root. Did you leave out sudo?"
|
echo "This script must be run as root. Did you leave out sudo?"
|
||||||
exit
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Clone the Mail-in-a-Box repository if it doesn't exist.
|
# Clone the Mail-in-a-Box repository if it doesn't exist.
|
||||||
@@ -68,12 +68,12 @@ fi
|
|||||||
cd $HOME/mailinabox
|
cd $HOME/mailinabox
|
||||||
|
|
||||||
# Update it.
|
# Update it.
|
||||||
if [ "$TAG" != `git describe` ]; then
|
if [ "$TAG" != $(git describe) ]; then
|
||||||
echo Updating Mail-in-a-Box to $TAG . . .
|
echo Updating Mail-in-a-Box to $TAG . . .
|
||||||
git fetch --depth 1 --force --prune origin tag $TAG
|
git fetch --depth 1 --force --prune origin tag $TAG
|
||||||
if ! git checkout -q $TAG; then
|
if ! git checkout -q $TAG; then
|
||||||
echo "Update failed. Did you modify something in `pwd`?"
|
echo "Update failed. Did you modify something in $(pwd)?"
|
||||||
exit
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo
|
echo
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ if grep -q "ExternalIgnoreList" /etc/opendkim.conf; then
|
|||||||
else
|
else
|
||||||
# Add various configuration options to the end of `opendkim.conf`.
|
# Add various configuration options to the end of `opendkim.conf`.
|
||||||
cat >> /etc/opendkim.conf << EOF;
|
cat >> /etc/opendkim.conf << EOF;
|
||||||
|
Canonicalization relaxed/simple
|
||||||
MinimumKeyBits 1024
|
MinimumKeyBits 1024
|
||||||
ExternalIgnoreList refile:/etc/opendkim/TrustedHosts
|
ExternalIgnoreList refile:/etc/opendkim/TrustedHosts
|
||||||
InternalHosts refile:/etc/opendkim/TrustedHosts
|
InternalHosts refile:/etc/opendkim/TrustedHosts
|
||||||
@@ -61,7 +62,40 @@ chmod go-rwx $STORAGE_ROOT/mail/dkim
|
|||||||
|
|
||||||
tools/editconf.py /etc/opendmarc.conf -s \
|
tools/editconf.py /etc/opendmarc.conf -s \
|
||||||
"Syslog=true" \
|
"Syslog=true" \
|
||||||
"Socket=inet:8893@[127.0.0.1]"
|
"Socket=inet:8893@[127.0.0.1]" \
|
||||||
|
"FailureReports=true"
|
||||||
|
|
||||||
|
# SPFIgnoreResults causes the filter to ignore any SPF results in the header
|
||||||
|
# of the message. This is useful if you want the filter to perfrom SPF checks
|
||||||
|
# itself, or because you don't trust the arriving header. This added header is
|
||||||
|
# used by spamassassin to evaluate the mail for spamminess.
|
||||||
|
|
||||||
|
tools/editconf.py /etc/opendmarc.conf -s \
|
||||||
|
"SPFIgnoreResults=true"
|
||||||
|
|
||||||
|
# SPFSelfValidate causes the filter to perform a fallback SPF check itself
|
||||||
|
# when it can find no SPF results in the message header. If SPFIgnoreResults
|
||||||
|
# is also set, it never looks for SPF results in headers and always performs
|
||||||
|
# the SPF check itself when this is set. This added header is used by
|
||||||
|
# spamassassin to evaluate the mail for spamminess.
|
||||||
|
|
||||||
|
tools/editconf.py /etc/opendmarc.conf -s \
|
||||||
|
"SPFSelfValidate=true"
|
||||||
|
|
||||||
|
# Enables generation of failure reports for sending domains that publish a
|
||||||
|
# "none" policy.
|
||||||
|
|
||||||
|
tools/editconf.py /etc/opendmarc.conf -s \
|
||||||
|
"FailureReportsOnNone=true"
|
||||||
|
|
||||||
|
# AlwaysAddARHeader Adds an "Authentication-Results:" header field even to
|
||||||
|
# unsigned messages from domains with no "signs all" policy. The reported DKIM
|
||||||
|
# result will be "none" in such cases. Normally unsigned mail from non-strict
|
||||||
|
# domains does not cause the results header field to be added. This added header
|
||||||
|
# is used by spamassassin to evaluate the mail for spamminess.
|
||||||
|
|
||||||
|
tools/editconf.py /etc/opendkim.conf -s \
|
||||||
|
"AlwaysAddARHeader=true"
|
||||||
|
|
||||||
# Add OpenDKIM and OpenDMARC as milters to postfix, which is how OpenDKIM
|
# Add OpenDKIM and OpenDMARC as milters to postfix, which is how OpenDKIM
|
||||||
# intercepts outgoing mail to perform the signing (by adding a mail header)
|
# intercepts outgoing mail to perform the signing (by adding a mail header)
|
||||||
|
|||||||
51
setup/dns.sh
51
setup/dns.sh
@@ -62,33 +62,27 @@ for ip in $PRIVATE_IP $PRIVATE_IPV6; do
|
|||||||
echo " ip-address: $ip" >> /etc/nsd/nsd.conf;
|
echo " ip-address: $ip" >> /etc/nsd/nsd.conf;
|
||||||
done
|
done
|
||||||
|
|
||||||
echo "include: /etc/nsd/zones.conf" >> /etc/nsd/nsd.conf;
|
# Create a directory for additional configuration directives, including
|
||||||
|
# the zones.conf file written out by our management daemon.
|
||||||
|
echo "include: /etc/nsd/nsd.conf.d/*.conf" >> /etc/nsd/nsd.conf;
|
||||||
|
|
||||||
|
# Remove the old location of zones.conf that we generate. It will
|
||||||
|
# now be stored in /etc/nsd/nsd.conf.d.
|
||||||
|
rm -f /etc/nsd/zones.conf
|
||||||
|
|
||||||
# Create DNSSEC signing keys.
|
# Create DNSSEC signing keys.
|
||||||
|
|
||||||
mkdir -p "$STORAGE_ROOT/dns/dnssec";
|
mkdir -p "$STORAGE_ROOT/dns/dnssec";
|
||||||
|
|
||||||
# TLDs don't all support the same algorithms, so we'll generate keys using a few
|
# TLDs, registrars, and validating nameservers don't all support the same algorithms,
|
||||||
# different algorithms. RSASHA1-NSEC3-SHA1 was possibly the first widely used
|
# so we'll generate keys using a few different algorithms so that dns_update.py can
|
||||||
# algorithm that supported NSEC3, which is a security best practice. However TLDs
|
# choose which algorithm to use when generating the zonefiles. See #1953 for recent
|
||||||
# will probably be moving away from it to a a SHA256-based algorithm.
|
# discussion. File for previously used algorithms (i.e. RSASHA1-NSEC3-SHA1) may still
|
||||||
#
|
# be in the output directory, and we'll continue to support signing zones with them
|
||||||
# Supports `RSASHA1-NSEC3-SHA1` (didn't test with `RSASHA256`):
|
# so that trust isn't broken with deployed DS records, but we won't generate those
|
||||||
#
|
# keys on new systems.
|
||||||
# * .info
|
|
||||||
# * .me
|
|
||||||
#
|
|
||||||
# Requires `RSASHA256`
|
|
||||||
#
|
|
||||||
# * .email
|
|
||||||
# * .guide
|
|
||||||
#
|
|
||||||
# Supports `RSASHA256` (and defaulting to this)
|
|
||||||
#
|
|
||||||
# * .fund
|
|
||||||
|
|
||||||
FIRST=1 #NODOC
|
FIRST=1 #NODOC
|
||||||
for algo in RSASHA1-NSEC3-SHA1 RSASHA256; do
|
for algo in RSASHA256 ECDSAP256SHA256; do
|
||||||
if [ ! -f "$STORAGE_ROOT/dns/dnssec/$algo.conf" ]; then
|
if [ ! -f "$STORAGE_ROOT/dns/dnssec/$algo.conf" ]; then
|
||||||
if [ $FIRST == 1 ]; then
|
if [ $FIRST == 1 ]; then
|
||||||
echo "Generating DNSSEC signing keys..."
|
echo "Generating DNSSEC signing keys..."
|
||||||
@@ -105,17 +99,22 @@ if [ ! -f "$STORAGE_ROOT/dns/dnssec/$algo.conf" ]; then
|
|||||||
# ldns-keygen uses /dev/random for generating random numbers by default.
|
# ldns-keygen uses /dev/random for generating random numbers by default.
|
||||||
# This is slow and unecessary if we ensure /dev/urandom is seeded properly,
|
# This is slow and unecessary if we ensure /dev/urandom is seeded properly,
|
||||||
# so we use /dev/urandom. See system.sh for an explanation. See #596, #115.
|
# so we use /dev/urandom. See system.sh for an explanation. See #596, #115.
|
||||||
KSK=$(umask 077; cd $STORAGE_ROOT/dns/dnssec; ldns-keygen -r /dev/urandom -a $algo -b 2048 -k _domain_);
|
# (This previously used -b 2048 but it's unclear if this setting makes sense
|
||||||
|
# for non-RSA keys, so it's removed. The RSA-based keys are not recommended
|
||||||
|
# anymore anyway.)
|
||||||
|
KSK=$(umask 077; cd $STORAGE_ROOT/dns/dnssec; ldns-keygen -r /dev/urandom -a $algo -k _domain_);
|
||||||
|
|
||||||
# Now create a Zone-Signing Key (ZSK) which is expected to be
|
# Now create a Zone-Signing Key (ZSK) which is expected to be
|
||||||
# rotated more often than a KSK, although we have no plans to
|
# rotated more often than a KSK, although we have no plans to
|
||||||
# rotate it (and doing so would be difficult to do without
|
# rotate it (and doing so would be difficult to do without
|
||||||
# disturbing DNS availability.) Omit `-k` and use a shorter key length.
|
# disturbing DNS availability.) Omit `-k`.
|
||||||
ZSK=$(umask 077; cd $STORAGE_ROOT/dns/dnssec; ldns-keygen -r /dev/urandom -a $algo -b 1024 _domain_);
|
# (This previously used -b 1024 but it's unclear if this setting makes sense
|
||||||
|
# for non-RSA keys, so it's removed.)
|
||||||
|
ZSK=$(umask 077; cd $STORAGE_ROOT/dns/dnssec; ldns-keygen -r /dev/urandom -a $algo _domain_);
|
||||||
|
|
||||||
# These generate two sets of files like:
|
# These generate two sets of files like:
|
||||||
#
|
#
|
||||||
# * `K_domain_.+007+08882.ds`: DS record normally provided to domain name registrar (but it's actually invalid with `_domain_`)
|
# * `K_domain_.+007+08882.ds`: DS record normally provided to domain name registrar (but it's actually invalid with `_domain_` so we don't use this file)
|
||||||
# * `K_domain_.+007+08882.key`: public key
|
# * `K_domain_.+007+08882.key`: public key
|
||||||
# * `K_domain_.+007+08882.private`: private key (secret!)
|
# * `K_domain_.+007+08882.private`: private key (secret!)
|
||||||
|
|
||||||
@@ -139,7 +138,7 @@ cat > /etc/cron.daily/mailinabox-dnssec << EOF;
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# Mail-in-a-Box
|
# Mail-in-a-Box
|
||||||
# Re-sign any DNS zones with DNSSEC because the signatures expire periodically.
|
# Re-sign any DNS zones with DNSSEC because the signatures expire periodically.
|
||||||
`pwd`/tools/dns_update
|
$(pwd)/tools/dns_update
|
||||||
EOF
|
EOF
|
||||||
chmod +x /etc/cron.daily/mailinabox-dnssec
|
chmod +x /etc/cron.daily/mailinabox-dnssec
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# If there aren't any mail users yet, create one.
|
# If there aren't any mail users yet, create one.
|
||||||
if [ -z "`tools/mail.py user`" ]; then
|
if [ -z "$(management/cli.py user)" ]; then
|
||||||
# The outut of "tools/mail.py user" is a list of mail users. If there
|
# The outut of "management/cli.py user" is a list of mail users. If there
|
||||||
# aren't any yet, it'll be empty.
|
# aren't any yet, it'll be empty.
|
||||||
|
|
||||||
# If we didn't ask for an email address at the start, do so now.
|
# If we didn't ask for an email address at the start, do so now.
|
||||||
@@ -10,7 +10,7 @@ if [ -z "`tools/mail.py user`" ]; then
|
|||||||
input_box "Mail Account" \
|
input_box "Mail Account" \
|
||||||
"Let's create your first mail account.
|
"Let's create your first mail account.
|
||||||
\n\nWhat email address do you want?" \
|
\n\nWhat email address do you want?" \
|
||||||
me@`get_default_hostname` \
|
me@$(get_default_hostname) \
|
||||||
EMAIL_ADDR
|
EMAIL_ADDR
|
||||||
|
|
||||||
if [ -z "$EMAIL_ADDR" ]; then
|
if [ -z "$EMAIL_ADDR" ]; then
|
||||||
@@ -47,11 +47,11 @@ if [ -z "`tools/mail.py user`" ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Create the user's mail account. This will ask for a password if none was given above.
|
# Create the user's mail account. This will ask for a password if none was given above.
|
||||||
tools/mail.py user add $EMAIL_ADDR ${EMAIL_PW:-}
|
management/cli.py user add $EMAIL_ADDR ${EMAIL_PW:-}
|
||||||
|
|
||||||
# Make it an admin.
|
# Make it an admin.
|
||||||
hide_output tools/mail.py user make-admin $EMAIL_ADDR
|
hide_output management/cli.py user make-admin $EMAIL_ADDR
|
||||||
|
|
||||||
# Create an alias to which we'll direct all automatically-created administrative aliases.
|
# Create an alias to which we'll direct all automatically-created administrative aliases.
|
||||||
tools/mail.py alias add administrator@$PRIMARY_HOSTNAME $EMAIL_ADDR > /dev/null
|
management/cli.py alias add administrator@$PRIMARY_HOSTNAME $EMAIL_ADDR > /dev/null
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -9,12 +9,12 @@ function hide_output {
|
|||||||
# and returns a non-zero exit code.
|
# and returns a non-zero exit code.
|
||||||
|
|
||||||
# Get a temporary file.
|
# Get a temporary file.
|
||||||
OUTPUT=$(tempfile)
|
OUTPUT=$(mktemp)
|
||||||
|
|
||||||
# Execute command, redirecting stderr/stdout to the temporary file. Since we
|
# Execute command, redirecting stderr/stdout to the temporary file. Since we
|
||||||
# check the return code ourselves, disable 'set -e' temporarily.
|
# check the return code ourselves, disable 'set -e' temporarily.
|
||||||
set +e
|
set +e
|
||||||
$@ &> $OUTPUT
|
"$@" &> $OUTPUT
|
||||||
E=$?
|
E=$?
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ function hide_output {
|
|||||||
if [ $E != 0 ]; then
|
if [ $E != 0 ]; then
|
||||||
# Something failed.
|
# Something failed.
|
||||||
echo
|
echo
|
||||||
echo FAILED: $@
|
echo FAILED: "$@"
|
||||||
echo -----------------------------------------
|
echo -----------------------------------------
|
||||||
cat $OUTPUT
|
cat $OUTPUT
|
||||||
echo -----------------------------------------
|
echo -----------------------------------------
|
||||||
@@ -53,17 +53,7 @@ function apt_install {
|
|||||||
# install' for all of the packages. Calling `dpkg` on each package is slow,
|
# install' for all of the packages. Calling `dpkg` on each package is slow,
|
||||||
# and doesn't affect what we actually do, except in the messages, so let's
|
# and doesn't affect what we actually do, except in the messages, so let's
|
||||||
# not do that anymore.
|
# not do that anymore.
|
||||||
PACKAGES=$@
|
apt_get_quiet install "$@"
|
||||||
apt_get_quiet install $PACKAGES
|
|
||||||
}
|
|
||||||
|
|
||||||
function apt_add_repository_to_unattended_upgrades {
|
|
||||||
if [ -f /etc/apt/apt.conf.d/50unattended-upgrades ]; then
|
|
||||||
if ! grep -q "$1" /etc/apt/apt.conf.d/50unattended-upgrades; then
|
|
||||||
sed -i "/Allowed-Origins/a \
|
|
||||||
\"$1\";" /etc/apt/apt.conf.d/50unattended-upgrades
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_default_hostname {
|
function get_default_hostname {
|
||||||
@@ -145,7 +135,14 @@ function get_default_privateip {
|
|||||||
function ufw_allow {
|
function ufw_allow {
|
||||||
if [ -z "${DISABLE_FIREWALL:-}" ]; then
|
if [ -z "${DISABLE_FIREWALL:-}" ]; then
|
||||||
# ufw has completely unhelpful output
|
# ufw has completely unhelpful output
|
||||||
ufw allow $1 > /dev/null;
|
ufw allow "$1" > /dev/null;
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
function ufw_limit {
|
||||||
|
if [ -z "${DISABLE_FIREWALL:-}" ]; then
|
||||||
|
# ufw has completely unhelpful output
|
||||||
|
ufw limit "$1" > /dev/null;
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -45,8 +45,8 @@ apt_install \
|
|||||||
# - https://www.dovecot.org/list/dovecot/2012-August/137569.html
|
# - https://www.dovecot.org/list/dovecot/2012-August/137569.html
|
||||||
# - https://www.dovecot.org/list/dovecot/2011-December/132455.html
|
# - https://www.dovecot.org/list/dovecot/2011-December/132455.html
|
||||||
tools/editconf.py /etc/dovecot/conf.d/10-master.conf \
|
tools/editconf.py /etc/dovecot/conf.d/10-master.conf \
|
||||||
default_process_limit=$(echo "`nproc` * 250" | bc) \
|
default_process_limit=$(echo "$(nproc) * 250" | bc) \
|
||||||
default_vsz_limit=$(echo "`free -tm | tail -1 | awk '{print $2}'` / 3" | bc)M \
|
default_vsz_limit=$(echo "$(free -tm | tail -1 | awk '{print $2}') / 3" | bc)M \
|
||||||
log_path=/var/log/mail.log
|
log_path=/var/log/mail.log
|
||||||
|
|
||||||
# The inotify `max_user_instances` default is 128, which constrains
|
# The inotify `max_user_instances` default is 128, which constrains
|
||||||
@@ -78,16 +78,15 @@ tools/editconf.py /etc/dovecot/conf.d/10-auth.conf \
|
|||||||
"auth_mechanisms=plain login"
|
"auth_mechanisms=plain login"
|
||||||
|
|
||||||
# Enable SSL, specify the location of the SSL certificate and private key files.
|
# Enable SSL, specify the location of the SSL certificate and private key files.
|
||||||
# Disable obsolete SSL protocols and allow only good ciphers per http://baldric.net/2013/12/07/tls-ciphers-in-postfix-and-dovecot/.
|
# Use Mozilla's "Intermediate" recommendations at https://ssl-config.mozilla.org/#server=dovecot&server-version=2.2.33&config=intermediate&openssl-version=1.1.1,
|
||||||
# Enable strong ssl dh parameters
|
# except that the current version of Dovecot does not have a TLSv1.3 setting, so we only use TLSv1.2.
|
||||||
|
|
||||||
tools/editconf.py /etc/dovecot/conf.d/10-ssl.conf \
|
tools/editconf.py /etc/dovecot/conf.d/10-ssl.conf \
|
||||||
ssl=required \
|
ssl=required \
|
||||||
"ssl_cert=<$STORAGE_ROOT/ssl/ssl_certificate.pem" \
|
"ssl_cert=<$STORAGE_ROOT/ssl/ssl_certificate.pem" \
|
||||||
"ssl_key=<$STORAGE_ROOT/ssl/ssl_private_key.pem" \
|
"ssl_key=<$STORAGE_ROOT/ssl/ssl_private_key.pem" \
|
||||||
"ssl_protocols=!SSLv3" \
|
"ssl_protocols=TLSv1.2" \
|
||||||
"ssl_cipher_list=ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS" \
|
"ssl_cipher_list=ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384" \
|
||||||
"ssl_prefer_server_ciphers = yes" \
|
"ssl_prefer_server_ciphers=no" \
|
||||||
"ssl_dh_parameters_length=2048"
|
"ssl_dh_parameters_length=2048"
|
||||||
|
|
||||||
# Disable in-the-clear IMAP/POP because there is no reason for a user to transmit
|
# Disable in-the-clear IMAP/POP because there is no reason for a user to transmit
|
||||||
@@ -145,7 +144,7 @@ service imap-login {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
protocol imap {
|
protocol imap {
|
||||||
mail_max_userip_connections = 20
|
mail_max_userip_connections = 40
|
||||||
}
|
}
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
@@ -184,6 +183,7 @@ plugin {
|
|||||||
sieve_after = $STORAGE_ROOT/mail/sieve/global_after
|
sieve_after = $STORAGE_ROOT/mail/sieve/global_after
|
||||||
sieve = $STORAGE_ROOT/mail/sieve/%d/%n.sieve
|
sieve = $STORAGE_ROOT/mail/sieve/%d/%n.sieve
|
||||||
sieve_dir = $STORAGE_ROOT/mail/sieve/%d/%n
|
sieve_dir = $STORAGE_ROOT/mail/sieve/%d/%n
|
||||||
|
sieve_redirect_envelope_from = recipient
|
||||||
}
|
}
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
# LMTP. Spamassassin then passes mail over to Dovecot for
|
# LMTP. Spamassassin then passes mail over to Dovecot for
|
||||||
# storage in the user's mailbox.
|
# storage in the user's mailbox.
|
||||||
#
|
#
|
||||||
# Postfix also listens on port 587 (SMTP+STARTLS) for
|
# Postfix also listens on ports 465/587 (SMTPS, SMTP+STARTLS) for
|
||||||
# connections from users who can authenticate and then sends
|
# connections from users who can authenticate and then sends
|
||||||
# their email out to the outside world. Postfix queries Dovecot
|
# their email out to the outside world. Postfix queries Dovecot
|
||||||
# to authenticate users.
|
# to authenticate users.
|
||||||
@@ -71,7 +71,7 @@ tools/editconf.py /etc/postfix/main.cf \
|
|||||||
|
|
||||||
# ### Outgoing Mail
|
# ### Outgoing Mail
|
||||||
|
|
||||||
# Enable the 'submission' port 587 smtpd server and tweak its settings.
|
# Enable the 'submission' ports 465 and 587 and tweak their settings.
|
||||||
#
|
#
|
||||||
# * Enable authentication. It's disabled globally so that it is disabled on port 25,
|
# * Enable authentication. It's disabled globally so that it is disabled on port 25,
|
||||||
# so we need to explicitly enable it here.
|
# so we need to explicitly enable it here.
|
||||||
@@ -80,20 +80,24 @@ tools/editconf.py /etc/postfix/main.cf \
|
|||||||
# OpenDKIM milter only. See dkim.sh.
|
# OpenDKIM milter only. See dkim.sh.
|
||||||
# * Even though we dont allow auth over non-TLS connections (smtpd_tls_auth_only below, and without auth the client cant
|
# * Even though we dont allow auth over non-TLS connections (smtpd_tls_auth_only below, and without auth the client cant
|
||||||
# send outbound mail), don't allow non-TLS mail submission on this port anyway to prevent accidental misconfiguration.
|
# send outbound mail), don't allow non-TLS mail submission on this port anyway to prevent accidental misconfiguration.
|
||||||
# * Require the best ciphers for incoming connections per http://baldric.net/2013/12/07/tls-ciphers-in-postfix-and-dovecot/.
|
# Setting smtpd_tls_security_level=encrypt also triggers the use of the 'mandatory' settings below (but this is ignored with smtpd_tls_wrappermode=yes.)
|
||||||
# By putting this setting here we leave opportunistic TLS on incoming mail at default cipher settings (any cipher is better than none).
|
|
||||||
# * Give it a different name in syslog to distinguish it from the port 25 smtpd server.
|
# * Give it a different name in syslog to distinguish it from the port 25 smtpd server.
|
||||||
# * Add a new cleanup service specific to the submission service ('authclean')
|
# * Add a new cleanup service specific to the submission service ('authclean')
|
||||||
# that filters out privacy-sensitive headers on mail being sent out by
|
# that filters out privacy-sensitive headers on mail being sent out by
|
||||||
# authenticated users. By default Postfix also applies this to attached
|
# authenticated users. By default Postfix also applies this to attached
|
||||||
# emails but we turn this off by setting nested_header_checks empty.
|
# emails but we turn this off by setting nested_header_checks empty.
|
||||||
tools/editconf.py /etc/postfix/master.cf -s -w \
|
tools/editconf.py /etc/postfix/master.cf -s -w \
|
||||||
|
"smtps=inet n - - - - smtpd
|
||||||
|
-o smtpd_tls_wrappermode=yes
|
||||||
|
-o smtpd_sasl_auth_enable=yes
|
||||||
|
-o syslog_name=postfix/submission
|
||||||
|
-o smtpd_milters=inet:127.0.0.1:8891
|
||||||
|
-o cleanup_service_name=authclean" \
|
||||||
"submission=inet n - - - - smtpd
|
"submission=inet n - - - - smtpd
|
||||||
-o smtpd_sasl_auth_enable=yes
|
-o smtpd_sasl_auth_enable=yes
|
||||||
-o syslog_name=postfix/submission
|
-o syslog_name=postfix/submission
|
||||||
-o smtpd_milters=inet:127.0.0.1:8891
|
-o smtpd_milters=inet:127.0.0.1:8891
|
||||||
-o smtpd_tls_security_level=encrypt
|
-o smtpd_tls_security_level=encrypt
|
||||||
-o smtpd_tls_ciphers=high -o smtpd_tls_exclude_ciphers=aNULL,DES,3DES,MD5,DES+MD5,RC4 -o smtpd_tls_mandatory_protocols=!SSLv2,!SSLv3
|
|
||||||
-o cleanup_service_name=authclean" \
|
-o cleanup_service_name=authclean" \
|
||||||
"authclean=unix n - - - 0 cleanup
|
"authclean=unix n - - - 0 cleanup
|
||||||
-o header_checks=pcre:/etc/postfix/outgoing_mail_header_filters
|
-o header_checks=pcre:/etc/postfix/outgoing_mail_header_filters
|
||||||
@@ -108,27 +112,44 @@ cp conf/postfix_outgoing_mail_header_filters /etc/postfix/outgoing_mail_header_f
|
|||||||
sed -i "s/PRIMARY_HOSTNAME/$PRIMARY_HOSTNAME/" /etc/postfix/outgoing_mail_header_filters
|
sed -i "s/PRIMARY_HOSTNAME/$PRIMARY_HOSTNAME/" /etc/postfix/outgoing_mail_header_filters
|
||||||
sed -i "s/PUBLIC_IP/$PUBLIC_IP/" /etc/postfix/outgoing_mail_header_filters
|
sed -i "s/PUBLIC_IP/$PUBLIC_IP/" /etc/postfix/outgoing_mail_header_filters
|
||||||
|
|
||||||
# Enable TLS on these and all other connections (i.e. ports 25 *and* 587) and
|
# Enable TLS on incoming connections. It is not required on port 25, allowing for opportunistic
|
||||||
# require TLS before a user is allowed to authenticate. This also makes
|
# encryption. On ports 465 and 587 it is mandatory (see above). Shared and non-shared settings are
|
||||||
# opportunistic TLS available on *incoming* mail.
|
# given here. Shared settings include:
|
||||||
# Set stronger DH parameters, which via openssl tend to default to 1024 bits
|
# * Require TLS before a user is allowed to authenticate.
|
||||||
# (see ssl.sh).
|
# * Set the path to the server TLS certificate and 2048-bit DH parameters for old DH ciphers.
|
||||||
|
# For port 25 only:
|
||||||
|
# * Disable extremely old versions of TLS and extremely unsafe ciphers, but some mail servers out in
|
||||||
|
# the world are very far behind and if we disable too much, they may not be able to use TLS and
|
||||||
|
# won't fall back to cleartext. So we don't disable too much. smtpd_tls_exclude_ciphers applies to
|
||||||
|
# both port 25 and port 587, but because we override the cipher list for both, it probably isn't used.
|
||||||
|
# Use Mozilla's "Old" recommendations at https://ssl-config.mozilla.org/#server=postfix&server-version=3.3.0&config=old&openssl-version=1.1.1
|
||||||
tools/editconf.py /etc/postfix/main.cf \
|
tools/editconf.py /etc/postfix/main.cf \
|
||||||
smtpd_tls_security_level=may\
|
smtpd_tls_security_level=may\
|
||||||
smtpd_tls_auth_only=yes \
|
smtpd_tls_auth_only=yes \
|
||||||
smtpd_tls_cert_file=$STORAGE_ROOT/ssl/ssl_certificate.pem \
|
smtpd_tls_cert_file=$STORAGE_ROOT/ssl/ssl_certificate.pem \
|
||||||
smtpd_tls_key_file=$STORAGE_ROOT/ssl/ssl_private_key.pem \
|
smtpd_tls_key_file=$STORAGE_ROOT/ssl/ssl_private_key.pem \
|
||||||
smtpd_tls_dh1024_param_file=$STORAGE_ROOT/ssl/dh2048.pem \
|
smtpd_tls_dh1024_param_file=$STORAGE_ROOT/ssl/dh2048.pem \
|
||||||
smtpd_tls_protocols=\!SSLv2,\!SSLv3 \
|
smtpd_tls_protocols="!SSLv2,!SSLv3" \
|
||||||
smtpd_tls_ciphers=medium \
|
smtpd_tls_ciphers=medium \
|
||||||
|
tls_medium_cipherlist=ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA \
|
||||||
smtpd_tls_exclude_ciphers=aNULL,RC4 \
|
smtpd_tls_exclude_ciphers=aNULL,RC4 \
|
||||||
|
tls_preempt_cipherlist=no \
|
||||||
smtpd_tls_received_header=yes
|
smtpd_tls_received_header=yes
|
||||||
|
|
||||||
|
# For ports 465/587 (via the 'mandatory' settings):
|
||||||
|
# * Use Mozilla's "Intermediate" TLS recommendations from https://ssl-config.mozilla.org/#server=postfix&server-version=3.3.0&config=intermediate&openssl-version=1.1.1
|
||||||
|
# using and overriding the "high" cipher list so we don't conflict with the more permissive settings for port 25.
|
||||||
|
tools/editconf.py /etc/postfix/main.cf \
|
||||||
|
smtpd_tls_mandatory_protocols="!SSLv2,!SSLv3,!TLSv1,!TLSv1.1" \
|
||||||
|
smtpd_tls_mandatory_ciphers=high \
|
||||||
|
tls_high_cipherlist=ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384 \
|
||||||
|
smtpd_tls_mandatory_exclude_ciphers=aNULL,DES,3DES,MD5,DES+MD5,RC4
|
||||||
|
|
||||||
# Prevent non-authenticated users from sending mail that requires being
|
# Prevent non-authenticated users from sending mail that requires being
|
||||||
# relayed elsewhere. We don't want to be an "open relay". On outbound
|
# relayed elsewhere. We don't want to be an "open relay". On outbound
|
||||||
# mail, require one of:
|
# mail, require one of:
|
||||||
#
|
#
|
||||||
# * `permit_sasl_authenticated`: Authenticated users (i.e. on port 587).
|
# * `permit_sasl_authenticated`: Authenticated users (i.e. on port 465/587).
|
||||||
# * `permit_mynetworks`: Mail that originates locally.
|
# * `permit_mynetworks`: Mail that originates locally.
|
||||||
# * `reject_unauth_destination`: No one else. (Permits mail whose destination is local and rejects other mail.)
|
# * `reject_unauth_destination`: No one else. (Permits mail whose destination is local and rejects other mail.)
|
||||||
tools/editconf.py /etc/postfix/main.cf \
|
tools/editconf.py /etc/postfix/main.cf \
|
||||||
@@ -143,8 +164,12 @@ tools/editconf.py /etc/postfix/main.cf \
|
|||||||
# offers it, otherwise it will transmit the message in the clear. Postfix will
|
# offers it, otherwise it will transmit the message in the clear. Postfix will
|
||||||
# accept whatever SSL certificate the remote end provides. Opportunistic TLS
|
# accept whatever SSL certificate the remote end provides. Opportunistic TLS
|
||||||
# protects against passive easvesdropping (but not man-in-the-middle attacks).
|
# protects against passive easvesdropping (but not man-in-the-middle attacks).
|
||||||
|
# Since we'd rather have poor encryption than none at all, we use Mozilla's
|
||||||
|
# "Old" recommendations at https://ssl-config.mozilla.org/#server=postfix&server-version=3.3.0&config=old&openssl-version=1.1.1
|
||||||
|
# for opportunistic encryption but "Intermediate" recommendations when DANE
|
||||||
|
# is used (see next and above). The cipher lists are set above.
|
||||||
|
|
||||||
# DANE takes this a step further:
|
# DANE takes this a step further:
|
||||||
#
|
|
||||||
# Postfix queries DNS for the TLSA record on the destination MX host. If no TLSA records are found,
|
# Postfix queries DNS for the TLSA record on the destination MX host. If no TLSA records are found,
|
||||||
# then opportunistic TLS is used. Otherwise the server certificate must match the TLSA records
|
# then opportunistic TLS is used. Otherwise the server certificate must match the TLSA records
|
||||||
# or else the mail bounces. TLSA also requires DNSSEC on the MX host. Postfix doesn't do DNSSEC
|
# or else the mail bounces. TLSA also requires DNSSEC on the MX host. Postfix doesn't do DNSSEC
|
||||||
@@ -157,11 +182,12 @@ tools/editconf.py /etc/postfix/main.cf \
|
|||||||
# now see notices about trusted certs. The CA file is provided by the package `ca-certificates`.
|
# now see notices about trusted certs. The CA file is provided by the package `ca-certificates`.
|
||||||
tools/editconf.py /etc/postfix/main.cf \
|
tools/editconf.py /etc/postfix/main.cf \
|
||||||
smtp_tls_protocols=\!SSLv2,\!SSLv3 \
|
smtp_tls_protocols=\!SSLv2,\!SSLv3 \
|
||||||
smtp_tls_mandatory_protocols=\!SSLv2,\!SSLv3 \
|
|
||||||
smtp_tls_ciphers=medium \
|
smtp_tls_ciphers=medium \
|
||||||
smtp_tls_exclude_ciphers=aNULL,RC4 \
|
smtp_tls_exclude_ciphers=aNULL,RC4 \
|
||||||
smtp_tls_security_level=dane \
|
smtp_tls_security_level=dane \
|
||||||
smtp_dns_support_level=dnssec \
|
smtp_dns_support_level=dnssec \
|
||||||
|
smtp_tls_mandatory_protocols="!SSLv2,!SSLv3,!TLSv1,!TLSv1.1" \
|
||||||
|
smtp_tls_mandatory_ciphers=high \
|
||||||
smtp_tls_CAfile=/etc/ssl/certs/ca-certificates.crt \
|
smtp_tls_CAfile=/etc/ssl/certs/ca-certificates.crt \
|
||||||
smtp_tls_loglevel=2
|
smtp_tls_loglevel=2
|
||||||
|
|
||||||
@@ -173,7 +199,7 @@ tools/editconf.py /etc/postfix/main.cf \
|
|||||||
#
|
#
|
||||||
# In a basic setup we would pass mail directly to Dovecot by setting
|
# In a basic setup we would pass mail directly to Dovecot by setting
|
||||||
# virtual_transport to `lmtp:unix:private/dovecot-lmtp`.
|
# virtual_transport to `lmtp:unix:private/dovecot-lmtp`.
|
||||||
tools/editconf.py /etc/postfix/main.cf virtual_transport=lmtp:[127.0.0.1]:10025
|
tools/editconf.py /etc/postfix/main.cf "virtual_transport=lmtp:[127.0.0.1]:10025"
|
||||||
# Because of a spampd bug, limit the number of recipients in each connection.
|
# Because of a spampd bug, limit the number of recipients in each connection.
|
||||||
# See https://github.com/mail-in-a-box/mailinabox/issues/1523.
|
# See https://github.com/mail-in-a-box/mailinabox/issues/1523.
|
||||||
tools/editconf.py /etc/postfix/main.cf lmtp_destination_recipient_limit=1
|
tools/editconf.py /etc/postfix/main.cf lmtp_destination_recipient_limit=1
|
||||||
@@ -210,6 +236,33 @@ tools/editconf.py /etc/postfix/main.cf \
|
|||||||
tools/editconf.py /etc/default/postgrey \
|
tools/editconf.py /etc/default/postgrey \
|
||||||
POSTGREY_OPTS=\"'--inet=127.0.0.1:10023 --delay=180'\"
|
POSTGREY_OPTS=\"'--inet=127.0.0.1:10023 --delay=180'\"
|
||||||
|
|
||||||
|
|
||||||
|
# We are going to setup a newer whitelist for postgrey, the version included in the distribution is old
|
||||||
|
cat > /etc/cron.daily/mailinabox-postgrey-whitelist << EOF;
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Mail-in-a-Box
|
||||||
|
|
||||||
|
# check we have a postgrey_whitelist_clients file and that it is not older than 28 days
|
||||||
|
if [ ! -f /etc/postgrey/whitelist_clients ] || find /etc/postgrey/whitelist_clients -mtime +28 | grep -q '.' ; then
|
||||||
|
# ok we need to update the file, so lets try to fetch it
|
||||||
|
if curl https://postgrey.schweikert.ch/pub/postgrey_whitelist_clients --output /tmp/postgrey_whitelist_clients -sS --fail > /dev/null 2>&1 ; then
|
||||||
|
# if fetching hasn't failed yet then check it is a plain text file
|
||||||
|
# curl manual states that --fail sometimes still produces output
|
||||||
|
# this final check will at least check the output is not html
|
||||||
|
# before moving it into place
|
||||||
|
if [ "\$(file -b --mime-type /tmp/postgrey_whitelist_clients)" == "text/plain" ]; then
|
||||||
|
mv /tmp/postgrey_whitelist_clients /etc/postgrey/whitelist_clients
|
||||||
|
service postgrey restart
|
||||||
|
else
|
||||||
|
rm /tmp/postgrey_whitelist_clients
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
EOF
|
||||||
|
chmod +x /etc/cron.daily/mailinabox-postgrey-whitelist
|
||||||
|
/etc/cron.daily/mailinabox-postgrey-whitelist
|
||||||
|
|
||||||
# Increase the message size limit from 10MB to 128MB.
|
# Increase the message size limit from 10MB to 128MB.
|
||||||
# The same limit is specified in nginx.conf for mail submitted via webmail and Z-Push.
|
# The same limit is specified in nginx.conf for mail submitted via webmail and Z-Push.
|
||||||
tools/editconf.py /etc/postfix/main.cf \
|
tools/editconf.py /etc/postfix/main.cf \
|
||||||
@@ -218,6 +271,7 @@ tools/editconf.py /etc/postfix/main.cf \
|
|||||||
# Allow the two SMTP ports in the firewall.
|
# Allow the two SMTP ports in the firewall.
|
||||||
|
|
||||||
ufw_allow smtp
|
ufw_allow smtp
|
||||||
|
ufw_allow smtps
|
||||||
ufw_allow submission
|
ufw_allow submission
|
||||||
|
|
||||||
# Restart services
|
# Restart services
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ if [ ! -f $db_path ]; then
|
|||||||
echo Creating new user database: $db_path;
|
echo Creating new user database: $db_path;
|
||||||
echo "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL UNIQUE, password TEXT NOT NULL, extra, privileges TEXT NOT NULL DEFAULT '');" | sqlite3 $db_path;
|
echo "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL UNIQUE, password TEXT NOT NULL, extra, privileges TEXT NOT NULL DEFAULT '');" | sqlite3 $db_path;
|
||||||
echo "CREATE TABLE aliases (id INTEGER PRIMARY KEY AUTOINCREMENT, source TEXT NOT NULL UNIQUE, destination TEXT NOT NULL, permitted_senders TEXT);" | sqlite3 $db_path;
|
echo "CREATE TABLE aliases (id INTEGER PRIMARY KEY AUTOINCREMENT, source TEXT NOT NULL UNIQUE, destination TEXT NOT NULL, permitted_senders TEXT);" | sqlite3 $db_path;
|
||||||
|
echo "CREATE TABLE mfa (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, type TEXT NOT NULL, secret TEXT NOT NULL, mru_token TEXT, label TEXT, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE);" | sqlite3 $db_path;
|
||||||
|
echo "CREATE TABLE auto_aliases (id INTEGER PRIMARY KEY AUTOINCREMENT, source TEXT NOT NULL UNIQUE, destination TEXT NOT NULL, permitted_senders TEXT);" | sqlite3 $db_path;
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ### User Authentication
|
# ### User Authentication
|
||||||
@@ -99,8 +101,12 @@ EOF
|
|||||||
# ### Destination Validation
|
# ### Destination Validation
|
||||||
|
|
||||||
# Use a Sqlite3 database to check whether a destination email address exists,
|
# Use a Sqlite3 database to check whether a destination email address exists,
|
||||||
# and to perform any email alias rewrites in Postfix.
|
# and to perform any email alias rewrites in Postfix. Additionally, we disable
|
||||||
|
# SMTPUTF8 because Dovecot's LMTP server that delivers mail to inboxes does
|
||||||
|
# not support it, and if a message is received with the SMTPUTF8 flag it will
|
||||||
|
# bounce.
|
||||||
tools/editconf.py /etc/postfix/main.cf \
|
tools/editconf.py /etc/postfix/main.cf \
|
||||||
|
smtputf8_enable=no \
|
||||||
virtual_mailbox_domains=sqlite:/etc/postfix/virtual-mailbox-domains.cf \
|
virtual_mailbox_domains=sqlite:/etc/postfix/virtual-mailbox-domains.cf \
|
||||||
virtual_mailbox_maps=sqlite:/etc/postfix/virtual-mailbox-maps.cf \
|
virtual_mailbox_maps=sqlite:/etc/postfix/virtual-mailbox-maps.cf \
|
||||||
virtual_alias_maps=sqlite:/etc/postfix/virtual-alias-maps.cf \
|
virtual_alias_maps=sqlite:/etc/postfix/virtual-alias-maps.cf \
|
||||||
@@ -109,7 +115,7 @@ tools/editconf.py /etc/postfix/main.cf \
|
|||||||
# SQL statement to check if we handle incoming mail for a domain, either for users or aliases.
|
# SQL statement to check if we handle incoming mail for a domain, either for users or aliases.
|
||||||
cat > /etc/postfix/virtual-mailbox-domains.cf << EOF;
|
cat > /etc/postfix/virtual-mailbox-domains.cf << EOF;
|
||||||
dbpath=$db_path
|
dbpath=$db_path
|
||||||
query = SELECT 1 FROM users WHERE email LIKE '%%@%s' UNION SELECT 1 FROM aliases WHERE source LIKE '%%@%s'
|
query = SELECT 1 FROM users WHERE email LIKE '%%@%s' UNION SELECT 1 FROM aliases WHERE source LIKE '%%@%s' UNION SELECT 1 FROM auto_aliases WHERE source LIKE '%%@%s'
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
# SQL statement to check if we handle incoming mail for a user.
|
# SQL statement to check if we handle incoming mail for a user.
|
||||||
@@ -144,7 +150,7 @@ EOF
|
|||||||
# empty destination here so that other lower priority rules might match.
|
# empty destination here so that other lower priority rules might match.
|
||||||
cat > /etc/postfix/virtual-alias-maps.cf << EOF;
|
cat > /etc/postfix/virtual-alias-maps.cf << EOF;
|
||||||
dbpath=$db_path
|
dbpath=$db_path
|
||||||
query = SELECT destination from (SELECT destination, 0 as priority FROM aliases WHERE source='%s' AND destination<>'' UNION SELECT email as destination, 1 as priority FROM users WHERE email='%s') ORDER BY priority LIMIT 1;
|
query = SELECT destination from (SELECT destination, 0 as priority FROM aliases WHERE source='%s' AND destination<>'' UNION SELECT email as destination, 1 as priority FROM users WHERE email='%s' UNION SELECT destination, 2 as priority FROM auto_aliases WHERE source='%s' AND destination<>'') ORDER BY priority LIMIT 1;
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
# Restart Services
|
# Restart Services
|
||||||
|
|||||||
@@ -18,19 +18,19 @@ while [ -d /usr/local/lib/python3.4/dist-packages/acme ]; do
|
|||||||
pip3 uninstall -y acme;
|
pip3 uninstall -y acme;
|
||||||
done
|
done
|
||||||
|
|
||||||
# duplicity is used to make backups of user data. It uses boto
|
# duplicity is used to make backups of user data.
|
||||||
# (via Python 2) to do backups to AWS S3. boto from the Ubuntu
|
|
||||||
# package manager is too out-of-date -- it doesn't support the newer
|
|
||||||
# S3 api used in some regions, which breaks backups to those regions.
|
|
||||||
# See #627, #653.
|
|
||||||
#
|
#
|
||||||
# virtualenv is used to isolate the Python 3 packages we
|
# virtualenv is used to isolate the Python 3 packages we
|
||||||
# install via pip from the system-installed packages.
|
# install via pip from the system-installed packages.
|
||||||
#
|
#
|
||||||
# certbot installs EFF's certbot which we use to
|
# certbot installs EFF's certbot which we use to
|
||||||
# provision free TLS certificates.
|
# provision free TLS certificates.
|
||||||
apt_install duplicity python-pip virtualenv certbot
|
apt_install duplicity python-pip virtualenv certbot rsync
|
||||||
hide_output pip2 install --upgrade boto
|
|
||||||
|
# b2sdk is used for backblaze backups.
|
||||||
|
# boto is used for amazon aws backups.
|
||||||
|
# Both are installed outside the pipenv, so they can be used by duplicity
|
||||||
|
hide_output pip3 install --upgrade b2sdk==1.14.1 boto
|
||||||
|
|
||||||
# Create a virtualenv for the installation of Python 3 packages
|
# Create a virtualenv for the installation of Python 3 packages
|
||||||
# used by the management daemon.
|
# used by the management daemon.
|
||||||
@@ -49,8 +49,9 @@ hide_output $venv/bin/pip install --upgrade pip
|
|||||||
# NOTE: email_validator is repeated in setup/questions.sh, so please keep the versions synced.
|
# NOTE: email_validator is repeated in setup/questions.sh, so please keep the versions synced.
|
||||||
hide_output $venv/bin/pip install --upgrade \
|
hide_output $venv/bin/pip install --upgrade \
|
||||||
rtyaml "email_validator>=1.0.0" "exclusiveprocess" \
|
rtyaml "email_validator>=1.0.0" "exclusiveprocess" \
|
||||||
flask dnspython python-dateutil \
|
flask dnspython python-dateutil expiringdict \
|
||||||
"idna>=2.0.0" "cryptography==2.2.2" boto psutil
|
qrcode[pil] pyotp \
|
||||||
|
"idna>=2.0.0" "cryptography==2.2.2" boto psutil postfix-mta-sts-resolver b2sdk
|
||||||
|
|
||||||
# CONFIGURATION
|
# CONFIGURATION
|
||||||
|
|
||||||
@@ -89,21 +90,29 @@ rm -f /tmp/bootstrap.zip
|
|||||||
# running after a reboot.
|
# running after a reboot.
|
||||||
cat > $inst_dir/start <<EOF;
|
cat > $inst_dir/start <<EOF;
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
# Set character encoding flags to ensure that any non-ASCII don't cause problems.
|
||||||
|
export LANGUAGE=en_US.UTF-8
|
||||||
|
export LC_ALL=en_US.UTF-8
|
||||||
|
export LANG=en_US.UTF-8
|
||||||
|
export LC_TYPE=en_US.UTF-8
|
||||||
|
|
||||||
source $venv/bin/activate
|
source $venv/bin/activate
|
||||||
exec python `pwd`/management/daemon.py
|
exec python $(pwd)/management/daemon.py
|
||||||
EOF
|
EOF
|
||||||
chmod +x $inst_dir/start
|
chmod +x $inst_dir/start
|
||||||
hide_output systemctl link -f conf/mailinabox.service
|
cp --remove-destination conf/mailinabox.service /lib/systemd/system/mailinabox.service # target was previously a symlink so remove it first
|
||||||
|
hide_output systemctl link -f /lib/systemd/system/mailinabox.service
|
||||||
hide_output systemctl daemon-reload
|
hide_output systemctl daemon-reload
|
||||||
hide_output systemctl enable mailinabox.service
|
hide_output systemctl enable mailinabox.service
|
||||||
|
|
||||||
# Perform nightly tasks at 3am in system time: take a backup, run
|
# Perform nightly tasks at 3am in system time: take a backup, run
|
||||||
# status checks and email the administrator any changes.
|
# status checks and email the administrator any changes.
|
||||||
|
|
||||||
|
minute=$((RANDOM % 60)) # avoid overloading mailinabox.email
|
||||||
cat > /etc/cron.d/mailinabox-nightly << EOF;
|
cat > /etc/cron.d/mailinabox-nightly << EOF;
|
||||||
# Mail-in-a-Box --- Do not edit / will be overwritten on update.
|
# Mail-in-a-Box --- Do not edit / will be overwritten on update.
|
||||||
# Run nightly tasks: backup, status checks.
|
# Run nightly tasks: backup, status checks.
|
||||||
0 3 * * * root (cd `pwd` && management/daily_tasks.sh)
|
$minute 3 * * * root (cd $(pwd) && management/daily_tasks.sh)
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
# Start the management server.
|
# Start the management server.
|
||||||
|
|||||||
@@ -181,6 +181,17 @@ def migration_12(env):
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
def migration_13(env):
|
||||||
|
# Add the "mfa" table for configuring MFA for login to the control panel.
|
||||||
|
db = os.path.join(env["STORAGE_ROOT"], 'mail/users.sqlite')
|
||||||
|
shell("check_call", ["sqlite3", db, "CREATE TABLE mfa (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, type TEXT NOT NULL, secret TEXT NOT NULL, mru_token TEXT, label TEXT, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE);"])
|
||||||
|
|
||||||
|
def migration_14(env):
|
||||||
|
# Add the "auto_aliases" table.
|
||||||
|
db = os.path.join(env["STORAGE_ROOT"], 'mail/users.sqlite')
|
||||||
|
shell("check_call", ["sqlite3", db, "CREATE TABLE auto_aliases (id INTEGER PRIMARY KEY AUTOINCREMENT, source TEXT NOT NULL UNIQUE, destination TEXT NOT NULL, permitted_senders TEXT);"])
|
||||||
|
|
||||||
|
###########################################################
|
||||||
|
|
||||||
def get_current_migration():
|
def get_current_migration():
|
||||||
ver = 0
|
ver = 0
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ find /etc/munin/plugins/ -lname /usr/share/munin/plugins/ntp_ -print0 | xargs -0
|
|||||||
# Deactivate monitoring of network interfaces that are not up. Otherwise we can get a lot of empty charts.
|
# Deactivate monitoring of network interfaces that are not up. Otherwise we can get a lot of empty charts.
|
||||||
for f in $(find /etc/munin/plugins/ \( -lname /usr/share/munin/plugins/if_ -o -lname /usr/share/munin/plugins/if_err_ -o -lname /usr/share/munin/plugins/bonding_err_ \)); do
|
for f in $(find /etc/munin/plugins/ \( -lname /usr/share/munin/plugins/if_ -o -lname /usr/share/munin/plugins/if_err_ -o -lname /usr/share/munin/plugins/bonding_err_ \)); do
|
||||||
IF=$(echo $f | sed s/.*_//);
|
IF=$(echo $f | sed s/.*_//);
|
||||||
if ! ifquery $IF >/dev/null 2>/dev/null; then
|
if ! grep -qFx up /sys/class/net/$IF/operstate 2>/dev/null; then
|
||||||
rm $f;
|
rm $f;
|
||||||
fi;
|
fi;
|
||||||
done
|
done
|
||||||
@@ -64,7 +64,8 @@ mkdir -p /var/lib/munin-node/plugin-state/
|
|||||||
# Create a systemd service for munin.
|
# Create a systemd service for munin.
|
||||||
ln -sf $(pwd)/management/munin_start.sh /usr/local/lib/mailinabox/munin_start.sh
|
ln -sf $(pwd)/management/munin_start.sh /usr/local/lib/mailinabox/munin_start.sh
|
||||||
chmod 0744 /usr/local/lib/mailinabox/munin_start.sh
|
chmod 0744 /usr/local/lib/mailinabox/munin_start.sh
|
||||||
hide_output systemctl link -f conf/munin.service
|
cp --remove-destination conf/munin.service /lib/systemd/system/munin.service # target was previously a symlink so remove first
|
||||||
|
hide_output systemctl link -f /lib/systemd/system/munin.service
|
||||||
hide_output systemctl daemon-reload
|
hide_output systemctl daemon-reload
|
||||||
hide_output systemctl unmask munin.service
|
hide_output systemctl unmask munin.service
|
||||||
hide_output systemctl enable munin.service
|
hide_output systemctl enable munin.service
|
||||||
|
|||||||
@@ -9,28 +9,67 @@ source /etc/mailinabox.conf # load global vars
|
|||||||
|
|
||||||
echo "Installing Nextcloud (contacts/calendar)..."
|
echo "Installing Nextcloud (contacts/calendar)..."
|
||||||
|
|
||||||
|
# Nextcloud core and app (plugin) versions to install.
|
||||||
|
# With each version we store a hash to ensure we install what we expect.
|
||||||
|
|
||||||
|
# Nextcloud core
|
||||||
|
# --------------
|
||||||
|
# * See https://nextcloud.com/changelog for the latest version.
|
||||||
|
# * Check https://docs.nextcloud.com/server/latest/admin_manual/installation/system_requirements.html
|
||||||
|
# for whether it supports the version of PHP available on this machine.
|
||||||
|
# * Since Nextcloud only supports upgrades from consecutive major versions,
|
||||||
|
# we automatically install intermediate versions as needed.
|
||||||
|
# * The hash is the SHA1 hash of the ZIP package, which you can find by just running this script and
|
||||||
|
# copying it from the error message when it doesn't match what is below.
|
||||||
|
nextcloud_ver=20.0.14
|
||||||
|
nextcloud_hash=92cac708915f51ee2afc1787fd845476fd090c81
|
||||||
|
|
||||||
|
# Nextcloud apps
|
||||||
|
# --------------
|
||||||
|
# * Find the most recent tag that is compatible with the Nextcloud version above by
|
||||||
|
# consulting the <dependencies>...<nextcloud> node at:
|
||||||
|
# https://github.com/nextcloud-releases/contacts/blob/master/appinfo/info.xml
|
||||||
|
# https://github.com/nextcloud-releases/calendar/blob/master/appinfo/info.xml
|
||||||
|
# https://github.com/nextcloud/user_external/blob/master/appinfo/info.xml
|
||||||
|
# * The hash is the SHA1 hash of the ZIP package, which you can find by just running this script and
|
||||||
|
# copying it from the error message when it doesn't match what is below.
|
||||||
|
contacts_ver=4.0.7
|
||||||
|
contacts_hash=45e7cf4bfe99cd8d03625cf9e5a1bb2e90549136
|
||||||
|
calendar_ver=3.0.4
|
||||||
|
calendar_hash=d0284b68135777ec9ca713c307216165b294d0fe
|
||||||
|
user_external_ver=1.0.0
|
||||||
|
user_external_hash=3bf2609061d7214e7f0f69dd8883e55c4ec8f50a
|
||||||
|
|
||||||
|
# Clear prior packages and install dependencies from apt.
|
||||||
|
|
||||||
apt-get purge -qq -y owncloud* # we used to use the package manager
|
apt-get purge -qq -y owncloud* # we used to use the package manager
|
||||||
|
|
||||||
apt_install php php-fpm \
|
apt_install php php-fpm \
|
||||||
php-cli php-sqlite3 php-gd php-imap php-curl php-pear curl \
|
php-cli php-sqlite3 php-gd php-imap php-curl php-pear curl \
|
||||||
php-dev php-gd php-xml php-mbstring php-zip php-apcu php-json \
|
php-dev php-gd php-xml php-mbstring php-zip php-apcu php-json \
|
||||||
php-intl php-imagick
|
php-intl php-imagick php-gmp php-bcmath
|
||||||
|
|
||||||
InstallNextcloud() {
|
InstallNextcloud() {
|
||||||
|
|
||||||
version=$1
|
version=$1
|
||||||
hash=$2
|
hash=$2
|
||||||
|
version_contacts=$3
|
||||||
|
hash_contacts=$4
|
||||||
|
version_calendar=$5
|
||||||
|
hash_calendar=$6
|
||||||
|
version_user_external=${7:-}
|
||||||
|
hash_user_external=${8:-}
|
||||||
|
|
||||||
echo
|
echo
|
||||||
echo "Upgrading to Nextcloud version $version"
|
echo "Upgrading to Nextcloud version $version"
|
||||||
echo
|
echo
|
||||||
|
|
||||||
# Remove the current owncloud/Nextcloud
|
|
||||||
rm -rf /usr/local/lib/owncloud
|
|
||||||
|
|
||||||
# Download and verify
|
# Download and verify
|
||||||
wget_verify https://download.nextcloud.com/server/releases/nextcloud-$version.zip $hash /tmp/nextcloud.zip
|
wget_verify https://download.nextcloud.com/server/releases/nextcloud-$version.zip $hash /tmp/nextcloud.zip
|
||||||
|
|
||||||
|
# Remove the current owncloud/Nextcloud
|
||||||
|
rm -rf /usr/local/lib/owncloud
|
||||||
|
|
||||||
# Extract ownCloud/Nextcloud
|
# Extract ownCloud/Nextcloud
|
||||||
unzip -q /tmp/nextcloud.zip -d /usr/local/lib
|
unzip -q /tmp/nextcloud.zip -d /usr/local/lib
|
||||||
mv /usr/local/lib/nextcloud /usr/local/lib/owncloud
|
mv /usr/local/lib/nextcloud /usr/local/lib/owncloud
|
||||||
@@ -40,18 +79,18 @@ InstallNextcloud() {
|
|||||||
# their github repositories.
|
# their github repositories.
|
||||||
mkdir -p /usr/local/lib/owncloud/apps
|
mkdir -p /usr/local/lib/owncloud/apps
|
||||||
|
|
||||||
wget_verify https://github.com/nextcloud/contacts/releases/download/v3.1.1/contacts.tar.gz a06bd967197dcb03c94ec1dbd698c037018669e5 /tmp/contacts.tgz
|
wget_verify https://github.com/nextcloud-releases/contacts/archive/refs/tags/v$version_contacts.tar.gz $hash_contacts /tmp/contacts.tgz
|
||||||
tar xf /tmp/contacts.tgz -C /usr/local/lib/owncloud/apps/
|
tar xf /tmp/contacts.tgz -C /usr/local/lib/owncloud/apps/
|
||||||
rm /tmp/contacts.tgz
|
rm /tmp/contacts.tgz
|
||||||
|
|
||||||
wget_verify https://github.com/nextcloud/calendar/releases/download/v1.6.5/calendar.tar.gz 79941255521a5172f7e4ce42dc7773838b5ede2f /tmp/calendar.tgz
|
wget_verify https://github.com/nextcloud-releases/calendar/archive/refs/tags/v$version_calendar.tar.gz $hash_calendar /tmp/calendar.tgz
|
||||||
tar xf /tmp/calendar.tgz -C /usr/local/lib/owncloud/apps/
|
tar xf /tmp/calendar.tgz -C /usr/local/lib/owncloud/apps/
|
||||||
rm /tmp/calendar.tgz
|
rm /tmp/calendar.tgz
|
||||||
|
|
||||||
# Starting with Nextcloud 15, the app user_external is no longer included in Nextcloud core,
|
# Starting with Nextcloud 15, the app user_external is no longer included in Nextcloud core,
|
||||||
# we will install from their github repository.
|
# we will install from their github repository.
|
||||||
if [[ $version =~ ^15 ]]; then
|
if [ -n "$version_user_external" ]; then
|
||||||
wget_verify https://github.com/nextcloud/user_external/releases/download/v0.6.3/user_external-0.6.3.tar.gz 0f756d35fef6b64a177d6a16020486b76ea5799c /tmp/user_external.tgz
|
wget_verify https://github.com/nextcloud/user_external/releases/download/v$version_user_external/user_external-$version_user_external.tar.gz $hash_user_external /tmp/user_external.tgz
|
||||||
tar -xf /tmp/user_external.tgz -C /usr/local/lib/owncloud/apps/
|
tar -xf /tmp/user_external.tgz -C /usr/local/lib/owncloud/apps/
|
||||||
rm /tmp/user_external.tgz
|
rm /tmp/user_external.tgz
|
||||||
fi
|
fi
|
||||||
@@ -90,18 +129,29 @@ InstallNextcloud() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
nextcloud_ver=15.0.8
|
# Current Nextcloud Version, #1623
|
||||||
nextcloud_hash=4129d8d4021c435f2e86876225fb7f15adf764a3
|
# Checking /usr/local/lib/owncloud/version.php shows version of the Nextcloud application, not the DB
|
||||||
# Check if Nextcloud dir exist, and check if version matches nextcloud_ver (if either doesn't - install/upgrade)
|
# $STORAGE_ROOT/owncloud is kept together even during a backup. It is better to rely on config.php than
|
||||||
if [ ! -d /usr/local/lib/owncloud/ ] \
|
# version.php since the restore procedure can leave the system in a state where you have a newer Nextcloud
|
||||||
|| ! grep -q $nextcloud_ver /usr/local/lib/owncloud/version.php; then
|
# application version than the database.
|
||||||
|
|
||||||
|
# If config.php exists, get version number, otherwise CURRENT_NEXTCLOUD_VER is empty.
|
||||||
|
if [ -f "$STORAGE_ROOT/owncloud/config.php" ]; then
|
||||||
|
CURRENT_NEXTCLOUD_VER=$(php -r "include(\"$STORAGE_ROOT/owncloud/config.php\"); echo(\$CONFIG['version']);")
|
||||||
|
else
|
||||||
|
CURRENT_NEXTCLOUD_VER=""
|
||||||
|
fi
|
||||||
|
|
||||||
|
# If the Nextcloud directory is missing (never been installed before, or the nextcloud version to be installed is different
|
||||||
|
# from the version currently installed, do the install/upgrade
|
||||||
|
if [ ! -d /usr/local/lib/owncloud/ ] || [[ ! ${CURRENT_NEXTCLOUD_VER} =~ ^$nextcloud_ver ]]; then
|
||||||
|
|
||||||
# Stop php-fpm if running. If theyre not running (which happens on a previously failed install), dont bail.
|
# Stop php-fpm if running. If theyre not running (which happens on a previously failed install), dont bail.
|
||||||
service php7.2-fpm stop &> /dev/null || /bin/true
|
service php7.2-fpm stop &> /dev/null || /bin/true
|
||||||
|
|
||||||
# Backup the existing ownCloud/Nextcloud.
|
# Backup the existing ownCloud/Nextcloud.
|
||||||
# Create a backup directory to store the current installation and database to
|
# Create a backup directory to store the current installation and database to
|
||||||
BACKUP_DIRECTORY=$STORAGE_ROOT/owncloud-backup/`date +"%Y-%m-%d-%T"`
|
BACKUP_DIRECTORY=$STORAGE_ROOT/owncloud-backup/$(date +"%Y-%m-%d-%T")
|
||||||
mkdir -p "$BACKUP_DIRECTORY"
|
mkdir -p "$BACKUP_DIRECTORY"
|
||||||
if [ -d /usr/local/lib/owncloud/ ]; then
|
if [ -d /usr/local/lib/owncloud/ ]; then
|
||||||
echo "Upgrading Nextcloud --- backing up existing installation, configuration, and database to directory to $BACKUP_DIRECTORY..."
|
echo "Upgrading Nextcloud --- backing up existing installation, configuration, and database to directory to $BACKUP_DIRECTORY..."
|
||||||
@@ -115,30 +165,51 @@ if [ ! -d /usr/local/lib/owncloud/ ] \
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# If ownCloud or Nextcloud was previously installed....
|
# If ownCloud or Nextcloud was previously installed....
|
||||||
if [ -e /usr/local/lib/owncloud/version.php ]; then
|
if [ ! -z ${CURRENT_NEXTCLOUD_VER} ]; then
|
||||||
# Database migrations from ownCloud are no longer possible because ownCloud cannot be run under
|
# Database migrations from ownCloud are no longer possible because ownCloud cannot be run under
|
||||||
# PHP 7.
|
# PHP 7.
|
||||||
if grep -q "OC_VersionString = '[89]\." /usr/local/lib/owncloud/version.php; then
|
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^[89] ]]; then
|
||||||
echo "Upgrades from Mail-in-a-Box prior to v0.28 (dated July 30, 2018) with Nextcloud < 13.0.6 (you have ownCloud 8 or 9) are not supported. Upgrade to Mail-in-a-Box version v0.30 first. Setup aborting."
|
echo "Upgrades from Mail-in-a-Box prior to v0.28 (dated July 30, 2018) with Nextcloud < 13.0.6 (you have ownCloud 8 or 9) are not supported. Upgrade to Mail-in-a-Box version v0.30 first. Setup will continue, but skip the Nextcloud migration."
|
||||||
exit 1
|
return 0
|
||||||
fi
|
elif [[ ${CURRENT_NEXTCLOUD_VER} =~ ^1[012] ]]; then
|
||||||
if grep -q "OC_VersionString = '1[012]\." /usr/local/lib/owncloud/version.php; then
|
echo "Upgrades from Mail-in-a-Box prior to v0.28 (dated July 30, 2018) with Nextcloud < 13.0.6 (you have ownCloud 10, 11 or 12) are not supported. Upgrade to Mail-in-a-Box version v0.30 first. Setup will continue, but skip the Nextcloud migration."
|
||||||
echo "Upgrades from Mail-in-a-Box prior to v0.28 (dated July 30, 2018) with Nextcloud < 13.0.6 (you have ownCloud 10, 11 or 12) are not supported. Upgrade to Mail-in-a-Box version v0.30 first. Setup aborting."
|
return 0
|
||||||
exit 1
|
elif [[ ${CURRENT_NEXTCLOUD_VER} =~ ^13 ]]; then
|
||||||
fi
|
|
||||||
# If we are running Nextcloud 13, upgrade to Nextcloud 14
|
# If we are running Nextcloud 13, upgrade to Nextcloud 14
|
||||||
if grep -q "OC_VersionString = '13\." /usr/local/lib/owncloud/version.php; then
|
InstallNextcloud 14.0.6 4e43a57340f04c2da306c8eea98e30040399ae5a 3.3.0 e55d0357c6785d3b1f3b5f21780cb6d41d32443a 2.0.3 9d9717b29337613b72c74e9914c69b74b346c466
|
||||||
InstallNextcloud 14.0.6 4e43a57340f04c2da306c8eea98e30040399ae5a
|
CURRENT_NEXTCLOUD_VER="14.0.6"
|
||||||
|
|
||||||
fi
|
fi
|
||||||
|
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^14 ]]; then
|
||||||
# During the upgrade from Nextcloud 14 to 15, user_external may cause the upgrade to fail.
|
# During the upgrade from Nextcloud 14 to 15, user_external may cause the upgrade to fail.
|
||||||
# We will disable it here before the upgrade and install it again after the upgrade.
|
# We will disable it here before the upgrade and install it again after the upgrade.
|
||||||
if grep -q "OC_VersionString = '14\." /usr/local/lib/owncloud/version.php; then
|
|
||||||
hide_output sudo -u www-data php /usr/local/lib/owncloud/console.php app:disable user_external
|
hide_output sudo -u www-data php /usr/local/lib/owncloud/console.php app:disable user_external
|
||||||
|
InstallNextcloud 15.0.8 4129d8d4021c435f2e86876225fb7f15adf764a3 3.3.0 e55d0357c6785d3b1f3b5f21780cb6d41d32443a 2.0.3 a1f3835c752929e3598eb94f22300516867ac6ab 0.7.0 555a94811daaf5bdd336c5e48a78aa8567b86437
|
||||||
|
CURRENT_NEXTCLOUD_VER="15.0.8"
|
||||||
|
fi
|
||||||
|
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^15 ]]; then
|
||||||
|
InstallNextcloud 16.0.6 0bb3098455ec89f5af77a652aad553ad40a88819 3.3.0 e55d0357c6785d3b1f3b5f21780cb6d41d32443a 2.0.3 a1f3835c752929e3598eb94f22300516867ac6ab 0.7.0 555a94811daaf5bdd336c5e48a78aa8567b86437
|
||||||
|
CURRENT_NEXTCLOUD_VER="16.0.6"
|
||||||
|
fi
|
||||||
|
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^16 ]]; then
|
||||||
|
InstallNextcloud 17.0.6 50b98d2c2f18510b9530e558ced9ab51eb4f11b0 3.3.0 e55d0357c6785d3b1f3b5f21780cb6d41d32443a 2.0.3 a1f3835c752929e3598eb94f22300516867ac6ab 0.7.0 555a94811daaf5bdd336c5e48a78aa8567b86437
|
||||||
|
CURRENT_NEXTCLOUD_VER="17.0.6"
|
||||||
|
fi
|
||||||
|
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^17 ]]; then
|
||||||
|
# Don't exit the install if this column already exists (see #2076)
|
||||||
|
(echo "ALTER TABLE oc_flow_operations ADD COLUMN entity VARCHAR;" | sqlite3 $STORAGE_ROOT/owncloud/owncloud.db 2>/dev/null) || true
|
||||||
|
InstallNextcloud 18.0.10 39c0021a8b8477c3f1733fddefacfa5ebf921c68 3.4.1 8f685e7dc99758636d660d595e389c324e51e9d1 2.0.3 a1f3835c752929e3598eb94f22300516867ac6ab 1.0.0 3bf2609061d7214e7f0f69dd8883e55c4ec8f50a
|
||||||
|
CURRENT_NEXTCLOUD_VER="18.0.10"
|
||||||
|
fi
|
||||||
|
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^18 ]]; then
|
||||||
|
InstallNextcloud 19.0.4 01e98791ba12f4860d3d4047b9803f97a1b55c60 3.4.1 8f685e7dc99758636d660d595e389c324e51e9d1 2.0.3 a1f3835c752929e3598eb94f22300516867ac6ab 1.0.0 3bf2609061d7214e7f0f69dd8883e55c4ec8f50a
|
||||||
|
CURRENT_NEXTCLOUD_VER="19.0.4"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
InstallNextcloud $nextcloud_ver $nextcloud_hash
|
InstallNextcloud $nextcloud_ver $nextcloud_hash $contacts_ver $contacts_hash $calendar_ver $calendar_hash $user_external_ver $user_external_hash
|
||||||
|
|
||||||
|
# Nextcloud 20 needs to have some optional columns added
|
||||||
|
sudo -u www-data php /usr/local/lib/owncloud/occ db:add-missing-columns
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ### Configuring Nextcloud
|
# ### Configuring Nextcloud
|
||||||
@@ -264,6 +335,11 @@ hide_output sudo -u www-data php /usr/local/lib/owncloud/console.php app:enable
|
|||||||
sudo -u www-data php /usr/local/lib/owncloud/occ upgrade
|
sudo -u www-data php /usr/local/lib/owncloud/occ upgrade
|
||||||
if [ \( $? -ne 0 \) -a \( $? -ne 3 \) ]; then exit 1; fi
|
if [ \( $? -ne 0 \) -a \( $? -ne 3 \) ]; then exit 1; fi
|
||||||
|
|
||||||
|
# Disable default apps that we don't support
|
||||||
|
sudo -u www-data \
|
||||||
|
php /usr/local/lib/owncloud/occ app:disable photos dashboard activity \
|
||||||
|
| (grep -v "No such app enabled" || /bin/true)
|
||||||
|
|
||||||
# Set PHP FPM values to support large file uploads
|
# Set PHP FPM values to support large file uploads
|
||||||
# (semicolon is the comment character in this file, hashes produce deprecation warnings)
|
# (semicolon is the comment character in this file, hashes produce deprecation warnings)
|
||||||
tools/editconf.py /etc/php/7.2/fpm/php.ini -c ';' \
|
tools/editconf.py /etc/php/7.2/fpm/php.ini -c ';' \
|
||||||
@@ -284,10 +360,6 @@ tools/editconf.py /etc/php/7.2/cli/conf.d/10-opcache.ini -c ';' \
|
|||||||
opcache.save_comments=1 \
|
opcache.save_comments=1 \
|
||||||
opcache.revalidate_freq=1
|
opcache.revalidate_freq=1
|
||||||
|
|
||||||
# Configure the path environment for php-fpm
|
|
||||||
tools/editconf.py /etc/php/7.2/fpm/pool.d/www.conf -c ';' \
|
|
||||||
env[PATH]=/usr/local/bin:/usr/bin:/bin
|
|
||||||
|
|
||||||
# If apc is explicitly disabled we need to enable it
|
# If apc is explicitly disabled we need to enable it
|
||||||
if grep -q apc.enabled=0 /etc/php/7.2/mods-available/apcu.ini; then
|
if grep -q apc.enabled=0 /etc/php/7.2/mods-available/apcu.ini; then
|
||||||
tools/editconf.py /etc/php/7.2/mods-available/apcu.ini -c ';' \
|
tools/editconf.py /etc/php/7.2/mods-available/apcu.ini -c ';' \
|
||||||
@@ -295,18 +367,21 @@ if grep -q apc.enabled=0 /etc/php/7.2/mods-available/apcu.ini; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Set up a cron job for Nextcloud.
|
# Set up a cron job for Nextcloud.
|
||||||
cat > /etc/cron.hourly/mailinabox-owncloud << EOF;
|
cat > /etc/cron.d/mailinabox-nextcloud << EOF;
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# Mail-in-a-Box
|
# Mail-in-a-Box
|
||||||
sudo -u www-data php -f /usr/local/lib/owncloud/cron.php
|
*/5 * * * * root sudo -u www-data php -f /usr/local/lib/owncloud/cron.php
|
||||||
EOF
|
EOF
|
||||||
chmod +x /etc/cron.hourly/mailinabox-owncloud
|
chmod +x /etc/cron.d/mailinabox-nextcloud
|
||||||
|
|
||||||
|
# Remove previous hourly cronjob
|
||||||
|
rm -f /etc/cron.hourly/mailinabox-owncloud
|
||||||
|
|
||||||
# There's nothing much of interest that a user could do as an admin for Nextcloud,
|
# There's nothing much of interest that a user could do as an admin for Nextcloud,
|
||||||
# and there's a lot they could mess up, so we don't make any users admins of Nextcloud.
|
# and there's a lot they could mess up, so we don't make any users admins of Nextcloud.
|
||||||
# But if we wanted to, we would do this:
|
# But if we wanted to, we would do this:
|
||||||
# ```
|
# ```
|
||||||
# for user in $(tools/mail.py user admins); do
|
# for user in $(management/cli.py user admins); do
|
||||||
# sqlite3 $STORAGE_ROOT/owncloud/owncloud.db "INSERT OR IGNORE INTO oc_group_user VALUES ('admin', '$user')"
|
# sqlite3 $STORAGE_ROOT/owncloud/owncloud.db "INSERT OR IGNORE INTO oc_group_user VALUES ('admin', '$user')"
|
||||||
# done
|
# done
|
||||||
# ```
|
# ```
|
||||||
|
|||||||
@@ -4,17 +4,17 @@ if [[ $EUID -ne 0 ]]; then
|
|||||||
echo
|
echo
|
||||||
echo "sudo $0"
|
echo "sudo $0"
|
||||||
echo
|
echo
|
||||||
exit
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Check that we are running on Ubuntu 18.04 LTS (or 18.04.xx).
|
# Check that we are running on Ubuntu 18.04 LTS (or 18.04.xx).
|
||||||
if [ "`lsb_release -d | sed 's/.*:\s*//' | sed 's/18\.04\.[0-9]/18.04/' `" != "Ubuntu 18.04 LTS" ]; then
|
if [ "$(lsb_release -d | sed 's/.*:\s*//' | sed 's/18\.04\.[0-9]/18.04/' )" != "Ubuntu 18.04 LTS" ]; then
|
||||||
echo "Mail-in-a-Box only supports being installed on Ubuntu 18.04, sorry. You are running:"
|
echo "Mail-in-a-Box only supports being installed on Ubuntu 18.04, sorry. You are running:"
|
||||||
echo
|
echo
|
||||||
lsb_release -d | sed 's/.*:\s*//'
|
lsb_release -d | sed 's/.*:\s*//'
|
||||||
echo
|
echo
|
||||||
echo "We can't write scripts that run on every possible setup, sorry."
|
echo "We can't write scripts that run on every possible setup, sorry."
|
||||||
exit
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Check that we have enough memory.
|
# Check that we have enough memory.
|
||||||
|
|||||||
@@ -64,8 +64,58 @@ tools/editconf.py /etc/default/spampd \
|
|||||||
# the X-Spam-Status & X-Spam-Score mail headers and related headers.
|
# the X-Spam-Status & X-Spam-Score mail headers and related headers.
|
||||||
tools/editconf.py /etc/spamassassin/local.cf -s \
|
tools/editconf.py /etc/spamassassin/local.cf -s \
|
||||||
report_safe=0 \
|
report_safe=0 \
|
||||||
add_header="all Report _REPORT_" \
|
"add_header all Report"=_REPORT_ \
|
||||||
add_header="all Score _SCORE_"
|
"add_header all Score"=_SCORE_
|
||||||
|
|
||||||
|
|
||||||
|
# Authentication-Results SPF/Dmarc checks
|
||||||
|
# ---------------------------------------
|
||||||
|
# OpenDKIM and OpenDMARC are configured to validate and add "Authentication-Results: ..."
|
||||||
|
# headers by checking the sender's SPF & DMARC policies. Instead of blocking mail that fails
|
||||||
|
# these checks, we can use these headers to evaluate the mail as spam.
|
||||||
|
#
|
||||||
|
# Our custom rules are added to their own file so that an update to the deb package config
|
||||||
|
# does not remove our changes.
|
||||||
|
#
|
||||||
|
# We need to escape period's in $PRIMARY_HOSTNAME since spamassassin config uses regex.
|
||||||
|
|
||||||
|
escapedprimaryhostname="${PRIMARY_HOSTNAME//./\\.}"
|
||||||
|
|
||||||
|
cat > /etc/spamassassin/miab_spf_dmarc.cf << EOF
|
||||||
|
# Evaluate DMARC Authentication-Results
|
||||||
|
header DMARC_PASS Authentication-Results =~ /$escapedprimaryhostname; dmarc=pass/
|
||||||
|
describe DMARC_PASS DMARC check passed
|
||||||
|
score DMARC_PASS -0.1
|
||||||
|
|
||||||
|
header DMARC_NONE Authentication-Results =~ /$escapedprimaryhostname; dmarc=none/
|
||||||
|
describe DMARC_NONE DMARC record not found
|
||||||
|
score DMARC_NONE 0.1
|
||||||
|
|
||||||
|
header DMARC_FAIL_NONE Authentication-Results =~ /$escapedprimaryhostname; dmarc=fail \(p=none/
|
||||||
|
describe DMARC_FAIL_NONE DMARC check failed (p=none)
|
||||||
|
score DMARC_FAIL_NONE 2.0
|
||||||
|
|
||||||
|
header DMARC_FAIL_QUARANTINE Authentication-Results =~ /$escapedprimaryhostname; dmarc=fail \(p=quarantine/
|
||||||
|
describe DMARC_FAIL_QUARANTINE DMARC check failed (p=quarantine)
|
||||||
|
score DMARC_FAIL_QUARANTINE 5.0
|
||||||
|
|
||||||
|
header DMARC_FAIL_REJECT Authentication-Results =~ /$escapedprimaryhostname; dmarc=fail \(p=reject/
|
||||||
|
describe DMARC_FAIL_REJECT DMARC check failed (p=reject)
|
||||||
|
score DMARC_FAIL_REJECT 10.0
|
||||||
|
|
||||||
|
# Evaluate SPF Authentication-Results
|
||||||
|
header SPF_PASS Authentication-Results =~ /$escapedprimaryhostname; spf=pass/
|
||||||
|
describe SPF_PASS SPF check passed
|
||||||
|
score SPF_PASS -0.1
|
||||||
|
|
||||||
|
header SPF_NONE Authentication-Results =~ /$escapedprimaryhostname; spf=none/
|
||||||
|
describe SPF_NONE SPF record not found
|
||||||
|
score SPF_NONE 2.0
|
||||||
|
|
||||||
|
header SPF_FAIL Authentication-Results =~ /$escapedprimaryhostname; spf=fail/
|
||||||
|
describe SPF_FAIL SPF check failed
|
||||||
|
score SPF_FAIL 5.0
|
||||||
|
EOF
|
||||||
|
|
||||||
# Bayesean learning
|
# Bayesean learning
|
||||||
# -----------------
|
# -----------------
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
#
|
#
|
||||||
# * DNSSEC DANE TLSA records
|
# * DNSSEC DANE TLSA records
|
||||||
# * IMAP
|
# * IMAP
|
||||||
# * SMTP (opportunistic TLS for port 25 and submission on port 587)
|
# * SMTP (opportunistic TLS for port 25 and submission on ports 465/587)
|
||||||
# * HTTPS
|
# * HTTPS
|
||||||
#
|
#
|
||||||
# The certificate is created with its CN set to the PRIMARY_HOSTNAME. It is
|
# The certificate is created with its CN set to the PRIMARY_HOSTNAME. It is
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ fi
|
|||||||
# in the first dialog prompt, so we should do this before that starts.
|
# in the first dialog prompt, so we should do this before that starts.
|
||||||
cat > /usr/local/bin/mailinabox << EOF;
|
cat > /usr/local/bin/mailinabox << EOF;
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
cd `pwd`
|
cd $(pwd)
|
||||||
source setup/start.sh
|
source setup/start.sh
|
||||||
EOF
|
EOF
|
||||||
chmod +x /usr/local/bin/mailinabox
|
chmod +x /usr/local/bin/mailinabox
|
||||||
@@ -78,13 +78,14 @@ if [ ! -d $STORAGE_ROOT ]; then
|
|||||||
mkdir -p $STORAGE_ROOT
|
mkdir -p $STORAGE_ROOT
|
||||||
fi
|
fi
|
||||||
if [ ! -f $STORAGE_ROOT/mailinabox.version ]; then
|
if [ ! -f $STORAGE_ROOT/mailinabox.version ]; then
|
||||||
echo $(setup/migrate.py --current) > $STORAGE_ROOT/mailinabox.version
|
setup/migrate.py --current > $STORAGE_ROOT/mailinabox.version
|
||||||
chown $STORAGE_USER.$STORAGE_USER $STORAGE_ROOT/mailinabox.version
|
chown $STORAGE_USER.$STORAGE_USER $STORAGE_ROOT/mailinabox.version
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|
||||||
# Save the global options in /etc/mailinabox.conf so that standalone
|
# Save the global options in /etc/mailinabox.conf so that standalone
|
||||||
# tools know where to look for data.
|
# tools know where to look for data. The default MTA_STS_MODE setting
|
||||||
|
# is blank unless set by an environment variable, but see web.sh for
|
||||||
|
# how that is interpreted.
|
||||||
cat > /etc/mailinabox.conf << EOF;
|
cat > /etc/mailinabox.conf << EOF;
|
||||||
STORAGE_USER=$STORAGE_USER
|
STORAGE_USER=$STORAGE_USER
|
||||||
STORAGE_ROOT=$STORAGE_ROOT
|
STORAGE_ROOT=$STORAGE_ROOT
|
||||||
@@ -93,6 +94,7 @@ PUBLIC_IP=$PUBLIC_IP
|
|||||||
PUBLIC_IPV6=$PUBLIC_IPV6
|
PUBLIC_IPV6=$PUBLIC_IPV6
|
||||||
PRIVATE_IP=$PRIVATE_IP
|
PRIVATE_IP=$PRIVATE_IP
|
||||||
PRIVATE_IPV6=$PRIVATE_IPV6
|
PRIVATE_IPV6=$PRIVATE_IPV6
|
||||||
|
MTA_STS_MODE=${DEFAULT_MTA_STS_MODE:-enforce}
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
# Start service configuration.
|
# Start service configuration.
|
||||||
|
|||||||
@@ -75,6 +75,13 @@ then
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# ### Set log retention policy.
|
||||||
|
|
||||||
|
# Set the systemd journal log retention from infinite to 10 days,
|
||||||
|
# since over time the logs take up a large amount of space.
|
||||||
|
# (See https://discourse.mailinabox.email/t/journalctl-reclaim-space-on-small-mailinabox/6728/11.)
|
||||||
|
tools/editconf.py /etc/systemd/journald.conf MaxRetentionSec=10day
|
||||||
|
|
||||||
# ### Add PPAs.
|
# ### Add PPAs.
|
||||||
|
|
||||||
# We install some non-standard Ubuntu packages maintained by other
|
# We install some non-standard Ubuntu packages maintained by other
|
||||||
@@ -86,9 +93,16 @@ if [ ! -f /usr/bin/add-apt-repository ]; then
|
|||||||
apt_install software-properties-common
|
apt_install software-properties-common
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Ensure the universe repository is enabled since some of our packages
|
||||||
|
# come from there and minimal Ubuntu installs may have it turned off.
|
||||||
|
hide_output add-apt-repository -y universe
|
||||||
|
|
||||||
# Install the certbot PPA.
|
# Install the certbot PPA.
|
||||||
hide_output add-apt-repository -y ppa:certbot/certbot
|
hide_output add-apt-repository -y ppa:certbot/certbot
|
||||||
|
|
||||||
|
# Install the duplicity PPA.
|
||||||
|
hide_output add-apt-repository -y ppa:duplicity-team/duplicity-release-git
|
||||||
|
|
||||||
# ### Update Packages
|
# ### Update Packages
|
||||||
|
|
||||||
# Update system packages to make sure we have the latest upstream versions
|
# Update system packages to make sure we have the latest upstream versions
|
||||||
@@ -121,11 +135,12 @@ apt_get_quiet autoremove
|
|||||||
# * sudo: allows privileged users to execute commands as root without being root
|
# * sudo: allows privileged users to execute commands as root without being root
|
||||||
# * coreutils: includes `nproc` tool to report number of processors, mktemp
|
# * coreutils: includes `nproc` tool to report number of processors, mktemp
|
||||||
# * bc: allows us to do math to compute sane defaults
|
# * bc: allows us to do math to compute sane defaults
|
||||||
|
# * openssh-client: provides ssh-keygen
|
||||||
|
|
||||||
echo Installing system packages...
|
echo Installing system packages...
|
||||||
apt_install python3 python3-dev python3-pip \
|
apt_install python3 python3-dev python3-pip python3-setuptools \
|
||||||
netcat-openbsd wget curl git sudo coreutils bc \
|
netcat-openbsd wget curl git sudo coreutils bc \
|
||||||
haveged pollinate unzip \
|
haveged pollinate openssh-client unzip \
|
||||||
unattended-upgrades cron ntp fail2ban rsyslog
|
unattended-upgrades cron ntp fail2ban rsyslog
|
||||||
|
|
||||||
# ### Suppress Upgrade Prompts
|
# ### Suppress Upgrade Prompts
|
||||||
@@ -251,7 +266,7 @@ if [ -z "${DISABLE_FIREWALL:-}" ]; then
|
|||||||
apt_install ufw
|
apt_install ufw
|
||||||
|
|
||||||
# Allow incoming connections to SSH.
|
# Allow incoming connections to SSH.
|
||||||
ufw_allow ssh;
|
ufw_limit ssh;
|
||||||
|
|
||||||
# ssh might be running on an alternate port. Use sshd -T to dump sshd's #NODOC
|
# ssh might be running on an alternate port. Use sshd -T to dump sshd's #NODOC
|
||||||
# settings, find the port it is supposedly running on, and open that port #NODOC
|
# settings, find the port it is supposedly running on, and open that port #NODOC
|
||||||
@@ -261,7 +276,7 @@ if [ -z "${DISABLE_FIREWALL:-}" ]; then
|
|||||||
if [ "$SSH_PORT" != "22" ]; then
|
if [ "$SSH_PORT" != "22" ]; then
|
||||||
|
|
||||||
echo Opening alternate SSH port $SSH_PORT. #NODOC
|
echo Opening alternate SSH port $SSH_PORT. #NODOC
|
||||||
ufw_allow $SSH_PORT #NODOC
|
ufw_limit $SSH_PORT #NODOC
|
||||||
|
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
@@ -312,6 +327,9 @@ fi #NODOC
|
|||||||
# name server, on IPV6.
|
# name server, on IPV6.
|
||||||
# * The listen-on directive in named.conf.options restricts `bind9` to
|
# * The listen-on directive in named.conf.options restricts `bind9` to
|
||||||
# binding to the loopback interface instead of all interfaces.
|
# binding to the loopback interface instead of all interfaces.
|
||||||
|
# * The max-recursion-queries directive increases the maximum number of iterative queries.
|
||||||
|
# If more queries than specified are sent, bind9 returns SERVFAIL. After flushing the cache during system checks,
|
||||||
|
# we ran into the limit thus we are increasing it from 75 (default value) to 100.
|
||||||
apt_install bind9
|
apt_install bind9
|
||||||
tools/editconf.py /etc/default/bind9 \
|
tools/editconf.py /etc/default/bind9 \
|
||||||
"OPTIONS=\"-u bind -4\""
|
"OPTIONS=\"-u bind -4\""
|
||||||
@@ -319,6 +337,10 @@ if ! grep -q "listen-on " /etc/bind/named.conf.options; then
|
|||||||
# Add a listen-on directive if it doesn't exist inside the options block.
|
# Add a listen-on directive if it doesn't exist inside the options block.
|
||||||
sed -i "s/^}/\n\tlisten-on { 127.0.0.1; };\n}/" /etc/bind/named.conf.options
|
sed -i "s/^}/\n\tlisten-on { 127.0.0.1; };\n}/" /etc/bind/named.conf.options
|
||||||
fi
|
fi
|
||||||
|
if ! grep -q "max-recursion-queries " /etc/bind/named.conf.options; then
|
||||||
|
# Add a max-recursion-queries directive if it doesn't exist inside the options block.
|
||||||
|
sed -i "s/^}/\n\tmax-recursion-queries 100;\n}/" /etc/bind/named.conf.options
|
||||||
|
fi
|
||||||
|
|
||||||
# First we'll disable systemd-resolved's management of resolv.conf and its stub server.
|
# First we'll disable systemd-resolved's management of resolv.conf and its stub server.
|
||||||
# Breaking the symlink to /run/systemd/resolve/stub-resolv.conf means
|
# Breaking the symlink to /run/systemd/resolve/stub-resolv.conf means
|
||||||
@@ -341,6 +363,7 @@ systemctl restart systemd-resolved
|
|||||||
rm -f /etc/fail2ban/jail.local # we used to use this file but don't anymore
|
rm -f /etc/fail2ban/jail.local # we used to use this file but don't anymore
|
||||||
rm -f /etc/fail2ban/jail.d/defaults-debian.conf # removes default config so we can manage all of fail2ban rules in one config
|
rm -f /etc/fail2ban/jail.d/defaults-debian.conf # removes default config so we can manage all of fail2ban rules in one config
|
||||||
cat conf/fail2ban/jails.conf \
|
cat conf/fail2ban/jails.conf \
|
||||||
|
| sed "s/PUBLIC_IPV6/$PUBLIC_IPV6/g" \
|
||||||
| sed "s/PUBLIC_IP/$PUBLIC_IP/g" \
|
| sed "s/PUBLIC_IP/$PUBLIC_IP/g" \
|
||||||
| sed "s#STORAGE_ROOT#$STORAGE_ROOT#" \
|
| sed "s#STORAGE_ROOT#$STORAGE_ROOT#" \
|
||||||
> /etc/fail2ban/jail.d/mailinabox.conf
|
> /etc/fail2ban/jail.d/mailinabox.conf
|
||||||
|
|||||||
67
setup/web.sh
67
setup/web.sh
@@ -19,7 +19,7 @@ fi
|
|||||||
|
|
||||||
echo "Installing Nginx (web server)..."
|
echo "Installing Nginx (web server)..."
|
||||||
|
|
||||||
apt_install nginx php-cli php-fpm
|
apt_install nginx php-cli php-fpm idn2
|
||||||
|
|
||||||
rm -f /etc/nginx/sites-enabled/default
|
rm -f /etc/nginx/sites-enabled/default
|
||||||
|
|
||||||
@@ -31,14 +31,19 @@ sed "s#STORAGE_ROOT#$STORAGE_ROOT#" \
|
|||||||
conf/nginx-ssl.conf > /etc/nginx/conf.d/ssl.conf
|
conf/nginx-ssl.conf > /etc/nginx/conf.d/ssl.conf
|
||||||
|
|
||||||
# Fix some nginx defaults.
|
# Fix some nginx defaults.
|
||||||
|
#
|
||||||
# The server_names_hash_bucket_size seems to prevent long domain names!
|
# The server_names_hash_bucket_size seems to prevent long domain names!
|
||||||
# The default, according to nginx's docs, depends on "the size of the
|
# The default, according to nginx's docs, depends on "the size of the
|
||||||
# processor’s cache line." It could be as low as 32. We fixed it at
|
# processor’s cache line." It could be as low as 32. We fixed it at
|
||||||
# 64 in 2014 to accommodate a long domain name (20 characters?). But
|
# 64 in 2014 to accommodate a long domain name (20 characters?). But
|
||||||
# even at 64, a 58-character domain name won't work (#93), so now
|
# even at 64, a 58-character domain name won't work (#93), so now
|
||||||
# we're going up to 128.
|
# we're going up to 128.
|
||||||
|
#
|
||||||
|
# Drop TLSv1.0, TLSv1.1, following the Mozilla "Intermediate" recommendations
|
||||||
|
# at https://ssl-config.mozilla.org/#server=nginx&server-version=1.17.0&config=intermediate&openssl-version=1.1.1.
|
||||||
tools/editconf.py /etc/nginx/nginx.conf -s \
|
tools/editconf.py /etc/nginx/nginx.conf -s \
|
||||||
server_names_hash_bucket_size="128;"
|
server_names_hash_bucket_size="128;" \
|
||||||
|
ssl_protocols="TLSv1.2 TLSv1.3;"
|
||||||
|
|
||||||
# Tell PHP not to expose its version number in the X-Powered-By header.
|
# Tell PHP not to expose its version number in the X-Powered-By header.
|
||||||
tools/editconf.py /etc/php/7.2/fpm/php.ini -c ';' \
|
tools/editconf.py /etc/php/7.2/fpm/php.ini -c ';' \
|
||||||
@@ -48,13 +53,47 @@ tools/editconf.py /etc/php/7.2/fpm/php.ini -c ';' \
|
|||||||
tools/editconf.py /etc/php/7.2/fpm/php.ini -c ';' \
|
tools/editconf.py /etc/php/7.2/fpm/php.ini -c ';' \
|
||||||
default_charset="UTF-8"
|
default_charset="UTF-8"
|
||||||
|
|
||||||
# Switch from the dynamic process manager to the ondemand manager see #1216
|
# Configure the path environment for php-fpm
|
||||||
tools/editconf.py /etc/php/7.2/fpm/pool.d/www.conf -c ';' \
|
tools/editconf.py /etc/php/7.2/fpm/pool.d/www.conf -c ';' \
|
||||||
pm=ondemand
|
env[PATH]=/usr/local/bin:/usr/bin:/bin \
|
||||||
|
|
||||||
# Bump up PHP's max_children to support more concurrent connections
|
# Configure php-fpm based on the amount of memory the machine has
|
||||||
|
# This is based on the nextcloud manual for performance tuning: https://docs.nextcloud.com/server/17/admin_manual/installation/server_tuning.html
|
||||||
|
# Some synchronisation issues can occur when many people access the site at once.
|
||||||
|
# The pm=ondemand setting is used for memory constrained machines < 2GB, this is copied over from PR: 1216
|
||||||
|
TOTAL_PHYSICAL_MEM=$(head -n 1 /proc/meminfo | awk '{print $2}' || /bin/true)
|
||||||
|
if [ $TOTAL_PHYSICAL_MEM -lt 1000000 ]
|
||||||
|
then
|
||||||
tools/editconf.py /etc/php/7.2/fpm/pool.d/www.conf -c ';' \
|
tools/editconf.py /etc/php/7.2/fpm/pool.d/www.conf -c ';' \
|
||||||
pm.max_children=8
|
pm=ondemand \
|
||||||
|
pm.max_children=8 \
|
||||||
|
pm.start_servers=2 \
|
||||||
|
pm.min_spare_servers=1 \
|
||||||
|
pm.max_spare_servers=3
|
||||||
|
elif [ $TOTAL_PHYSICAL_MEM -lt 2000000 ]
|
||||||
|
then
|
||||||
|
tools/editconf.py /etc/php/7.2/fpm/pool.d/www.conf -c ';' \
|
||||||
|
pm=ondemand \
|
||||||
|
pm.max_children=16 \
|
||||||
|
pm.start_servers=4 \
|
||||||
|
pm.min_spare_servers=1 \
|
||||||
|
pm.max_spare_servers=6
|
||||||
|
elif [ $TOTAL_PHYSICAL_MEM -lt 3000000 ]
|
||||||
|
then
|
||||||
|
tools/editconf.py /etc/php/7.2/fpm/pool.d/www.conf -c ';' \
|
||||||
|
pm=dynamic \
|
||||||
|
pm.max_children=60 \
|
||||||
|
pm.start_servers=6 \
|
||||||
|
pm.min_spare_servers=3 \
|
||||||
|
pm.max_spare_servers=9
|
||||||
|
else
|
||||||
|
tools/editconf.py /etc/php/7.2/fpm/pool.d/www.conf -c ';' \
|
||||||
|
pm=dynamic \
|
||||||
|
pm.max_children=120 \
|
||||||
|
pm.start_servers=12 \
|
||||||
|
pm.min_spare_servers=6 \
|
||||||
|
pm.max_spare_servers=18
|
||||||
|
fi
|
||||||
|
|
||||||
# Other nginx settings will be configured by the management service
|
# Other nginx settings will be configured by the management service
|
||||||
# since it depends on what domains we're serving, which we don't know
|
# since it depends on what domains we're serving, which we don't know
|
||||||
@@ -83,6 +122,21 @@ cat conf/mozilla-autoconfig.xml \
|
|||||||
> /var/lib/mailinabox/mozilla-autoconfig.xml
|
> /var/lib/mailinabox/mozilla-autoconfig.xml
|
||||||
chmod a+r /var/lib/mailinabox/mozilla-autoconfig.xml
|
chmod a+r /var/lib/mailinabox/mozilla-autoconfig.xml
|
||||||
|
|
||||||
|
# Create a generic mta-sts.txt file which is exposed via the
|
||||||
|
# nginx configuration at /.well-known/mta-sts.txt
|
||||||
|
# more documentation is available on:
|
||||||
|
# https://www.uriports.com/blog/mta-sts-explained/
|
||||||
|
# default mode is "enforce". In /etc/mailinabox.conf change
|
||||||
|
# "MTA_STS_MODE=testing" which means "Messages will be delivered
|
||||||
|
# as though there was no failure but a report will be sent if
|
||||||
|
# TLS-RPT is configured" if you are not sure you want this yet. Or "none".
|
||||||
|
PUNY_PRIMARY_HOSTNAME=$(echo "$PRIMARY_HOSTNAME" | idn2)
|
||||||
|
cat conf/mta-sts.txt \
|
||||||
|
| sed "s/MODE/${MTA_STS_MODE}/" \
|
||||||
|
| sed "s/PRIMARY_HOSTNAME/$PUNY_PRIMARY_HOSTNAME/" \
|
||||||
|
> /var/lib/mailinabox/mta-sts.txt
|
||||||
|
chmod a+r /var/lib/mailinabox/mta-sts.txt
|
||||||
|
|
||||||
# make a default homepage
|
# make a default homepage
|
||||||
if [ -d $STORAGE_ROOT/www/static ]; then mv $STORAGE_ROOT/www/static $STORAGE_ROOT/www/default; fi # migration #NODOC
|
if [ -d $STORAGE_ROOT/www/static ]; then mv $STORAGE_ROOT/www/static $STORAGE_ROOT/www/default; fi # migration #NODOC
|
||||||
mkdir -p $STORAGE_ROOT/www/default
|
mkdir -p $STORAGE_ROOT/www/default
|
||||||
@@ -98,4 +152,3 @@ restart_service php7.2-fpm
|
|||||||
# Open ports.
|
# Open ports.
|
||||||
ufw_allow http
|
ufw_allow http
|
||||||
ufw_allow https
|
ufw_allow https
|
||||||
|
|
||||||
|
|||||||
@@ -22,18 +22,25 @@ source /etc/mailinabox.conf # load global vars
|
|||||||
echo "Installing Roundcube (webmail)..."
|
echo "Installing Roundcube (webmail)..."
|
||||||
apt_install \
|
apt_install \
|
||||||
dbconfig-common \
|
dbconfig-common \
|
||||||
php-cli php-sqlite3 php-intl php-json php-common php-curl \
|
php-cli php-sqlite3 php-intl php-json php-common php-curl php-ldap \
|
||||||
php-gd php-pspell tinymce libjs-jquery libjs-jquery-mousewheel libmagic1 php-mbstring
|
php-gd php-pspell tinymce libjs-jquery libjs-jquery-mousewheel libmagic1 php-mbstring
|
||||||
|
|
||||||
# Install Roundcube from source if it is not already present or if it is out of date.
|
# Install Roundcube from source if it is not already present or if it is out of date.
|
||||||
# Combine the Roundcube version number with the commit hash of plugins to track
|
# Combine the Roundcube version number with the commit hash of plugins to track
|
||||||
# whether we have the latest version of everything.
|
# whether we have the latest version of everything.
|
||||||
VERSION=1.3.9
|
# For the latest versions, see:
|
||||||
HASH=02850972b416bbfa1c13580f16d06fd7ae2774aa
|
# https://github.com/roundcube/roundcubemail/releases
|
||||||
PERSISTENT_LOGIN_VERSION=dc5ca3d3f4415cc41edb2fde533c8a8628a94c76
|
# https://github.com/mfreiholz/persistent_login/commits/master
|
||||||
HTML5_NOTIFIER_VERSION=4b370e3cd60dabd2f428a26f45b677ad1b7118d5
|
# https://github.com/stremlau/html5_notifier/commits/master
|
||||||
CARDDAV_VERSION=3.0.3
|
# https://github.com/mstilkerich/rcmcarddav/releases
|
||||||
CARDDAV_HASH=d1e3b0d851ffa2c6bd42bf0c04f70d0e1d0d78f8
|
# The easiest way to get the package hashes is to run this script and get the hash from
|
||||||
|
# the error message.
|
||||||
|
VERSION=1.5.2
|
||||||
|
HASH=208ce4ca0be423cc0f7070ff59bd03588b4439bf
|
||||||
|
PERSISTENT_LOGIN_VERSION=59ca1b0d3a02cff5fa621c1ad581d15f9d642fe8
|
||||||
|
HTML5_NOTIFIER_VERSION=68d9ca194212e15b3c7225eb6085dbcf02fd13d7 # version 0.6.4+
|
||||||
|
CARDDAV_VERSION=4.3.0
|
||||||
|
CARDDAV_HASH=4ad7df8843951062878b1375f77c614f68bc5c61
|
||||||
|
|
||||||
UPDATE_KEY=$VERSION:$PERSISTENT_LOGIN_VERSION:$HTML5_NOTIFIER_VERSION:$CARDDAV_VERSION
|
UPDATE_KEY=$VERSION:$PERSISTENT_LOGIN_VERSION:$HTML5_NOTIFIER_VERSION:$CARDDAV_VERSION
|
||||||
|
|
||||||
@@ -46,11 +53,18 @@ needs_update=0 #NODOC
|
|||||||
if [ ! -f /usr/local/lib/roundcubemail/version ]; then
|
if [ ! -f /usr/local/lib/roundcubemail/version ]; then
|
||||||
# not installed yet #NODOC
|
# not installed yet #NODOC
|
||||||
needs_update=1 #NODOC
|
needs_update=1 #NODOC
|
||||||
elif [[ "$UPDATE_KEY" != `cat /usr/local/lib/roundcubemail/version` ]]; then
|
elif [[ "$UPDATE_KEY" != $(cat /usr/local/lib/roundcubemail/version) ]]; then
|
||||||
# checks if the version is what we want
|
# checks if the version is what we want
|
||||||
needs_update=1 #NODOC
|
needs_update=1 #NODOC
|
||||||
fi
|
fi
|
||||||
if [ $needs_update == 1 ]; then
|
if [ $needs_update == 1 ]; then
|
||||||
|
# if upgrading from 1.3.x, clear the temp_dir
|
||||||
|
if [ -f /usr/local/lib/roundcubemail/version ]; then
|
||||||
|
if [ "$(cat /usr/local/lib/roundcubemail/version | cut -c1-3)" == '1.3' ]; then
|
||||||
|
find /var/tmp/roundcubemail/ -type f ! -name 'RCMTEMP*' -delete
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
# install roundcube
|
# install roundcube
|
||||||
wget_verify \
|
wget_verify \
|
||||||
https://github.com/roundcube/roundcubemail/releases/download/$VERSION/roundcubemail-$VERSION-complete.tar.gz \
|
https://github.com/roundcube/roundcubemail/releases/download/$VERSION/roundcubemail-$VERSION-complete.tar.gz \
|
||||||
@@ -69,13 +83,13 @@ if [ $needs_update == 1 ]; then
|
|||||||
|
|
||||||
# download and verify the full release of the carddav plugin
|
# download and verify the full release of the carddav plugin
|
||||||
wget_verify \
|
wget_verify \
|
||||||
https://github.com/blind-coder/rcmcarddav/releases/download/v${CARDDAV_VERSION}/carddav-${CARDDAV_VERSION}.zip \
|
https://github.com/blind-coder/rcmcarddav/releases/download/v${CARDDAV_VERSION}/carddav-v${CARDDAV_VERSION}.tar.gz \
|
||||||
$CARDDAV_HASH \
|
$CARDDAV_HASH \
|
||||||
/tmp/carddav.zip
|
/tmp/carddav.tar.gz
|
||||||
|
|
||||||
# unzip and cleanup
|
# unzip and cleanup
|
||||||
unzip -q /tmp/carddav.zip -d ${RCM_PLUGIN_DIR}
|
tar -C ${RCM_PLUGIN_DIR} -zxf /tmp/carddav.tar.gz
|
||||||
rm -f /tmp/carddav.zip
|
rm -f /tmp/carddav.tar.gz
|
||||||
|
|
||||||
# record the version we've installed
|
# record the version we've installed
|
||||||
echo $UPDATE_KEY > ${RCM_DIR}/version
|
echo $UPDATE_KEY > ${RCM_DIR}/version
|
||||||
@@ -83,8 +97,9 @@ fi
|
|||||||
|
|
||||||
# ### Configuring Roundcube
|
# ### Configuring Roundcube
|
||||||
|
|
||||||
# Generate a safe 24-character secret key of safe characters.
|
# Generate a secret key of PHP-string-safe characters appropriate
|
||||||
SECRET_KEY=$(dd if=/dev/urandom bs=1 count=18 2>/dev/null | base64 | fold -w 24 | head -n 1)
|
# for the cipher algorithm selected below.
|
||||||
|
SECRET_KEY=$(dd if=/dev/urandom bs=1 count=32 2>/dev/null | base64 | sed s/=//g)
|
||||||
|
|
||||||
# Create a configuration file.
|
# Create a configuration file.
|
||||||
#
|
#
|
||||||
@@ -110,9 +125,6 @@ cat > $RCM_CONFIG <<EOF;
|
|||||||
);
|
);
|
||||||
\$config['imap_timeout'] = 15;
|
\$config['imap_timeout'] = 15;
|
||||||
\$config['smtp_server'] = 'tls://127.0.0.1';
|
\$config['smtp_server'] = 'tls://127.0.0.1';
|
||||||
\$config['smtp_port'] = 587;
|
|
||||||
\$config['smtp_user'] = '%u';
|
|
||||||
\$config['smtp_pass'] = '%p';
|
|
||||||
\$config['smtp_conn_options'] = array(
|
\$config['smtp_conn_options'] = array(
|
||||||
'ssl' => array(
|
'ssl' => array(
|
||||||
'verify_peer' => false,
|
'verify_peer' => false,
|
||||||
@@ -121,10 +133,12 @@ cat > $RCM_CONFIG <<EOF;
|
|||||||
);
|
);
|
||||||
\$config['support_url'] = 'https://mailinabox.email/';
|
\$config['support_url'] = 'https://mailinabox.email/';
|
||||||
\$config['product_name'] = '$PRIMARY_HOSTNAME Webmail';
|
\$config['product_name'] = '$PRIMARY_HOSTNAME Webmail';
|
||||||
\$config['des_key'] = '$SECRET_KEY';
|
\$config['cipher_method'] = 'AES-256-CBC'; # persistent login cookie and potentially other things
|
||||||
|
\$config['des_key'] = '$SECRET_KEY'; # 37 characters -> ~256 bits for AES-256, see above
|
||||||
\$config['plugins'] = array('html5_notifier', 'archive', 'zipdownload', 'password', 'managesieve', 'jqueryui', 'persistent_login', 'carddav');
|
\$config['plugins'] = array('html5_notifier', 'archive', 'zipdownload', 'password', 'managesieve', 'jqueryui', 'persistent_login', 'carddav');
|
||||||
\$config['skin'] = 'larry';
|
\$config['skin'] = 'elastic';
|
||||||
\$config['login_autocomplete'] = 2;
|
\$config['login_autocomplete'] = 2;
|
||||||
|
\$config['login_username_filter'] = 'email';
|
||||||
\$config['password_charset'] = 'UTF-8';
|
\$config['password_charset'] = 'UTF-8';
|
||||||
\$config['junk_mbox'] = 'Spam';
|
\$config['junk_mbox'] = 'Spam';
|
||||||
?>
|
?>
|
||||||
@@ -156,7 +170,7 @@ mkdir -p /var/log/roundcubemail /var/tmp/roundcubemail $STORAGE_ROOT/mail/roundc
|
|||||||
chown -R www-data.www-data /var/log/roundcubemail /var/tmp/roundcubemail $STORAGE_ROOT/mail/roundcube
|
chown -R www-data.www-data /var/log/roundcubemail /var/tmp/roundcubemail $STORAGE_ROOT/mail/roundcube
|
||||||
|
|
||||||
# Ensure the log file monitored by fail2ban exists, or else fail2ban can't start.
|
# Ensure the log file monitored by fail2ban exists, or else fail2ban can't start.
|
||||||
sudo -u www-data touch /var/log/roundcubemail/errors
|
sudo -u www-data touch /var/log/roundcubemail/errors.log
|
||||||
|
|
||||||
# Password changing plugin settings
|
# Password changing plugin settings
|
||||||
# The config comes empty by default, so we need the settings
|
# The config comes empty by default, so we need the settings
|
||||||
|
|||||||
@@ -22,23 +22,23 @@ apt_install \
|
|||||||
phpenmod -v php imap
|
phpenmod -v php imap
|
||||||
|
|
||||||
# Copy Z-Push into place.
|
# Copy Z-Push into place.
|
||||||
VERSION=2.5.0
|
VERSION=2.6.2
|
||||||
TARGETHASH=30ce5c1af3f10939036361b6032d1187651b621e
|
TARGETHASH=f0e8091a8030e5b851f5ba1f9f0e1a05b8762d80
|
||||||
needs_update=0 #NODOC
|
needs_update=0 #NODOC
|
||||||
if [ ! -f /usr/local/lib/z-push/version ]; then
|
if [ ! -f /usr/local/lib/z-push/version ]; then
|
||||||
needs_update=1 #NODOC
|
needs_update=1 #NODOC
|
||||||
elif [[ $VERSION != `cat /usr/local/lib/z-push/version` ]]; then
|
elif [[ $VERSION != $(cat /usr/local/lib/z-push/version) ]]; then
|
||||||
# checks if the version
|
# checks if the version
|
||||||
needs_update=1 #NODOC
|
needs_update=1 #NODOC
|
||||||
fi
|
fi
|
||||||
if [ $needs_update == 1 ]; then
|
if [ $needs_update == 1 ]; then
|
||||||
# Download
|
# Download
|
||||||
wget_verify "https://stash.z-hub.io/rest/api/latest/projects/ZP/repos/z-push/archive?at=refs%2Ftags%2F$VERSION&format=zip" $TARGETHASH /tmp/z-push.zip
|
wget_verify "https://github.com/Z-Hub/Z-Push/archive/refs/tags/$VERSION.zip" $TARGETHASH /tmp/z-push.zip
|
||||||
|
|
||||||
# Extract into place.
|
# Extract into place.
|
||||||
rm -rf /usr/local/lib/z-push /tmp/z-push
|
rm -rf /usr/local/lib/z-push /tmp/z-push
|
||||||
unzip -q /tmp/z-push.zip -d /tmp/z-push
|
unzip -q /tmp/z-push.zip -d /tmp/z-push
|
||||||
mv /tmp/z-push/src /usr/local/lib/z-push
|
mv /tmp/z-push/*/src /usr/local/lib/z-push
|
||||||
rm -rf /tmp/z-push.zip /tmp/z-push
|
rm -rf /tmp/z-push.zip /tmp/z-push
|
||||||
|
|
||||||
rm -f /usr/sbin/z-push-{admin,top}
|
rm -f /usr/sbin/z-push-{admin,top}
|
||||||
|
|||||||
@@ -90,6 +90,26 @@ def pop_test():
|
|||||||
if M:
|
if M:
|
||||||
M.quit()
|
M.quit()
|
||||||
|
|
||||||
|
def managesieve_test():
|
||||||
|
# We don't have a Python sieve client, so we'll
|
||||||
|
# just run the IMAP client and see what happens.
|
||||||
|
import imaplib
|
||||||
|
|
||||||
|
try:
|
||||||
|
M = imaplib.IMAP4(hostname, 4190)
|
||||||
|
except ConnectionRefusedError:
|
||||||
|
# looks like fail2ban worked
|
||||||
|
raise IsBlocked()
|
||||||
|
|
||||||
|
try:
|
||||||
|
M.login("fakeuser", "fakepassword")
|
||||||
|
raise Exception("authentication didn't fail")
|
||||||
|
except imaplib.IMAP4.error:
|
||||||
|
# authentication should fail
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
M.logout() # shuts down connection, has nothing to do with login()
|
||||||
|
|
||||||
def http_test(url, expected_status, postdata=None, qsargs=None, auth=None):
|
def http_test(url, expected_status, postdata=None, qsargs=None, auth=None):
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
import requests
|
import requests
|
||||||
@@ -208,8 +228,11 @@ if __name__ == "__main__":
|
|||||||
# POP
|
# POP
|
||||||
run_test(pop_test, [], 20, 30, 4)
|
run_test(pop_test, [], 20, 30, 4)
|
||||||
|
|
||||||
|
# Managesieve
|
||||||
|
run_test(managesieve_test, [], 20, 30, 4)
|
||||||
|
|
||||||
# Mail-in-a-Box control panel
|
# Mail-in-a-Box control panel
|
||||||
run_test(http_test, ["/admin/me", 200], 20, 30, 1)
|
run_test(http_test, ["/admin/login", 200], 20, 30, 1)
|
||||||
|
|
||||||
# Munin via the Mail-in-a-Box control panel
|
# Munin via the Mail-in-a-Box control panel
|
||||||
run_test(http_test, ["/admin/munin/", 401], 20, 30, 1)
|
run_test(http_test, ["/admin/munin/", 401], 20, 30, 1)
|
||||||
|
|||||||
@@ -41,9 +41,8 @@ This is a test message. It should be automatically deleted by the test script.""
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Connect to the server on the SMTP submission TLS port.
|
# Connect to the server on the SMTP submission TLS port.
|
||||||
server = smtplib.SMTP(host, 587)
|
server = smtplib.SMTP_SSL(host)
|
||||||
#server.set_debuglevel(1)
|
#server.set_debuglevel(1)
|
||||||
server.starttls()
|
|
||||||
|
|
||||||
# Verify that the EHLO name matches the server's reverse DNS.
|
# Verify that the EHLO name matches the server's reverse DNS.
|
||||||
ipaddr = socket.gethostbyname(host) # IPv4 only!
|
ipaddr = socket.gethostbyname(host) # IPv4 only!
|
||||||
|
|||||||
134
tools/mail.py
134
tools/mail.py
@@ -1,131 +1,3 @@
|
|||||||
#!/usr/bin/python3
|
#!/bin/bash
|
||||||
|
# This script has moved.
|
||||||
import sys, getpass, urllib.request, urllib.error, json, re
|
management/cli.py "$@"
|
||||||
|
|
||||||
def mgmt(cmd, data=None, is_json=False):
|
|
||||||
# The base URL for the management daemon. (Listens on IPv4 only.)
|
|
||||||
mgmt_uri = 'http://127.0.0.1:10222'
|
|
||||||
|
|
||||||
setup_key_auth(mgmt_uri)
|
|
||||||
|
|
||||||
req = urllib.request.Request(mgmt_uri + cmd, urllib.parse.urlencode(data).encode("utf8") if data else None)
|
|
||||||
try:
|
|
||||||
response = urllib.request.urlopen(req)
|
|
||||||
except urllib.error.HTTPError as e:
|
|
||||||
if e.code == 401:
|
|
||||||
try:
|
|
||||||
print(e.read().decode("utf8"))
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
print("The management daemon refused access. The API key file may be out of sync. Try 'service mailinabox restart'.", file=sys.stderr)
|
|
||||||
elif hasattr(e, 'read'):
|
|
||||||
print(e.read().decode('utf8'), file=sys.stderr)
|
|
||||||
else:
|
|
||||||
print(e, file=sys.stderr)
|
|
||||||
sys.exit(1)
|
|
||||||
resp = response.read().decode('utf8')
|
|
||||||
if is_json: resp = json.loads(resp)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def read_password():
|
|
||||||
while True:
|
|
||||||
first = getpass.getpass('password: ')
|
|
||||||
if len(first) < 8:
|
|
||||||
print("Passwords must be at least eight characters.")
|
|
||||||
continue
|
|
||||||
if re.search(r'[\s]', first):
|
|
||||||
print("Passwords cannot contain spaces.")
|
|
||||||
continue
|
|
||||||
second = getpass.getpass(' (again): ')
|
|
||||||
if first != second:
|
|
||||||
print("Passwords not the same. Try again.")
|
|
||||||
continue
|
|
||||||
break
|
|
||||||
return first
|
|
||||||
|
|
||||||
def setup_key_auth(mgmt_uri):
|
|
||||||
key = open('/var/lib/mailinabox/api.key').read().strip()
|
|
||||||
|
|
||||||
auth_handler = urllib.request.HTTPBasicAuthHandler()
|
|
||||||
auth_handler.add_password(
|
|
||||||
realm='Mail-in-a-Box Management Server',
|
|
||||||
uri=mgmt_uri,
|
|
||||||
user=key,
|
|
||||||
passwd='')
|
|
||||||
opener = urllib.request.build_opener(auth_handler)
|
|
||||||
urllib.request.install_opener(opener)
|
|
||||||
|
|
||||||
if len(sys.argv) < 2:
|
|
||||||
print("Usage: ")
|
|
||||||
print(" tools/mail.py user (lists users)")
|
|
||||||
print(" tools/mail.py user add user@domain.com [password]")
|
|
||||||
print(" tools/mail.py user password user@domain.com [password]")
|
|
||||||
print(" tools/mail.py user remove user@domain.com")
|
|
||||||
print(" tools/mail.py user make-admin user@domain.com")
|
|
||||||
print(" tools/mail.py user remove-admin user@domain.com")
|
|
||||||
print(" tools/mail.py user admins (lists admins)")
|
|
||||||
print(" tools/mail.py alias (lists aliases)")
|
|
||||||
print(" tools/mail.py alias add incoming.name@domain.com sent.to@other.domain.com")
|
|
||||||
print(" tools/mail.py alias add incoming.name@domain.com 'sent.to@other.domain.com, multiple.people@other.domain.com'")
|
|
||||||
print(" tools/mail.py alias remove incoming.name@domain.com")
|
|
||||||
print()
|
|
||||||
print("Removing a mail user does not delete their mail folders on disk. It only prevents IMAP/SMTP login.")
|
|
||||||
print()
|
|
||||||
|
|
||||||
elif sys.argv[1] == "user" and len(sys.argv) == 2:
|
|
||||||
# Dump a list of users, one per line. Mark admins with an asterisk.
|
|
||||||
users = mgmt("/mail/users?format=json", is_json=True)
|
|
||||||
for domain in users:
|
|
||||||
for user in domain["users"]:
|
|
||||||
if user['status'] == 'inactive': continue
|
|
||||||
print(user['email'], end='')
|
|
||||||
if "admin" in user['privileges']:
|
|
||||||
print("*", end='')
|
|
||||||
print()
|
|
||||||
|
|
||||||
elif sys.argv[1] == "user" and sys.argv[2] in ("add", "password"):
|
|
||||||
if len(sys.argv) < 5:
|
|
||||||
if len(sys.argv) < 4:
|
|
||||||
email = input("email: ")
|
|
||||||
else:
|
|
||||||
email = sys.argv[3]
|
|
||||||
pw = read_password()
|
|
||||||
else:
|
|
||||||
email, pw = sys.argv[3:5]
|
|
||||||
|
|
||||||
if sys.argv[2] == "add":
|
|
||||||
print(mgmt("/mail/users/add", { "email": email, "password": pw }))
|
|
||||||
elif sys.argv[2] == "password":
|
|
||||||
print(mgmt("/mail/users/password", { "email": email, "password": pw }))
|
|
||||||
|
|
||||||
elif sys.argv[1] == "user" and sys.argv[2] == "remove" and len(sys.argv) == 4:
|
|
||||||
print(mgmt("/mail/users/remove", { "email": sys.argv[3] }))
|
|
||||||
|
|
||||||
elif sys.argv[1] == "user" and sys.argv[2] in ("make-admin", "remove-admin") and len(sys.argv) == 4:
|
|
||||||
if sys.argv[2] == "make-admin":
|
|
||||||
action = "add"
|
|
||||||
else:
|
|
||||||
action = "remove"
|
|
||||||
print(mgmt("/mail/users/privileges/" + action, { "email": sys.argv[3], "privilege": "admin" }))
|
|
||||||
|
|
||||||
elif sys.argv[1] == "user" and sys.argv[2] == "admins":
|
|
||||||
# Dump a list of admin users.
|
|
||||||
users = mgmt("/mail/users?format=json", is_json=True)
|
|
||||||
for domain in users:
|
|
||||||
for user in domain["users"]:
|
|
||||||
if "admin" in user['privileges']:
|
|
||||||
print(user['email'])
|
|
||||||
|
|
||||||
elif sys.argv[1] == "alias" and len(sys.argv) == 2:
|
|
||||||
print(mgmt("/mail/aliases"))
|
|
||||||
|
|
||||||
elif sys.argv[1] == "alias" and sys.argv[2] == "add" and len(sys.argv) == 5:
|
|
||||||
print(mgmt("/mail/aliases/add", { "address": sys.argv[3], "forwards_to": sys.argv[4] }))
|
|
||||||
|
|
||||||
elif sys.argv[1] == "alias" and sys.argv[2] == "remove" and len(sys.argv) == 4:
|
|
||||||
print(mgmt("/mail/aliases/remove", { "address": sys.argv[3] }))
|
|
||||||
|
|
||||||
else:
|
|
||||||
print("Invalid command-line arguments.")
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ fi
|
|||||||
|
|
||||||
if [ ! -f $1/config.php ]; then
|
if [ ! -f $1/config.php ]; then
|
||||||
echo "This isn't a valid backup location"
|
echo "This isn't a valid backup location"
|
||||||
exit
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "Restoring backup from $1"
|
echo "Restoring backup from $1"
|
||||||
|
|||||||
@@ -261,6 +261,10 @@ class UfwAllow(Grammar):
|
|||||||
grammar = (ZERO_OR_MORE(SPACE), L("ufw_allow "), REST_OF_LINE, EOL)
|
grammar = (ZERO_OR_MORE(SPACE), L("ufw_allow "), REST_OF_LINE, EOL)
|
||||||
def value(self):
|
def value(self):
|
||||||
return shell_line("ufw allow " + self[2].string)
|
return shell_line("ufw allow " + self[2].string)
|
||||||
|
class UfwLimit(Grammar):
|
||||||
|
grammar = (ZERO_OR_MORE(SPACE), L("ufw_limit "), REST_OF_LINE, EOL)
|
||||||
|
def value(self):
|
||||||
|
return shell_line("ufw limit " + self[2].string)
|
||||||
class RestartService(Grammar):
|
class RestartService(Grammar):
|
||||||
grammar = (ZERO_OR_MORE(SPACE), L("restart_service "), REST_OF_LINE, EOL)
|
grammar = (ZERO_OR_MORE(SPACE), L("restart_service "), REST_OF_LINE, EOL)
|
||||||
def value(self):
|
def value(self):
|
||||||
@@ -275,7 +279,7 @@ class OtherLine(Grammar):
|
|||||||
return "<pre class='shell'><div>" + recode_bash(self.string.strip()) + "</div></pre>\n"
|
return "<pre class='shell'><div>" + recode_bash(self.string.strip()) + "</div></pre>\n"
|
||||||
|
|
||||||
class BashElement(Grammar):
|
class BashElement(Grammar):
|
||||||
grammar = Comment | CatEOF | EchoPipe | EchoLine | HideOutput | EditConf | SedReplace | AptGet | UfwAllow | RestartService | OtherLine
|
grammar = Comment | CatEOF | EchoPipe | EchoLine | HideOutput | EditConf | SedReplace | AptGet | UfwAllow | UfwLimit | RestartService | OtherLine
|
||||||
def value(self):
|
def value(self):
|
||||||
return self[0].value()
|
return self[0].value()
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user