mirror of
https://github.com/mail-in-a-box/mailinabox.git
synced 2026-03-13 17:17:23 +01:00
Compare commits
975 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
39fd4ce16c | ||
|
|
c0f4d5479f | ||
|
|
193763f8f0 | ||
|
|
79759ea5a3 | ||
|
|
6e5ceab0f8 | ||
|
|
c6fa0d23df | ||
|
|
85e59245fd | ||
|
|
4232a1205c | ||
|
|
0d4c693792 | ||
|
|
77b2246010 | ||
|
|
aff80ac58c | ||
|
|
25fec63a03 | ||
|
|
9b46637aff | ||
|
|
fb25013334 | ||
|
|
dd7a2aa8a6 | ||
|
|
149552f79b | ||
|
|
adddd95e38 | ||
|
|
bad38840d8 | ||
|
|
10050aa601 | ||
|
|
c60e3dc842 | ||
|
|
c7659d9053 | ||
|
|
cd3fb1b487 | ||
|
|
29e77d25fc | ||
|
|
e56c55efe8 | ||
|
|
8e0d9b9f21 | ||
|
|
6e60b47cb5 | ||
|
|
a3add03706 | ||
|
|
7b592b1e99 | ||
|
|
a67aa4cfd4 | ||
|
|
31b743b164 | ||
|
|
71f1c92b9e | ||
|
|
e80a1dd4b7 | ||
|
|
b7e9a90005 | ||
|
|
0d4565e71d | ||
|
|
703a9376ef | ||
|
|
b3b798adf2 | ||
|
|
bd54b41041 | ||
|
|
a211ad422b | ||
|
|
ef28a1defd | ||
|
|
c5c413b447 | ||
|
|
d2beb3919b | ||
|
|
a7dded8182 | ||
|
|
000363492e | ||
|
|
5be74dec6e | ||
|
|
9ddca42c91 | ||
|
|
ff6d8fc672 | ||
|
|
870b82637a | ||
|
|
dc6458623d | ||
|
|
60f9c9e3b7 | ||
|
|
e5e0c64395 | ||
|
|
aa52f52d02 | ||
|
|
b05b06c74a | ||
|
|
7f8f4518e3 | ||
|
|
86e2cfb6c8 | ||
|
|
0335595e7e | ||
|
|
8d5670068a | ||
|
|
c9b3d88108 | ||
|
|
16f38042ec | ||
|
|
2f494e9a1c | ||
|
|
f739662392 | ||
|
|
6eb9055275 | ||
|
|
3dbd6c994a | ||
|
|
bc4bdca752 | ||
|
|
bbfa01f33a | ||
|
|
f6a641ad23 | ||
|
|
51972fd129 | ||
|
|
bb43a2127c | ||
|
|
d96613b8fe | ||
|
|
504a9b0abc | ||
|
|
842fbb3d72 | ||
|
|
a5d5a073c7 | ||
|
|
d4b122ee94 | ||
|
|
052a1f3b26 | ||
|
|
180b054dbc | ||
|
|
cb162da5fe | ||
|
|
de9c556ad7 | ||
|
|
f420294819 | ||
|
|
738e0a6e17 | ||
|
|
e0d46d1eb5 | ||
|
|
7f37abca05 | ||
|
|
2f467556bd | ||
|
|
15583ec10d | ||
|
|
78d1c9be6e | ||
|
|
b0b5d8e792 | ||
|
|
82844ca651 | ||
|
|
2a72c800f6 | ||
|
|
8be23d5ef6 | ||
|
|
f9a0e39cc9 | ||
|
|
0c0a079354 | ||
|
|
42e86610ba | ||
|
|
7c62f4b8e9 | ||
|
|
1eba7b0616 | ||
|
|
9c7820f422 | ||
|
|
87ec4e9f82 | ||
|
|
08becf7fa3 | ||
|
|
5eb4a53de1 | ||
|
|
598ade3f7a | ||
|
|
8f399df5bb | ||
|
|
ae73dc5d30 | ||
|
|
c409b2efd0 | ||
|
|
6961840c0e | ||
|
|
6162a9637c | ||
|
|
47c968e71b | ||
|
|
ed3e2aa712 | ||
|
|
fe597da7aa | ||
|
|
61e9888a85 | ||
|
|
35fed8606e | ||
|
|
ef6f121491 | ||
|
|
ec3aab0eaa | ||
|
|
8c69b9e261 | ||
|
|
e7150e3bc6 | ||
|
|
8d6d84d87f | ||
|
|
a6a1cc7ae0 | ||
|
|
b5c0736d27 | ||
|
|
8ee7de6ff3 | ||
|
|
0088fb4553 | ||
|
|
b2d103145f | ||
|
|
fc9e279cec | ||
|
|
257983d559 | ||
|
|
e924459140 | ||
|
|
441bd35053 | ||
|
|
a0e603a3c6 | ||
|
|
88604074d6 | ||
|
|
d43111eb48 | ||
|
|
6729588d8c | ||
|
|
5f14eca67f | ||
|
|
8944cd7980 | ||
|
|
2bbbc9dfa3 | ||
|
|
544f155948 | ||
|
|
f080eabb3a | ||
|
|
7bf377eed1 | ||
|
|
cd554cf480 | ||
|
|
e5448405ae | ||
|
|
a7eff8fb35 | ||
|
|
341aa8695a | ||
|
|
5efdd72f41 | ||
|
|
f25801e88d | ||
|
|
cc7be13098 | ||
|
|
2556e3fbc2 | ||
|
|
00898b2ff5 | ||
|
|
35b8a149d8 | ||
|
|
d0423afd18 | ||
|
|
edf42df835 | ||
|
|
734745a4a6 | ||
|
|
dbebaba8b9 | ||
|
|
cb765dfe2a | ||
|
|
81258e2189 | ||
|
|
4dd4b4232a | ||
|
|
48ff664ee9 | ||
|
|
a52c56e571 | ||
|
|
6ace97e482 | ||
|
|
19a928e4ec | ||
|
|
78f2fe213e | ||
|
|
a16855ecf0 | ||
|
|
d773140502 | ||
|
|
2c324d0bc9 | ||
|
|
2bd6cc4d6b | ||
|
|
b11157e0b6 | ||
|
|
46ba62b7b1 | ||
|
|
4c36d6e6c9 | ||
|
|
e49c99890b | ||
|
|
a13fd90347 | ||
|
|
18f1689f45 | ||
|
|
8234a5a9f4 | ||
|
|
1d9f9ea617 | ||
|
|
fbb38c3881 | ||
|
|
2caddb41eb | ||
|
|
d2b7204319 | ||
|
|
68ebca8a15 | ||
|
|
9c9dcdbf0a | ||
|
|
0c4c2e51bb | ||
|
|
828512b95a | ||
|
|
add985ce5d | ||
|
|
416dbebf45 | ||
|
|
2a046a22f4 | ||
|
|
b66f12dd4c | ||
|
|
6e04eb490f | ||
|
|
cd39c2b53f | ||
|
|
5da168466d | ||
|
|
a5f39784dd | ||
|
|
a072730fb8 | ||
|
|
00c61dbcdd | ||
|
|
10bf40250b | ||
|
|
453091f1fb | ||
|
|
48e0f39179 | ||
|
|
bb641cdfba | ||
|
|
255a65ac98 | ||
|
|
c7badb80d1 | ||
|
|
653cb7ce10 | ||
|
|
d7d8964afc | ||
|
|
6c3696a54a | ||
|
|
9c9cae2096 | ||
|
|
423f1907d0 | ||
|
|
86621392f6 | ||
|
|
368b9c50d0 | ||
|
|
3830facf78 | ||
|
|
d4baac2363 | ||
|
|
f88c907a29 | ||
|
|
89222d519a | ||
|
|
36bef2ee16 | ||
|
|
f6b20a810f | ||
|
|
f2ff14100e | ||
|
|
2c86fa3755 | ||
|
|
3c05fc94ff | ||
|
|
2e00530944 | ||
|
|
32d6728dc9 | ||
|
|
a3c71fe14f | ||
|
|
a24977a96e | ||
|
|
e694f57673 | ||
|
|
cd59de6314 | ||
|
|
a081d04082 | ||
|
|
09577816f8 | ||
|
|
2647febbf5 | ||
|
|
bd0635728c | ||
|
|
584cfe42c4 | ||
|
|
41601a592f | ||
|
|
18c253eeda | ||
|
|
34d58fb720 | ||
|
|
99d0afd650 | ||
|
|
cd717ec94e | ||
|
|
0b7f477b96 | ||
|
|
ab2367e98a | ||
|
|
384c3b5e3d | ||
|
|
d91368c478 | ||
|
|
61105b1ec3 | ||
|
|
b6f90e10c1 | ||
|
|
3af5e55035 | ||
|
|
e03b071e8b | ||
|
|
df93d82d0f | ||
|
|
59913a5e4c | ||
|
|
c3605f6211 | ||
|
|
96b3a29800 | ||
|
|
abb6a1a070 | ||
|
|
041b5f883f | ||
|
|
3b78a8d9d6 | ||
|
|
6ea1a06a12 | ||
|
|
2b00478b8b | ||
|
|
155bcfc654 | ||
|
|
4b07a6aa8f | ||
|
|
2151d81453 | ||
|
|
fd6226187a | ||
|
|
bbe27df413 | ||
|
|
a658abc95f | ||
|
|
9331dbc519 | ||
|
|
8b5eba21c0 | ||
|
|
da5497cd1c | ||
|
|
a27ec68467 | ||
|
|
3ac4b8aca8 | ||
|
|
02feeafe6a | ||
|
|
5f0376bfbf | ||
|
|
4e4fe90fc7 | ||
|
|
3cd5a6eee7 | ||
|
|
c26bc841a2 | ||
|
|
163daea41c | ||
|
|
d8316119eb | ||
|
|
102b2d46ab | ||
|
|
58541c467f | ||
|
|
00bd23eb04 | ||
|
|
d73d1c6900 | ||
|
|
fc0abd5b4d | ||
|
|
27b4edfc76 | ||
|
|
ba75ff7820 | ||
|
|
a14b17794b | ||
|
|
35a360ef0b | ||
|
|
86457e5bc4 | ||
|
|
7c9f3e0b23 | ||
|
|
83d8dbca3e | ||
|
|
8cf2e468bd | ||
|
|
440a545010 | ||
|
|
942bcfc7c5 | ||
|
|
4f2d16a31d | ||
|
|
e9368de462 | ||
|
|
cdd0a821eb | ||
|
|
6f165d0aeb | ||
|
|
6c22c0533e | ||
|
|
d38b732b0a | ||
|
|
81b5af6b64 | ||
|
|
fc5cc9753b | ||
|
|
1aca6fe08f | ||
|
|
cf3e1cd595 | ||
|
|
b044dda28f | ||
|
|
f66f39b61d | ||
|
|
6de7d59f14 | ||
|
|
9c8f2e75fc | ||
|
|
cbc4bf553d | ||
|
|
4e3cfead46 | ||
|
|
8844a9185f | ||
|
|
3249a55f3a | ||
|
|
b58fb54725 | ||
|
|
82903cd09e | ||
|
|
fb14e30feb | ||
|
|
d9ac321f25 | ||
|
|
bf5e9200f8 | ||
|
|
5f5f00af4a | ||
|
|
6b73bb5d80 | ||
|
|
3055f9a79c | ||
|
|
1c84e0aeb6 | ||
|
|
ae1b56d23f | ||
|
|
946cd63e8e | ||
|
|
01fa8cf72c | ||
|
|
fac8477ba1 | ||
|
|
61744095a8 | ||
|
|
d5b38a27e6 | ||
|
|
6666d28c44 | ||
|
|
66675ff2e9 | ||
|
|
9ee2d946b7 | ||
|
|
ff7d4196a6 | ||
|
|
490b36d86c | ||
|
|
867d9c4669 | ||
|
|
1ad5892acd | ||
|
|
94b7c80792 | ||
|
|
69bd137b4e | ||
|
|
ae8cd4efdf | ||
|
|
6d259a6e12 | ||
|
|
e7fffc66c7 | ||
|
|
8548ede638 | ||
|
|
6eeb107ee3 | ||
|
|
31eefa18da | ||
|
|
20adbb51cb | ||
|
|
79a39d86f9 | ||
|
|
0ebf33e9df | ||
|
|
d3818d1db6 | ||
|
|
f65d9d3196 | ||
|
|
74fea6b93e | ||
|
|
7a935d8385 | ||
|
|
7e0f534aea | ||
|
|
736b3de221 | ||
|
|
5628f8eecb | ||
|
|
9cc5160c38 | ||
|
|
42f2e983e5 | ||
|
|
bc40134b7b | ||
|
|
3649ba1ce9 | ||
|
|
22395bdb8b | ||
|
|
30c89be982 | ||
|
|
853b641d1b | ||
|
|
703a963ae5 | ||
|
|
c9f30e8059 | ||
|
|
1a1d125b31 | ||
|
|
86881c0107 | ||
|
|
e65c77588e | ||
|
|
3843f63416 | ||
|
|
703e6795e8 | ||
|
|
b3223136f4 | ||
|
|
aa1fdaddaf | ||
|
|
7fa9baf308 | ||
|
|
36d51bbde0 | ||
|
|
eb8cfaab75 | ||
|
|
c5e8a975cd | ||
|
|
3210ccdcac | ||
|
|
252c35c66e | ||
|
|
c910a58f07 | ||
|
|
f292e8fc5b | ||
|
|
4d7229ccb0 | ||
|
|
1e1c3cbd00 | ||
|
|
611e9cc84d | ||
|
|
454a2b167b | ||
|
|
f6e0af124f | ||
|
|
d7d8bda0a4 | ||
|
|
df92a10eba | ||
|
|
74a0359cec | ||
|
|
336b95b3d5 | ||
|
|
56591abbc2 | ||
|
|
313a86d0fa | ||
|
|
083e3cf755 | ||
|
|
696bbe4e82 | ||
|
|
3d4cabbcd5 | ||
|
|
cdedaed3b0 | ||
|
|
c01f903413 | ||
|
|
5edefbec27 | ||
|
|
67555679bd | ||
|
|
546d6f0026 | ||
|
|
bd86d44c8b | ||
|
|
72fcb005b2 | ||
|
|
84638ab11e | ||
|
|
84f4509b48 | ||
|
|
35a593af13 | ||
|
|
f69d6e9015 | ||
|
|
44705a32b7 | ||
|
|
e343061cf4 | ||
|
|
65add24e2a | ||
|
|
33a9fb6aa2 | ||
|
|
0bc5d20e8f | ||
|
|
49ea9cddd1 | ||
|
|
6a48cdcdf3 | ||
|
|
f78f039776 | ||
|
|
d881487d68 | ||
|
|
33d07b2b54 | ||
|
|
3bbec18ac6 | ||
|
|
fc5c198646 | ||
|
|
2be373fd06 | ||
|
|
b71ad85e9f | ||
|
|
86d3e9da86 | ||
|
|
f53d3bc390 | ||
|
|
f9ca440ce8 | ||
|
|
8ea2f5a766 | ||
|
|
6c1357e16c | ||
|
|
d880f088be | ||
|
|
5cabfd591b | ||
|
|
721730f0e8 | ||
|
|
af80849857 | ||
|
|
7a191e67b8 | ||
|
|
4b2e48f2c0 | ||
|
|
eb545d7941 | ||
|
|
a2e6e81697 | ||
|
|
1b24e2cbaf | ||
|
|
0843159fb4 | ||
|
|
a7e60af93f | ||
|
|
42f879687f | ||
|
|
057903a303 | ||
|
|
b8e99c30a2 | ||
|
|
3d933c16d0 | ||
|
|
e785886447 | ||
|
|
23ecff04b8 | ||
|
|
a0bae5db5c | ||
|
|
86368ed165 | ||
|
|
5e4c0ed825 | ||
|
|
ffa9dc5d67 | ||
|
|
43cb6c4995 | ||
|
|
36cb2ef41d | ||
|
|
098e250cc4 | ||
|
|
3d5a35b184 | ||
|
|
87d3f2641d | ||
|
|
c6c75c5a17 | ||
|
|
1ba44b02d4 | ||
|
|
6fd4cd85ca | ||
|
|
6182347641 | ||
|
|
401b0526a3 | ||
|
|
2f24328608 | ||
|
|
8ea42847da | ||
|
|
4ed23f44e6 | ||
|
|
178527dab1 | ||
|
|
f5c376dca8 | ||
|
|
239eac662c | ||
|
|
4e18f66db6 | ||
|
|
77937df955 | ||
|
|
4db8efa0df | ||
|
|
66c80bd16a | ||
|
|
5895aeecd7 | ||
|
|
83ffc99b9c | ||
|
|
3615772b2d | ||
|
|
78729bd277 | ||
|
|
85a9a1608c | ||
|
|
2e693f7011 | ||
|
|
6f0220da4b | ||
|
|
09a45b4397 | ||
|
|
6b408ef824 | ||
|
|
62b6117638 | ||
|
|
70111dafbc | ||
|
|
faaa74c3a7 | ||
|
|
8932aaf4ef | ||
|
|
6d6f3ea391 | ||
|
|
2ad7d0830e | ||
|
|
5045e206c2 | ||
|
|
07f9228694 | ||
|
|
50b5b91216 | ||
|
|
72bfc0915c | ||
|
|
a7d7a9adbd | ||
|
|
413af1fe67 | ||
|
|
b09cbb0ca4 | ||
|
|
5b135738b4 | ||
|
|
36e5772a8e | ||
|
|
2b9fb9643d | ||
|
|
2882e63dd8 | ||
|
|
812ef024ef | ||
|
|
40cdc5aa30 | ||
|
|
b8d6226a9a | ||
|
|
bac15d3919 | ||
|
|
4b4f670adf | ||
|
|
b1b57f9bfd | ||
|
|
b6933a73fa | ||
|
|
5033042b8c | ||
|
|
89a46089ee | ||
|
|
e288d7730b | ||
|
|
5ae75e723c | ||
|
|
d6d5009d23 | ||
|
|
06a0e7f3fe | ||
|
|
a9cd72bbf9 | ||
|
|
f184a74fa0 | ||
|
|
682b1dea5e | ||
|
|
3fbbf56986 | ||
|
|
2835d9b468 | ||
|
|
afd401c3d4 | ||
|
|
362bc060f6 | ||
|
|
c8fef45362 | ||
|
|
8d19eade85 | ||
|
|
d53332b7cf | ||
|
|
392d33b902 | ||
|
|
4305a71916 | ||
|
|
a4d8e12fd7 | ||
|
|
3cb5e109a3 | ||
|
|
e4a4b47fac | ||
|
|
8a35905d2e | ||
|
|
dbf4729109 | ||
|
|
86b9ef496c | ||
|
|
6336cc6452 | ||
|
|
bc79319864 | ||
|
|
62e88cff54 | ||
|
|
6e6c993724 | ||
|
|
f8b4e3775d | ||
|
|
fad69f85fa | ||
|
|
0029811de2 | ||
|
|
fe9ed3f70d | ||
|
|
aedfe62bb0 | ||
|
|
c4f00626ef | ||
|
|
fdad83a1bb | ||
|
|
20e11bbab3 | ||
|
|
5bbe9f9a04 | ||
|
|
7a93d219ef | ||
|
|
808522d895 | ||
|
|
be9efe0273 | ||
|
|
766b98c4ad | ||
|
|
c422543fdd | ||
|
|
cf33be4596 | ||
|
|
161d096139 | ||
|
|
b32cb6229b | ||
|
|
3dd5fff110 | ||
|
|
398a66dd4a | ||
|
|
59f8aa1c31 | ||
|
|
cfba97e104 | ||
|
|
bbf78716fd | ||
|
|
b9820641aa | ||
|
|
8c00556bab | ||
|
|
16d148a8a9 | ||
|
|
e8264e9b6a | ||
|
|
4f2b223070 | ||
|
|
05e128cafb | ||
|
|
59e9952a61 | ||
|
|
2f9fd09b2f | ||
|
|
ec20d657ba | ||
|
|
34ba279b0a | ||
|
|
c28065cc56 | ||
|
|
04960d0b98 | ||
|
|
280de022cb | ||
|
|
fa1cad7fb2 | ||
|
|
1926bfa1c5 | ||
|
|
2b351208e0 | ||
|
|
96b02e68ee | ||
|
|
82f4f8b2eb | ||
|
|
d703b0a2a1 | ||
|
|
2e3796c4f7 | ||
|
|
ac238b9d28 | ||
|
|
25e6fa53c2 | ||
|
|
57b4c685df | ||
|
|
3fd1279e7d | ||
|
|
3bc38c89ab | ||
|
|
4995cebc38 | ||
|
|
720157e8a3 | ||
|
|
8d9eb022d1 | ||
|
|
5e2eb51879 | ||
|
|
d0062b7de4 | ||
|
|
6307503cda | ||
|
|
9b1e04b1e8 | ||
|
|
24f1dbc0bb | ||
|
|
5d158c524d | ||
|
|
fd9287a0fd | ||
|
|
90836eff5b | ||
|
|
914cf68651 | ||
|
|
4db82d3d09 | ||
|
|
5055ef060d | ||
|
|
35088a7cac | ||
|
|
f046031b26 | ||
|
|
3b91bc2c0a | ||
|
|
4c4babd9e7 | ||
|
|
53dc53bf8f | ||
|
|
274e5ca676 | ||
|
|
5e7b7835b7 | ||
|
|
1bdfdbee89 | ||
|
|
ebffaab16a | ||
|
|
d6d4085809 | ||
|
|
2a44b0cafb | ||
|
|
834c42bc50 | ||
|
|
6c8ee1862a | ||
|
|
787beab63f | ||
|
|
58349a9410 | ||
|
|
93c2258d23 | ||
|
|
bd7a4dedc1 | ||
|
|
ae3ae0b5ba | ||
|
|
42d657eb54 | ||
|
|
d60d73b7e0 | ||
|
|
6704da1446 | ||
|
|
d24a2f7cab | ||
|
|
ed31002cc6 | ||
|
|
f8ac896795 | ||
|
|
3e96de26dd | ||
|
|
4f6fa40dbd | ||
|
|
104b804059 | ||
|
|
c545e46ebe | ||
|
|
52a216fbcb | ||
|
|
2c29d59895 | ||
|
|
de34d0d337 | ||
|
|
2bb7a6fc27 | ||
|
|
1b84292c56 | ||
|
|
18efae9703 | ||
|
|
4b6d86ef89 | ||
|
|
75a75a6f84 | ||
|
|
2e99589336 | ||
|
|
188b21dd36 | ||
|
|
0cf56e0aad | ||
|
|
bd7728ac94 | ||
|
|
b6f7a10569 | ||
|
|
53a9fc0e48 | ||
|
|
b05af6eecb | ||
|
|
571171a0c6 | ||
|
|
c5082498ab | ||
|
|
d19c215bf1 | ||
|
|
42dd46e305 | ||
|
|
a6496949f8 | ||
|
|
ab59323813 | ||
|
|
a56a9dc6a1 | ||
|
|
bc790ea581 | ||
|
|
dbfd158388 | ||
|
|
2b1f7da654 | ||
|
|
0c9d431a3f | ||
|
|
1a525df8ad | ||
|
|
ef1779ba80 | ||
|
|
d4e9938e3f | ||
|
|
f26c0b71d2 | ||
|
|
b2dfdc386a | ||
|
|
732a6922de | ||
|
|
9501a2209e | ||
|
|
8c83171a28 | ||
|
|
289936db7a | ||
|
|
6c71abbb09 | ||
|
|
841181ed55 | ||
|
|
c3821e9165 | ||
|
|
d9a4085efa | ||
|
|
6b35d8402c | ||
|
|
3b6f7250ee | ||
|
|
c6bf061b26 | ||
|
|
a8074ae3e4 | ||
|
|
cfc4e6b48b | ||
|
|
73fbcd7fa3 | ||
|
|
79317ed67e | ||
|
|
1b26632bb4 | ||
|
|
5b415c6895 | ||
|
|
078f3bff70 | ||
|
|
d02f800d1b | ||
|
|
83d3643e8f | ||
|
|
6d35ae56d3 | ||
|
|
39270a8e35 | ||
|
|
8c08f957cd | ||
|
|
5924d0fe0d | ||
|
|
c23a34d475 | ||
|
|
1bd3a725ca | ||
|
|
848dea83ab | ||
|
|
bded529535 | ||
|
|
ec665a97db | ||
|
|
fc536b6ff3 | ||
|
|
f96bef43cc | ||
|
|
f4e8ee0af9 | ||
|
|
c2e5f5cb2b | ||
|
|
9ca116d545 | ||
|
|
cdd3a64638 | ||
|
|
99e51f8a52 | ||
|
|
3b4b57c081 | ||
|
|
c7f8ead496 | ||
|
|
3f15879578 | ||
|
|
1cdd205eb7 | ||
|
|
77099b3bce | ||
|
|
0d8a4099c1 | ||
|
|
606cf6a941 | ||
|
|
ba9065cada | ||
|
|
e693802091 | ||
|
|
fa0dd684da | ||
|
|
43fb7fe635 | ||
|
|
91e4ea6e2f | ||
|
|
1e3e34f15f | ||
|
|
96fb0f78f7 | ||
|
|
2e6c410336 | ||
|
|
0293e04311 | ||
|
|
8c066764d9 | ||
|
|
1900e512f2 | ||
|
|
d0ccde7b48 | ||
|
|
1e261e347a | ||
|
|
2cb4cdc645 | ||
|
|
123ac4fd33 | ||
|
|
423bb8e317 | ||
|
|
e6ff280984 | ||
|
|
3fdfad27cd | ||
|
|
d3bbc0ec95 | ||
|
|
e54608c282 | ||
|
|
9b9a40ddd7 | ||
|
|
1b00184c89 | ||
|
|
e11825392d | ||
|
|
1a995d9e26 | ||
|
|
53d4820d74 | ||
|
|
40a5fa46d1 | ||
|
|
05e33edb0d | ||
|
|
76dba1a521 | ||
|
|
f7298a45bd | ||
|
|
3f606feea3 | ||
|
|
541d9252f6 | ||
|
|
cbbbb117e0 | ||
|
|
415f95b792 | ||
|
|
5f17abc856 | ||
|
|
a91995f0a7 | ||
|
|
216acb0eeb | ||
|
|
5dd5fc4a1c | ||
|
|
09133c8f59 | ||
|
|
d08a3095a9 | ||
|
|
593fd242bf | ||
|
|
e591d9082f | ||
|
|
b6f26c0f1e | ||
|
|
34b7638342 | ||
|
|
acd91665b5 | ||
|
|
b503ea1cf7 | ||
|
|
091c2e45bf | ||
|
|
0a78d1d2fa | ||
|
|
ff4780d5fb | ||
|
|
07beef3db2 | ||
|
|
0924f8ca7a | ||
|
|
6302aa6c12 | ||
|
|
da4d9ff607 | ||
|
|
dd0bdef640 | ||
|
|
e57e08088a | ||
|
|
5e43c394d5 | ||
|
|
b2eaaeca4b | ||
|
|
e2d9a523c3 | ||
|
|
11df1e4680 | ||
|
|
53d5542402 | ||
|
|
bfda3f40b9 | ||
|
|
c0ddceb2bd | ||
|
|
42a506231b | ||
|
|
e3252f53da | ||
|
|
aa33428311 | ||
|
|
ca5d228be6 | ||
|
|
f89a98c78a | ||
|
|
a3087d8815 | ||
|
|
23d2df7a93 | ||
|
|
1cd97d46a2 | ||
|
|
53f84a8092 | ||
|
|
6441de63ba | ||
|
|
b2553aea33 | ||
|
|
5ef1cfbdc7 | ||
|
|
7527b4dc27 | ||
|
|
1367816b04 | ||
|
|
299a2315c1 | ||
|
|
9a6aea6940 | ||
|
|
98cd04cccf | ||
|
|
0cc20cbb97 | ||
|
|
ef6a17d4a6 | ||
|
|
17a149947a | ||
|
|
a2c50ae967 | ||
|
|
13958ba4df | ||
|
|
8eb71483f3 | ||
|
|
d8e30883fa | ||
|
|
47acbbf332 | ||
|
|
dece359c90 | ||
|
|
6a9eb4e367 | ||
|
|
fc03ce9b2f | ||
|
|
ce17c12ca2 | ||
|
|
5edaeb8c7b | ||
|
|
3a28d1b073 | ||
|
|
6f2226bfcd | ||
|
|
97cd4c64ad | ||
|
|
43d50d0667 | ||
|
|
6258a7f311 | ||
|
|
ab36cc8968 | ||
|
|
33b71c6b3c | ||
|
|
34e821c102 | ||
|
|
2af557139d | ||
|
|
9e0dcd8718 | ||
|
|
be2b5a62de | ||
|
|
0cbba71c72 | ||
|
|
d28563fb45 | ||
|
|
38632f0f90 | ||
|
|
0754ce01b1 | ||
|
|
1ef455d37d | ||
|
|
d152603abd | ||
|
|
9e125aec00 | ||
|
|
2c90c267bd | ||
|
|
47de93961e | ||
|
|
1990f32ca4 | ||
|
|
807939c0e4 | ||
|
|
a1c7bf0883 | ||
|
|
5008cc603e | ||
|
|
9857db96cd | ||
|
|
e9e6d94e3b | ||
|
|
462a79cf47 | ||
|
|
f792deeebd | ||
|
|
95173bb327 | ||
|
|
1d09e2406b | ||
|
|
c9add7a8bf | ||
|
|
e4caed9277 | ||
|
|
1760eaa601 | ||
|
|
b25ce67fe1 | ||
|
|
b23ba6f75e | ||
|
|
cf904a05cc | ||
|
|
47a5a44b9e | ||
|
|
a0e6c7ceb6 | ||
|
|
49aa367ffa | ||
|
|
83b36f2c3a | ||
|
|
2b341d884f | ||
|
|
141a09b31e | ||
|
|
6378ec4bbd | ||
|
|
603fb1c698 | ||
|
|
67b4ea947b | ||
|
|
4075b7c78a | ||
|
|
6499eba0cb | ||
|
|
980626aa40 | ||
|
|
3f329bc1a8 | ||
|
|
69de67b1c2 | ||
|
|
7158f9a8d9 | ||
|
|
bb75bd7167 | ||
|
|
4fa58169f1 | ||
|
|
564040897f | ||
|
|
f78bbab289 | ||
|
|
d3c82d7363 | ||
|
|
7b9b978a6d | ||
|
|
45d47818ca | ||
|
|
202c4a948b | ||
|
|
b5269bb28e | ||
|
|
d6c5f09a1a | ||
|
|
11546b97bb | ||
|
|
cac6a251cc | ||
|
|
31d26a7bad | ||
|
|
a9ed9ae936 | ||
|
|
a9892efe38 | ||
|
|
f02e0a3ccb | ||
|
|
d6f26609fc | ||
|
|
05438d047d | ||
|
|
32f5632620 | ||
|
|
005cc08b40 | ||
|
|
6a659fe10d | ||
|
|
6941ca2f63 | ||
|
|
e4eba49c1b | ||
|
|
f289439d1d | ||
|
|
a5ef64919a | ||
|
|
e132125cf3 | ||
|
|
01b5512ac7 | ||
|
|
a0c7e63d78 | ||
|
|
8ba5f2ffa7 | ||
|
|
2c44333679 | ||
|
|
610be9cf17 | ||
|
|
eb5e8fe388 | ||
|
|
c999c6082f | ||
|
|
3b86b3fe66 | ||
|
|
0a71dca825 | ||
|
|
4f98d470a0 | ||
|
|
57abae3999 | ||
|
|
202e49a897 | ||
|
|
13093f1732 | ||
|
|
837d327c1e | ||
|
|
e39b777abc | ||
|
|
7ca42489ae | ||
|
|
8c6363f792 | ||
|
|
cbb7f29f96 | ||
|
|
8886c9b6bc | ||
|
|
a07de38e80 | ||
|
|
1f08997a9e | ||
|
|
1b2d07d81d | ||
|
|
fc32cf5bcc | ||
|
|
ce94ef38b2 | ||
|
|
1e9c587b92 | ||
|
|
9f1d633ae4 | ||
|
|
f01189631a | ||
|
|
542877ee46 | ||
|
|
f1760b516d | ||
|
|
f0143fd6c9 | ||
|
|
febfa72d60 | ||
|
|
c03e00035f | ||
|
|
2f8866ef32 | ||
|
|
f98afac6df | ||
|
|
5efd5abbe4 | ||
|
|
6bb8f5d889 | ||
|
|
35f4a49d10 | ||
|
|
a31d713fcc | ||
|
|
6f38f7afc3 | ||
|
|
e514ca0009 | ||
|
|
8c3aed2846 | ||
|
|
2cab9d5514 | ||
|
|
c38bdbb0c5 | ||
|
|
2a1704a0dc | ||
|
|
36168b4609 | ||
|
|
bd498def76 | ||
|
|
d8279c48ac | ||
|
|
4232245546 | ||
|
|
2d1186e55d | ||
|
|
072aeca1be | ||
|
|
cb656f9ef4 | ||
|
|
322a5779f1 | ||
|
|
e41df28bf2 | ||
|
|
d3239b49ce | ||
|
|
d11be61d94 | ||
|
|
916063a79b | ||
|
|
5aa0bf2d14 | ||
|
|
f3ad6b4acc | ||
|
|
ec039719de | ||
|
|
6989df0af3 | ||
|
|
14b16b2f36 | ||
|
|
cbc7e280d6 | ||
|
|
f4fa9c93a0 | ||
|
|
6c64723d7c | ||
|
|
3d21f2223e | ||
|
|
710a69b812 | ||
|
|
dd6a8d9998 | ||
|
|
9f32e5af0a | ||
|
|
298e19598b | ||
|
|
680191d7cb | ||
|
|
81d6d69b85 | ||
|
|
6df72bf4ac | ||
|
|
01f2451349 | ||
|
|
dcd971d079 | ||
|
|
4d22fb9b2a | ||
|
|
c18d58b13f | ||
|
|
b539c2df70 | ||
|
|
64fdb4ddc1 | ||
|
|
a8669197dd | ||
|
|
2412c92772 | ||
|
|
7c0ca42145 | ||
|
|
c443524ee2 | ||
|
|
e2fa01e0cf | ||
|
|
6558f05d1d | ||
|
|
1be0f39be0 | ||
|
|
d01001f2a5 | ||
|
|
7c85694d60 | ||
|
|
b2fcd4c9e5 | ||
|
|
ba8123f08a | ||
|
|
e2879a8eb1 | ||
|
|
eab8652225 | ||
|
|
ead6f96513 | ||
|
|
7ec662c83f | ||
|
|
348d2b8701 | ||
|
|
12f0dcb23b | ||
|
|
449a538e6b | ||
|
|
3c50c9a18b | ||
|
|
3c10ec70a5 | ||
|
|
1a59f343c0 | ||
|
|
fba4d4702e | ||
|
|
143bbf37f4 | ||
|
|
fd3ad267ba | ||
|
|
330583f71d | ||
|
|
d775f90f0c | ||
|
|
e096144713 | ||
|
|
7ce30ba888 | ||
|
|
6a3ec1d874 | ||
|
|
575d3a66c6 | ||
|
|
cc333b3965 | ||
|
|
351758b3bd | ||
|
|
94053d8432 | ||
|
|
e14b2826e0 | ||
|
|
150611123a | ||
|
|
abfc17ee62 | ||
|
|
97be9c94b9 | ||
|
|
21b00e8fbb | ||
|
|
01636c2e4b | ||
|
|
005315cd29 | ||
|
|
20d20df829 | ||
|
|
f945a1bc6b | ||
|
|
3a09b04786 | ||
|
|
82e752395b | ||
|
|
e330abd587 | ||
|
|
16422b4055 | ||
|
|
b9ca74c915 | ||
|
|
7e05d7478f | ||
|
|
8fd98d7db3 | ||
|
|
1039a08be6 | ||
|
|
023b38df50 | ||
|
|
3187053b3a | ||
|
|
a3e526e818 | ||
|
|
f6d4621834 | ||
|
|
d075113c1a | ||
|
|
63f2abd923 | ||
|
|
f78cff225b | ||
|
|
31eec9fa1c | ||
|
|
624cc7876a | ||
|
|
d3059c810f | ||
|
|
85a40da83c | ||
|
|
1bf8f1991f | ||
|
|
d155aa8745 | ||
|
|
c0bfd6d15f | ||
|
|
24cc108147 | ||
|
|
b02d7d990e | ||
|
|
87f82addbc | ||
|
|
09713e8eab |
30
.editorconfig
Normal file
30
.editorconfig
Normal file
@@ -0,0 +1,30 @@
|
||||
# EditorConfig helps developers define and maintain consistent
|
||||
# coding styles between different editors and IDEs
|
||||
# editorconfig.org
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[Makefile]
|
||||
indent_style = tabs
|
||||
indent_size = 4
|
||||
|
||||
[Vagrantfile]
|
||||
indent_size = 2
|
||||
|
||||
[*.rb]
|
||||
indent_size = 2
|
||||
|
||||
[*.py]
|
||||
indent_style = tabs
|
||||
|
||||
[*.js]
|
||||
indent_size = 2
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -4,3 +4,4 @@ management/__pycache__/
|
||||
tools/__pycache__/
|
||||
externals/
|
||||
.env
|
||||
.vagrant
|
||||
|
||||
773
CHANGELOG.md
773
CHANGELOG.md
@@ -1,6 +1,777 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
v0.42 (July 4, 2019)
|
||||
--------------------
|
||||
|
||||
Changes:
|
||||
|
||||
* Decreased the minimum supported RAM to 502 Mb.
|
||||
* Improved mail client autoconfiguration.
|
||||
* Added support for S3-compatible backup services besides Amazon S3.
|
||||
* Fixed the control panel login page to let LastPass save passwords.
|
||||
* Fixed an error in the user privileges API.
|
||||
* Silenced some spurrious messages.
|
||||
|
||||
Software updates:
|
||||
|
||||
* Upgraded Roundcube from 1.3.8 to 1.3.9.
|
||||
* Upgraded Nextcloud from 14.0.6 to 15.0.8 (with Contacts from 2.1.8 to 3.1.1 and Calendar from 1.6.4 to 1.6.5).
|
||||
* Upgraded Z-Push from 2.4.4 to 2.5.0.
|
||||
|
||||
v0.41 (February 26, 2019)
|
||||
-------------------------
|
||||
|
||||
System:
|
||||
|
||||
* Missing brute force login attack prevention (fail2ban) filters which stopped working on Ubuntu 18.04 were added back.
|
||||
* Upgrades would fail if Mail-in-a-Box moved to a different directory in `systemctl link`.
|
||||
|
||||
Mail:
|
||||
|
||||
* Incoming messages addressed to more than one local user were rejected because of a bug in spampd packaged by Ubuntu 18.04. A workaround was added.
|
||||
|
||||
Contacts/Calendar:
|
||||
|
||||
* Upgraded Nextcloud from 13.0.6 to 14.0.6.
|
||||
* Upgraded Contacts from 2.1.5 to 2.1.8.
|
||||
* Upgraded Calendar from 1.6.1 to 1.6.4.
|
||||
|
||||
v0.40 (January 12, 2019)
|
||||
------------------------
|
||||
|
||||
This is the first release for Ubuntu 18.04. This version and versions going forward can **only** be installed on Ubuntu 18.04; however, upgrades of existing Ubuntu 14.04 boxes to the latest version supporting Ubuntu 14.04 (v0.30) continue to work as normal.
|
||||
|
||||
When **upgrading**, you **must first upgrade your existing Ubuntu 14.04 Mail-in-a-Box box** to the latest release supporting Ubuntu 14.04 --- that's v0.30 --- before you migrate to Ubuntu 18.04. If you are running an older version of Mail-in-a-Box which has an old version of ownCloud or Nextcloud, you will *not* be able to upgrade your data because older versions of ownCloud and Nextcloud that are required to perform the upgrade *cannot* be run on Ubuntu 18.04. To upgrade from Ubuntu 14.04 to Ubuntu 18.04, you **must create a fresh Ubuntu 18.04 machine** before installing this version. In-place upgrades of servers are not supported. Since Ubuntu's support for Ubuntu 14.04 has almost ended, everyone is encouraged to create a new Ubuntu 18.04 machine and migrate to it.
|
||||
|
||||
For complete upgrade instructions, see:
|
||||
|
||||
https://discourse.mailinabox.email/t/mail-in-a-box-version-v0-40-and-moving-to-ubuntu-18-04/4289
|
||||
|
||||
The changelog for this release follows.
|
||||
|
||||
Setup:
|
||||
|
||||
* Mail-in-a-Box now targets Ubuntu 18.04 LTS, which will have support from Ubuntu through 2022.
|
||||
* Some of the system packages updated in virtue of using Ubuntu 18.04 include postfix (2.11=>3.3) nsd (4.0=>4.1), nginx (1.4=>1.14), PHP (7.0=>7.2), Python (3.4=>3.6), fail2ban (0.8=>0.10), Duplicity (0.6=>0.7).
|
||||
* [Unofficial Bash Strict Mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) is turned on for setup, which might catch previously uncaught issues during setup.
|
||||
|
||||
Mail:
|
||||
|
||||
* IMAP server-side full text search is no longer supported because we were using a custom-built `dovecot-lucene` package that we are no longer maintaining.
|
||||
* Sending email is now disabled on port 25 --- you must log in to port 587 to send email, per the long-standing mail instructions.
|
||||
* Greylisting may delay more emails from new senders. We were using a custom-built postgrey package previously that whitelisted sending domains in dnswl.org, but we are no longer maintaining that package.
|
||||
|
||||
v0.30 (January 9, 2019)
|
||||
-----------------------
|
||||
|
||||
Setup:
|
||||
|
||||
* Update to Roundcube 1.3.8 and the CardDAV plugin to 3.0.3.
|
||||
* Add missing rsyslog package to install line since some OS images don't have it installed by default.
|
||||
* A log file for nsd was added.
|
||||
|
||||
Control Panel:
|
||||
|
||||
* The users page now documents that passwords should only have ASCII characters to prevent character encoding mismaches between clients and the server.
|
||||
* The users page no longer shows user mailbox sizes because this was extremely slow for very large mailboxes.
|
||||
* The Mail-in-a-Box version is now shown in the system status checks even when the new-version check is disabled.
|
||||
* The alises page now warns that alises should not be used to forward mail off of the box. Mail filters within Roundcube are better for that.
|
||||
* The explanation of greylisting has been improved.
|
||||
|
||||
v0.29 (October 25, 2018)
|
||||
------------------------
|
||||
|
||||
* Starting with v0.28, TLS certificate provisioning wouldn't work on new boxes until the mailinabox setup command was run a second time because of a problem with the non-interactive setup.
|
||||
* Update to Nextcloud 13.0.6.
|
||||
* Update to Roundcube 1.3.7.
|
||||
* Update to Z-Push 2.4.4.
|
||||
* Backup dates listed in the control panel now use an internationalized format.
|
||||
|
||||
v0.28 (July 30, 2018)
|
||||
---------------------
|
||||
|
||||
System:
|
||||
|
||||
* We now use EFF's `certbot` to provision TLS certificates (from Let's Encrypt) instead of our home-grown ACME library.
|
||||
|
||||
Contacts/Calendar:
|
||||
|
||||
* Fix for Mac OS X autoconfig of the calendar.
|
||||
|
||||
Setup:
|
||||
|
||||
* Installing Z-Push broke because of what looks like a change or problem in their git server HTTPS certificate. That's fixed.
|
||||
|
||||
v0.27 (June 14, 2018)
|
||||
---------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* A report of box activity, including sent/received mail totals and logins by user, is now emailed to the box's administrator user each week.
|
||||
* Update Roundcube to version 1.3.6 and Z-Push to version 2.3.9.
|
||||
|
||||
Control Panel:
|
||||
|
||||
* The undocumented feature for proxying web requests to another server now sets X-Forwarded-For.
|
||||
|
||||
v0.26c (February 13, 2018)
|
||||
--------------------------
|
||||
|
||||
Setup:
|
||||
|
||||
* Upgrades from v0.21c (February 1, 2017) or earlier were broken because the intermediate versions of ownCloud used in setup were no longer available from ownCloud.
|
||||
* Some download errors had no output --- there is more output on error now.
|
||||
|
||||
Control Panel:
|
||||
|
||||
* The background service for the control panel was not restarting on updates, leaving the old version running. This was broken in v0.26 and is now fixed.
|
||||
* Installing your own TLS/SSL certificate had been broken since v0.24 because the new version of openssl became stricter about CSR generation parameters.
|
||||
* Fixed password length help text.
|
||||
|
||||
Contacts/Calendar:
|
||||
|
||||
* Upgraded Nextcloud from 12.0.3 to 12.0.5.
|
||||
|
||||
v0.26b (January 25, 2018)
|
||||
-------------------------
|
||||
|
||||
* Fix new installations which broke at the step of asking for the user's desired email address, which was broken by v0.26's changes related to the control panel.
|
||||
* Fix the provisioning of TLS certificates by pinning a Python package we rely on (acme) to an earlier version because our code isn't yet compatible with its current version.
|
||||
* Reduce munin's log_level from debug to warning to prevent massive log files.
|
||||
|
||||
v0.26 (January 18, 2018)
|
||||
------------------------
|
||||
|
||||
Security:
|
||||
|
||||
* HTTPS, IMAP, and POP's TLS settings have been updated to Mozilla's intermediate cipher list recommendation. Some extremely old devices that use less secure TLS ciphers may no longer be able to connect to IMAP/POP.
|
||||
* Updated web HSTS header to use longer six month duration.
|
||||
|
||||
Mail:
|
||||
|
||||
* Adding attachments in Roundcube broke after the last update for some users after rebooting because a temporary directory was deleted on reboot. The temporary directory is now moved from /tmp to /var so that it is persistent.
|
||||
* `X-Spam-Score` header is added to incoming mail.
|
||||
|
||||
Control panel:
|
||||
|
||||
* RSASHA256 is now used for DNSSEC for .lv domains.
|
||||
* Some documentation/links improvements.
|
||||
|
||||
Installer:
|
||||
|
||||
* We now run `apt-get autoremove` at the start of setup to clear out old packages, especially old kernels that take up a lot of space. On the first run, this step may take a long time.
|
||||
* We now fetch Z-Push from its tagged git repository, fixing an installation problem.
|
||||
* Some old PHP5 packages are removed from setup, fixing an installation bug where Apache would get installed.
|
||||
* Python 3 packages for the control panel are now installed using a virtualenv to prevent installation errors due to conflicts in the cryptography/openssl packages between OS-installed packages and pip-installed packages.
|
||||
|
||||
v0.25 (November 15, 2017)
|
||||
-------------------------
|
||||
|
||||
This update is a security update addressing [CVE-2017-16651, a vulnerability in Roundcube webmail that allows logged-in users to access files on the local filesystem](https://roundcube.net/news/2017/11/08/security-updates-1.3.3-1.2.7-and-1.1.10).
|
||||
|
||||
Mail:
|
||||
|
||||
* Update to Roundcube 1.3.3.
|
||||
|
||||
Control Panel:
|
||||
|
||||
* Allow custom DNS records to be set for DNS wildcard subdomains (i.e. `*`).
|
||||
|
||||
v0.24 (October 3, 2017)
|
||||
-----------------------
|
||||
|
||||
System:
|
||||
|
||||
* Install PHP7 via a PPA. Switch to the on-demand process manager.
|
||||
|
||||
Mail:
|
||||
|
||||
* Updated to [Roundcube 1.3.1](https://roundcube.net/news/2017/06/26/roundcube-webmail-1.3.0-released), but unfortunately dropping the Vacation plugin because it has not been supported by its author and is not compatible with Roundcube 1.3, and updated the persistent login plugin.
|
||||
* Updated to [Z-Push 2.3.8](http://download.z-push.org/final/2.3/z-push-2.3.8.txt).
|
||||
* Dovecot now uses stronger 2048 bit DH params for better forward secrecy.
|
||||
|
||||
Nextcloud:
|
||||
|
||||
* Nextcloud updated to 12.0.3, using PHP7.
|
||||
|
||||
Control Panel:
|
||||
|
||||
* Nameserver (NS) records can now be set on custom domains.
|
||||
* Fix an erroneous status check error due to IPv6 address formatting.
|
||||
* Aliases for administrative addresses can now be set to send mail to +tag administrative addresses.
|
||||
|
||||
v0.23a (May 31, 2017)
|
||||
---------------------
|
||||
|
||||
Corrects a problem in the new way third-party assets are downloaded during setup for the control panel, since v0.23.
|
||||
|
||||
v0.23 (May 30, 2017)
|
||||
--------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* The default theme for Roundcube was changed to the nicer Larry theme.
|
||||
* Exchange/ActiveSync support has been replaced with z-push 2.3.6 from z-push.org (rather than z-push-contrib).
|
||||
|
||||
ownCloud (now Nextcloud):
|
||||
|
||||
* ownCloud is replaced with Nextcloud 10.0.5.
|
||||
* Fixed an error in Owncloud/Nextcloud setup not updating domain when changing hostname.
|
||||
|
||||
Control Panel/Management:
|
||||
|
||||
* Fix an error in the control panel showing rsync backup status.
|
||||
* Fix an error in the control panel related to IPv6 addresses.
|
||||
* TLS certificates for internationalized domain names can now be provisioned from Let's Encrypt automatically.
|
||||
* Third-party assets used in the control panel (jQuery/Bootstrap) are now downloaded during setup and served from the box rather than from a CDN.
|
||||
|
||||
DNS:
|
||||
|
||||
* Add support for custom CAA records.
|
||||
|
||||
v0.22 (April 2, 2017)
|
||||
---------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* The CardDAV plugin has been added to Roundcube so that your ownCloud contacts are available in webmail.
|
||||
* Upgraded to Roundcube 1.2.4 and updated the persistent login plugin.
|
||||
* Allow larger messages to be checked by SpamAssassin.
|
||||
* Dovecot's vsz memory limit has been increased proportional to system memory.
|
||||
* Newly set user passwords must be at least eight characters.
|
||||
|
||||
ownCloud:
|
||||
|
||||
* Upgraded to ownCloud 9.1.4.
|
||||
|
||||
Control Panel/Management:
|
||||
|
||||
* The status checks page crashed when the mailinabox.email website was down - that's fixed.
|
||||
* Made nightly re-provisioning of TLS certificates less noisy.
|
||||
* Fixed bugs in rsync backup method and in the list of recent backups.
|
||||
* Fixed incorrect status checks errors about IPv6 addresses.
|
||||
* Fixed incorrect status checks errors for secondary nameservers if round-robin custom A records are set.
|
||||
* The management mail_log.py tool has been rewritten.
|
||||
|
||||
DNS:
|
||||
|
||||
* Added support for DSA, ED25519, and custom SSHFP records.
|
||||
|
||||
System:
|
||||
|
||||
* The SSH fail2ban jail was not activated.
|
||||
|
||||
Installation:
|
||||
|
||||
* At the end of installation, the SHA256 -- rather than SHA1 -- hash of the system's TLS certificate is shown.
|
||||
|
||||
v0.21c (February 1, 2017)
|
||||
-------------------------
|
||||
|
||||
Installations and upgrades started failing about 10 days ago with the error "ImportError: No module named 'packaging'" after an upstream package (Python's setuptools) was updated by its maintainers. The updated package conflicted with Ubuntu 14.04's version of another package (Python's pip). This update upgrades both packages to remove the conflict.
|
||||
|
||||
If you already encountered the error during installation or upgrade of Mail-in-a-Box, this update may not correct the problem on your existing system. See https://discourse.mailinabox.email/t/v0-21c-release-fixes-python-package-installation-issue/1881 for help if the problem persists after upgrading to this version of Mail-in-a-Box.
|
||||
|
||||
v0.21b (December 4, 2016)
|
||||
-------------------------
|
||||
|
||||
This update corrects a first-time installation issue introduced in v0.21 caused by the new Exchange/ActiveSync feature.
|
||||
|
||||
v0.21 (November 30, 2016)
|
||||
-------------------------
|
||||
|
||||
This version updates ownCloud, which may include security fixes, and makes some other smaller improvements.
|
||||
|
||||
Mail:
|
||||
|
||||
* Header privacy filters were improperly running on the contents of forwarded email --- that's fixed.
|
||||
* We have another go at fixing a long-standing issue with training the spam filter (because of a file permissions issue).
|
||||
* Exchange/ActiveSync will now use your display name set in Roundcube in the From: line of outgoing email.
|
||||
|
||||
ownCloud:
|
||||
|
||||
* Updated ownCloud to version 9.1.1.
|
||||
|
||||
Control panel:
|
||||
|
||||
* Backups can now be made using rsync-over-ssh!
|
||||
* Status checks failed if the system doesn't support iptables or doesn't have ufw installed.
|
||||
* Added support for SSHFP records when sshd listens on non-standard ports.
|
||||
* Recommendations for TLS certificate providers were removed now that everyone mostly uses Let's Encrypt.
|
||||
|
||||
System:
|
||||
|
||||
* Ubuntu's "Upgrade to 16.04" notice is suppressed since you should not do that.
|
||||
* Lowered memory requirements to 512MB, display a warning if system memory is below 768MB.
|
||||
|
||||
v0.20 (September 23, 2016)
|
||||
--------------------------
|
||||
|
||||
ownCloud:
|
||||
|
||||
* Updated to ownCloud to 8.2.7.
|
||||
|
||||
Control Panel:
|
||||
|
||||
* Fixed a crash that occurs when there are IPv6 DNS records due to a bug in dnspython 1.14.0.
|
||||
* Improved the wonky low disk space check.
|
||||
|
||||
v0.19b (August 20, 2016)
|
||||
------------------------
|
||||
|
||||
This update corrects a security issue introduced in v0.18.
|
||||
|
||||
* A remote code execution vulnerability is corrected in how the munin system monitoring graphs are generated for the control panel. The vulnerability involves an administrative user visiting a carefully crafted URL.
|
||||
|
||||
v0.19a (August 18, 2016)
|
||||
------------------------
|
||||
|
||||
This update corrects a security issue in v0.19.
|
||||
|
||||
* fail2ban won't start if Roundcube had not yet been used - new installations probably do not have fail2ban running.
|
||||
|
||||
v0.19 (August 13, 2016)
|
||||
-----------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* Roundcube is updated to version 1.2.1.
|
||||
* SSLv3 and RC4 are now no longer supported in incoming and outgoing mail (SMTP port 25).
|
||||
|
||||
Control panel:
|
||||
|
||||
* The users and aliases APIs are now documented on their control panel pages.
|
||||
* The HSTS header was missing.
|
||||
* New status checks were added for the ufw firewall.
|
||||
|
||||
DNS:
|
||||
|
||||
* Add SRV records for CardDAV/CalDAV to facilitate autoconfiguration (e.g. in DavDroid, whose latest version didn't seem to work to configure with entering just a hostname).
|
||||
|
||||
System:
|
||||
|
||||
* fail2ban jails added for SMTP submission, Roundcube, ownCloud, the control panel, and munin.
|
||||
* Mail-in-a-Box can now be installed on the i686 architecture.
|
||||
|
||||
v0.18c (June 2, 2016)
|
||||
---------------------
|
||||
|
||||
* Domain aliases (and misconfigured aliases/catch-alls with non-existent local targets) would accept mail and deliver it to new mailbox folders on disk even if the target address didn't correspond with an existing mail user, instead of rejecting the mail. This issue was introduced in v0.18.
|
||||
* The Munin Monitoring link in the control panel now opens a new window.
|
||||
* Added an undocumented before-backup script.
|
||||
|
||||
v0.18b (May 16, 2016)
|
||||
---------------------
|
||||
|
||||
* Fixed a Roundcube user accounts issue introduced in v0.18.
|
||||
|
||||
v0.18 (May 15, 2016)
|
||||
--------------------
|
||||
|
||||
ownCloud:
|
||||
|
||||
* Updated to ownCloud to 8.2.3
|
||||
|
||||
Mail:
|
||||
|
||||
* Roundcube is updated to version 1.1.5 and the Roundcube login screen now says "[hostname] Webmail" instead of "Mail-in-a-Box/Roundcube webmail".
|
||||
* Fixed a long-standing issue with training the spam filter not working (because of a file permissions issue).
|
||||
|
||||
Control panel:
|
||||
|
||||
* Munin system monitoring graphs are now zoomable.
|
||||
* When a reboot is required (due to Ubuntu security updates automatically installed), a Reboot Box button now appears on the System Status Checks page of the control panel.
|
||||
* It is now possible to add SRV and secondary MX records in the Custom DNS page.
|
||||
* Other minor fixes.
|
||||
|
||||
System:
|
||||
|
||||
* The fail2ban recidive jail, which blocks long-duration brute force attacks, now no longer sends the administrator emails (which were not helpful).
|
||||
|
||||
Setup:
|
||||
|
||||
* The system hostname is now set during setup.
|
||||
* A swap file is now created if system memory is less than 2GB, 5GB of free disk space is available, and if no swap file yet exists.
|
||||
* We now install Roundcube from the official GitHub repository instead of our own mirror, which we had previously created to solve problems with SourceForge.
|
||||
* DKIM was incorrectly set up on machines where "localhost" was defined as something other than "127.0.0.1".
|
||||
|
||||
v0.17c (April 1, 2016)
|
||||
----------------------
|
||||
|
||||
This update addresses some minor security concerns and some installation issues.
|
||||
|
||||
ownCoud:
|
||||
|
||||
* Block web access to the configuration parameters (config.php). There is no immediate impact (see [#776](https://github.com/mail-in-a-box/mailinabox/pull/776)), although advanced users may want to take note.
|
||||
|
||||
Mail:
|
||||
|
||||
* Roundcube html5_notifier plugin updated from version 0.6 to 0.6.2 to fix Roundcube getting stuck for some people.
|
||||
|
||||
Control panel:
|
||||
|
||||
* Prevent click-jacking of the management interface by adding HTTP headers.
|
||||
* Failed login no longer reveals whether an account exists on the system.
|
||||
|
||||
Setup:
|
||||
|
||||
* Setup dialogs did not appear correctly when connecting to SSH using Putty on Windows.
|
||||
* We now install Roundcube from our own mirror because Sourceforge's downloads experience frequent intermittant unavailability.
|
||||
|
||||
v0.17b (March 1, 2016)
|
||||
----------------------
|
||||
|
||||
ownCloud moved their source code to a new location, breaking our installation script.
|
||||
|
||||
v0.17 (February 25, 2016)
|
||||
-------------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* Roundcube updated to version 1.1.4.
|
||||
* When there's a problem delivering an outgoing message, a new 'warning' bounce will come after 3 hours and the box will stop trying after 2 days (instead of 5).
|
||||
* On multi-homed machines, Postfix now binds to the right network interface when sending outbound mail so that SPF checks on the receiving end will pass.
|
||||
* Mail sent from addresses on subdomains of other domains hosted by this box would not be DKIM-signed and so would fail DMARC checks by recipients, since version v0.15.
|
||||
|
||||
Control panel:
|
||||
|
||||
* TLS certificate provisioning would crash if DNS propagation was in progress and a challenge failed; might have shown the wrong error when provisioning fails.
|
||||
* Backup times were displayed with the wrong time zone.
|
||||
* Thresholds for displaying messages when the system is running low on memory have been reduced from 30% to 20% for a warning and from 15% to 10% for an error.
|
||||
* Other minor fixes.
|
||||
|
||||
System:
|
||||
|
||||
* Backups to some AWS S3 regions broke in version 0.15 because we reverted the version of boto. That's now fixed.
|
||||
* On low-usage systems, don't hold backups for quite so long by taking a full backup more often.
|
||||
* Nightly status checks might fail on systems not configured with a default Unicode locale.
|
||||
* If domains need a TLS certificate and the user hasn't installed one yet using Let's Encrypt, the administrator would get a nightly email with weird interactive text asking them to agree to Let's Encrypt's ToS. Now just say that the provisioning can't be done automatically.
|
||||
* Reduce the number of background processes used by the management daemon to lower memory consumption.
|
||||
|
||||
Setup:
|
||||
|
||||
* The first screen now warns users not to install on a machine used for other things.
|
||||
|
||||
v0.16 (January 30, 2016)
|
||||
------------------------
|
||||
|
||||
This update primarily adds automatic SSL (now "TLS") certificate provisioning from Let's Encrypt (https://letsencrypt.org/).
|
||||
|
||||
Control Panel:
|
||||
|
||||
* The SSL certificates (now referred to as "TLS ccertificates") page now supports provisioning free certificates from Let's Encrypt.
|
||||
* Report free memory usage.
|
||||
* Fix a crash when the git directory is not checked out to a tag.
|
||||
* When IPv6 is enabled, check that all domains (besides the system hostname) resolve over IPv6.
|
||||
* When a domain doesn't resolve to the box, don't bother checking if the TLS certificate is valid.
|
||||
* Remove rounded border on the menu bar.
|
||||
|
||||
Other:
|
||||
|
||||
* The Sieve port is now open so tools like the Thunderbird Sieve extension can be used to edit mail filters.
|
||||
* .be domains now offer DNSSEC options supported by the TLD
|
||||
* The daily backup will now email the administrator if there is a problem.
|
||||
* Expiring TLS certificates are now automatically renewed via Let's Encrypt.
|
||||
* File ownership for installed Roundcube files is fixed.
|
||||
* Typos fixed.
|
||||
|
||||
v0.15a (January 9, 2016)
|
||||
------------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* Sending mail through Exchange/ActiveSync (Z-Push) had been broken since v0.14 in some setups. This is now fixed.
|
||||
|
||||
v0.15 (January 1, 2016)
|
||||
-----------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* Updated Roundcube to version 1.1.3.
|
||||
* Auto-create aliases for abuse@, as required by RFC2142.
|
||||
* The DANE TLSA record is changed to use the certificate subject public key rather than the whole certificate, which means the record remains valid after certificate changes (so long as the private key remains the same, which it does for us).
|
||||
|
||||
Control panel:
|
||||
|
||||
* When IPv6 is enabled, check that system services are accessible over IPv6 too, that the box's hostname resolves over IPv6, and that reverse DNS is setup correctly for IPv6.
|
||||
* Explanatory text for setting up secondary nameserver is added/fixed.
|
||||
* DNS checks now have a timeout in case a DNS server is not responding, so the checks don't stall indefinitely.
|
||||
* Better messages if external DNS is used and, weirdly, custom secondary nameservers are set.
|
||||
* Add POP to the mail client settings documentation.
|
||||
* The box's IP address is added to the fail2ban whitelist so that the status checks don't trigger the machine banning itself, which results in the status checks showing services down even though they are running.
|
||||
* For SSL certificates, rather than asking you what country you are in during setup, ask at the time a CSR is generated. The default system self-signed certificate now omits a country in the subject (it was never needed). The CSR_COUNTRY Mail-in-a-Box setting is dropped entirely.
|
||||
|
||||
System:
|
||||
|
||||
* Nightly backups and system status checks are now moved to 3am in the system's timezone.
|
||||
* fail2ban's recidive jail is now active, which guards against persistent brute force login attacks over long periods of time.
|
||||
* Setup (first run only) now asks for your timezone to set the system time.
|
||||
* The Exchange/ActiveSync server is now taken offline during nightly backups (along with SMTP and IMAP).
|
||||
* The machine's random number generator (/dev/urandom) is now seeded with Ubuntu Pollinate and a blocking read on /dev/random.
|
||||
* DNSSEC key generation during install now uses /dev/urandom (instead of /dev/random), which is faster.
|
||||
* The $STORAGE_ROOT/ssl directory is flattened by a migration script and the system SSL certificate path is now a symlink to the actual certificate.
|
||||
* If ownCloud sends out email, it will use the box's administrative address now (admin@yourboxname).
|
||||
* Z-Push (Exchange/ActiveSync) logs now exclude warnings and are now rotated to save disk space.
|
||||
* Fix pip command that might have not installed all necessary Python packages.
|
||||
* The control panel and backup would not work on Google Compute Engine because GCE installs a conflicting boto package.
|
||||
* Added a new command `management/backup.py --restore` to restore files from a backup to a target directory (command line arguments are passed to `duplicity restore`).
|
||||
|
||||
v0.14 (November 4, 2015)
|
||||
------------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* Spamassassin's network-based tests (Pyzor, others) and DKIM tests are now enabled. (Pyzor had always been installed but was not active due to a misconfiguration.)
|
||||
* Moving spam out of the Spam folder and into Trash would incorrectly train Spamassassin that those messages were not spam.
|
||||
* Automatically create the Sent and Archive folders for new users.
|
||||
* The HTML5_Notifier plugin for Roundcube is now included, which when turned on in Roundcube settings provides desktop notifications for new mail.
|
||||
* The Exchange/ActiveSync backend Z-Push has been updated to fix a problem with CC'd emails not being sent to the CC recipients.
|
||||
|
||||
Calender/Contacts:
|
||||
|
||||
* CalDAV/CardDAV and Exchange/ActiveSync for calendar/contacts wasn't working in some network configurations.
|
||||
|
||||
Web:
|
||||
|
||||
* When a new domain is added to the box, rather than applying a new self-signed certificate for that domain, the SSL certificate for the box's primary hostname will be used instead.
|
||||
* If a custom DNS record is set on a domain or 'www'+domain, web would not be served for that domain. If the custom DNS record is just the box's IP address, that's a configuration mistake, but allow it and let web continue to be served.
|
||||
* Accommodate really long domain names by increasing an nginx setting.
|
||||
|
||||
Control panel:
|
||||
|
||||
* Added an option to check for new Mail-in-a-Box versions within status checks. It is off by default so that boxes don't "phone home" without permission.
|
||||
* Added a random password generator on the users page to simplify creating new accounts.
|
||||
* When S3 backup credentials are set, the credentials are now no longer ever sent back from the box to the client, for better security.
|
||||
* Fixed the jumpiness when a modal is displayed.
|
||||
* Focus is put into the login form fields when the login form is displayed.
|
||||
* Status checks now include a warning if a custom DNS record has been set on a domain that would normally serve web and as a result that domain no longer is serving web.
|
||||
* Status checks now check that secondary nameservers, if specified, are actually serving the domains.
|
||||
* Some errors in the control panel when there is invalid data in the database or an improperly named archived user account have been suppressed.
|
||||
* Added subresource integrity attributes to all remotely-sourced resources (i.e. via CDNs) to guard against CDNs being used as an attack vector.
|
||||
|
||||
System:
|
||||
|
||||
* Tweaks to fail2ban settings.
|
||||
* Fixed a spurrious warning while installing munin.
|
||||
|
||||
v0.13b (August 30, 2015)
|
||||
------------------------
|
||||
|
||||
Another ownCloud 8.1.1 issue was found. New installations left ownCloud improperly setup ("You are accessing the server from an untrusted domain."). Upgrading to this version will fix that.
|
||||
|
||||
v0.13a (August 23, 2015)
|
||||
------------------------
|
||||
|
||||
Note: v0.13 (no 'a', August 19, 2015) was pulled immediately due to an ownCloud bug that prevented upgrades. v0.13a works around that problem.
|
||||
|
||||
Mail:
|
||||
|
||||
* Outbound mail headers (the Recieved: header) are tweaked to possibly improve deliverability.
|
||||
* Some MIME messages would hang Roundcube due to a missing package.
|
||||
* The users permitted to send as an alias can now be different from where an alias forwards to.
|
||||
|
||||
DNS:
|
||||
|
||||
* The secondary nameservers option in the control panel now accepts more than one nameserver and a special xfr:IP format to specify zone-transfer-only IP addresses.
|
||||
* A TLSA record is added for HTTPS for DNSSEC-aware clients that support it.
|
||||
|
||||
System:
|
||||
|
||||
* Backups can now be turned off, or stored in Amazon S3, through new control panel options.
|
||||
* Munin was not working on machines confused about their hostname and had lots of errors related to PANGO, NTP peers and network interfaces that were not up.
|
||||
* ownCloud updated to version 8.1.1 (with upgrade work-around), its memcached caching enabled.
|
||||
* When upgrading, network checks like blocked port 25 are now skipped.
|
||||
* Tweaks to the intrusion detection rules for IMAP.
|
||||
* Mail-in-a-Box's setup is a lot quieter, hiding lots of irrelevant messages.
|
||||
|
||||
Control panel:
|
||||
|
||||
* SSL certificate checks were failing on OVH/OpenVZ servers due to missing /dev/stdin.
|
||||
* Improve the sort order of the domains in the status checks.
|
||||
* Some links in the control panel were only working in Chrome.
|
||||
|
||||
v0.12c (July 19, 2015)
|
||||
----------------------
|
||||
|
||||
v0.12c was posted to work around the current Sourceforge.net outage: pyzor's remote server is now hard-coded rather than accessing a file hosted on Sourceforge, and roundcube is now downloaded from a Mail-in-a-Box mirror rather than from Sourceforge.
|
||||
|
||||
v0.12b (July 4, 2015)
|
||||
---------------------
|
||||
|
||||
This version corrects a minor regression in v0.12 related to creating aliases targetting multiple addresses.
|
||||
|
||||
v0.12 (July 3, 2015)
|
||||
--------------------
|
||||
|
||||
This is a minor update to v0.11, which was a major update. Please read v0.11's advisories.
|
||||
|
||||
* The administrator@ alias was incorrectly created starting with v0.11. If your first install was v0.11, check that the administrator@ alias forwards mail to you.
|
||||
* Intrusion detection rules (fail2ban) are relaxed (i.e. less is blocked).
|
||||
* SSL certificates could not be installed for the new automatic 'www.' redirect domains.
|
||||
* PHP's default character encoding is changed from no default to UTF8. The effect of this change is unclear but should prevent possible future text conversion issues.
|
||||
* User-installed SSL private keys in the BEGIN PRIVATE KEY format were not accepted.
|
||||
* SSL certificates with SAN domains with IDNA encoding were broken in v0.11.
|
||||
* Some IDNA functionality was using IDNA 2003 rather than IDNA 2008.
|
||||
|
||||
v0.11b (June 29, 2015)
|
||||
----------------------
|
||||
|
||||
v0.11b was posted shortly after the initial posting of v0.11 to correct a missing dependency for the new PPA.
|
||||
|
||||
v0.11 (June 29, 2015)
|
||||
---------------------
|
||||
|
||||
Advisories:
|
||||
* Users can no longer spoof arbitrary email addresses in outbound mail. When sending mail, the email address configured in your mail client must match the SMTP login username being used, or the email address must be an alias with the SMTP login username listed as one of the alias's targets.
|
||||
* This update replaces your DKIM signing key with a stronger key. Because of DNS caching/propagation, mail sent within a few hours after this update could be marked as spam by recipients. If you use External DNS, you will need to update your DNS records.
|
||||
* The box will now install software from a new Mail-in-a-Box PPA on Launchpad.net, where we are distributing two of our own packages: a patched postgrey and dovecot-lucene.
|
||||
|
||||
Mail:
|
||||
* Greylisting will now let some reputable senders pass through immediately.
|
||||
* Searching mail (via IMAP) will now be much faster using the dovecot lucene full text search plugin.
|
||||
* Users can no longer spoof arbitrary email addresses in outbound mail (see above).
|
||||
* Fix for deleting admin@ and postmaster@ addresses.
|
||||
* Roundcube is updated to version 1.1.2, plugins updated.
|
||||
* Exchange/ActiveSync autoconfiguration was not working on all devices (e.g. iPhone) because of a case-sensitive URL.
|
||||
* The DKIM signing key has been increased to 2048 bits, from 1024, replacing the existing key.
|
||||
|
||||
Web:
|
||||
* 'www' subdomains now automatically redirect to their parent domain (but you'll need to install an SSL certificate).
|
||||
* OCSP no longer uses Google Public DNS.
|
||||
* The installed PHP version is no longer exposed through HTTP response headers, for better security.
|
||||
|
||||
DNS:
|
||||
* Default IPv6 AAAA records were missing since version 0.09.
|
||||
|
||||
Control panel:
|
||||
* Resetting a user's password now forces them to log in again everywhere.
|
||||
* Status checks were not working if an ssh server was not installed.
|
||||
* SSL certificate validation now uses the Python cryptography module in some places where openssl was used.
|
||||
* There is a new tab to show the installed version of Mail-in-a-Box and to fetch the latest released version.
|
||||
|
||||
System:
|
||||
* The munin system monitoring tool is now installed and accessible at /admin/munin.
|
||||
* ownCloud updated to version 8.0.4. The ownCloud installation step now is reslient to download problems. The ownCloud configuration file is now stored in STORAGE_ROOT to fix loss of data when moving STORAGE_ROOT to a new machine.
|
||||
* The setup scripts now run `apt-get update` prior to installing anything to ensure the apt database is in sync with the packages actually available.
|
||||
|
||||
|
||||
v0.10 (June 1, 2015)
|
||||
--------------------
|
||||
|
||||
* SMTP Submission (port 587) began offering the insecure SSLv3 protocol due to a misconfiguration in the previous version.
|
||||
* Roundcube now allows persistent logins using Roundcube-Persistent-Login-Plugin.
|
||||
* ownCloud is updated to version 8.0.3.
|
||||
* SPF records for non-mail domains were tightened.
|
||||
* The minimum greylisting delay has been reduced from 5 minutes to 3 minutes.
|
||||
* Users and aliases weren't working if they were entered with any uppercase letters. Now only lowercase is allowed.
|
||||
* After installing an SSL certificate from the control panel, the page wasn't being refreshed.
|
||||
* Backups broke if the box's hostname was changed after installation.
|
||||
* Dotfiles (i.e. .svn) stored in ownCloud Files were not accessible from ownCloud's mobile/desktop clients.
|
||||
* Fix broken install on OVH VPS's.
|
||||
|
||||
|
||||
v0.09 (May 8, 2015)
|
||||
-------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* Spam checking is now performed on messages larger than the previous limit of 64KB.
|
||||
* POP3S is now enabled (port 995).
|
||||
* Roundcube is updated to version 1.1.1.
|
||||
* Minor security improvements (more mail headers with user agent info are anonymized; crypto settings were tightened).
|
||||
|
||||
ownCloud:
|
||||
|
||||
* Downloading files you uploaded to ownCloud broke because of a change in ownCloud 8.
|
||||
|
||||
DNS:
|
||||
|
||||
* Internationalized Domain Names (IDNs) should now work in email. If you had custom DNS or custom web settings for internationalized domains, check that they are still working.
|
||||
* It is now possible to set multiple TXT and other types of records on the same domain in the control panel.
|
||||
* The custom DNS API was completely rewritten to support setting multiple records of the same type on a domain. Any existing client code using the DNS API will have to be rewritten. (Existing code will just get 404s back.)
|
||||
* On some systems the `nsd` service failed to start if network inferfaces were not ready.
|
||||
|
||||
System / Control Panel:
|
||||
|
||||
* In order to guard against misconfiguration that can lead to domain control validation hijacking, email addresses that begin with admin, administrator, postmaster, hostmaster, and webmaster can no longer be used for (new) mail user accounts, and aliases for these addresses may direct mail only to the box's administrator(s).
|
||||
* Backups now use duplicity's built-in gpg symmetric AES256 encryption rather than my home-brewed encryption. Old backups will be incorporated inside the first backup after this update but then deleted from disk (i.e. your backups from the previous few days will be backed up).
|
||||
* There was a race condition between backups and the new nightly status checks.
|
||||
* The control panel would sometimes lock up with an unnecessary loading indicator.
|
||||
* You can no longer delete your own account from the control panel.
|
||||
|
||||
Setup:
|
||||
|
||||
* All Mail-in-a-Box release tags are now signed on github, instructions for verifying the signature are added to the README, and the integrity of some packages downloaded during setup is now verified against a SHA1 hash stored in the tag itself.
|
||||
* Bugs in first user account creation were fixed.
|
||||
|
||||
v0.08 (April 1, 2015)
|
||||
---------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* The Roundcube vacation_sieve plugin by @arodier is now installed to make it easier to set vacation auto-reply messages from within Roundcube.
|
||||
* Authentication-Results headers for DMARC, added in v0.07, were mistakenly added for outbound mail --- that's now removed.
|
||||
* The Trash folder is now created automatically for new mail accounts, addressing a Roundcube error.
|
||||
|
||||
DNS:
|
||||
|
||||
* Custom DNS TXT records were not always working and they can now override the default SPF, DKIM, and DMARC records.
|
||||
|
||||
System:
|
||||
|
||||
* ownCloud updated to version 8.0.2.
|
||||
* Brute-force SSH and IMAP login attempts are now prevented by properly configuring fail2ban.
|
||||
* Status checks are run each night and any changes from night to night are emailed to the box administrator (the first user account).
|
||||
|
||||
Control panel:
|
||||
|
||||
* The new check that system services are running mistakenly checked that the Dovecot Managesieve service is publicly accessible. Although the service binds to the public network interface we don't open the port in ufw. On some machines it seems that ufw blocks the connection from the status checks (which seems correct) and on some machines (mine) it doesn't, which is why I didn't notice the problem.
|
||||
* The current backup chain will now try to predict how many days until it is deleted (always at least 3 days after the next full backup).
|
||||
* The list of aliases that forward to a user are removed from the Mail Users page because when there are many alises it is slow and times-out.
|
||||
* Some status check errors are turned into warnings, especially those that might not apply if External DNS is used.
|
||||
|
||||
v0.07 (February 28, 2015)
|
||||
-------------------------
|
||||
|
||||
Mail:
|
||||
|
||||
* If the box manages mail for a domain and a subdomain of that domain, outbound mail from the subdomain was not DKIM-signed and would therefore fail DMARC tests on the receiving end, possibly result in the mail heading into spam folders.
|
||||
* Auto-configuration for Mozilla Thunderbird, Evolution, KMail, and Kontact is now available.
|
||||
* Domains that only have a catch-all alias or domain alias no longer automatically create/require admin@ and postmaster@ addresses since they'll forward anyway.
|
||||
* Roundcube is updated to version 1.1.0.
|
||||
* Authentication-Results headers for DMARC are now added to incoming mail.
|
||||
|
||||
DNS:
|
||||
|
||||
* If a custom CNAME record is set on a 'www' subdomain, the default A/AAAA records were preventing the CNAME from working.
|
||||
* If a custom DNS A record overrides one provided by the box, the a corresponding default IPv6 record by the box is removed since it will probably be incorrect.
|
||||
* Internationalized domain names (IDNs) are now supported for DNS and web, but email is not yet tested.
|
||||
|
||||
Web:
|
||||
|
||||
* Static websites now deny access to certain dot (.) files and directories which typically have sensitive info: .ht*, .svn*, .git*, .hg*, .bzr*.
|
||||
* The nginx server no longer reports its version and OS for better privacy.
|
||||
* The HTTP->HTTPS redirect is now more efficient.
|
||||
* When serving a 'www.' domain, reuse the SSL certificate for the parent domain if it covers the 'www' subdomain too
|
||||
* If a custom DNS CNAME record is set on a domain, don't offer to put a website on that domain. (Same logic already applies to custom A/AAAA records.)
|
||||
|
||||
Control panel:
|
||||
|
||||
* Status checks now check that system services are actually running by pinging each port that should have something running on it.
|
||||
* The status checks are now parallelized so they may be a little faster.
|
||||
* The status check for MX records now allow any priority, in case an unusual setup is required.
|
||||
* The interface for setting website domain-specific directories is simplified.
|
||||
* The mail guide now says that to use Outlook, Outlook 2007 or later on Windows 7 and later is required.
|
||||
* External DNS settings now skip the special "_secondary_nameserver" key which is used for storing secondary NS information.
|
||||
|
||||
Setup:
|
||||
|
||||
* Install cron if it isn't already installed.
|
||||
* Fix a units problem in the minimum memory check.
|
||||
* If you override the STORAGE_ROOT, your setting will now persist if you re-run setup.
|
||||
* Hangs due to apt wanting the user to resolve a conflict should now be fixed (apt will just clobber the problematic file now).
|
||||
|
||||
v0.06 (January 4, 2015)
|
||||
-----------------------
|
||||
|
||||
@@ -124,4 +895,4 @@ v0.02 (September 21, 2014)
|
||||
v0.01 (August 19, 2014)
|
||||
-----------------------
|
||||
|
||||
First release.
|
||||
First versioned release after a year of unversioned development.
|
||||
|
||||
48
CODE_OF_CONDUCT.md
Normal file
48
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# Mail-in-a-Box Code of Conduct
|
||||
|
||||
Mail-in-a-Box is an open source community project about working, as a group, to empower ourselves and others to have control over our own digital communications. Just as we hope to increase technological diversity on the Internet through decentralization, we also believe that diverse viewpoints and voices among our community members foster innovation and creative solutions to the challenges we face.
|
||||
|
||||
We are committed to providing a safe, welcoming, and harrassment-free space for collaboration, for everyone, without regard to age, disability, economic situation, ethnicity, gender identity and expression, language fluency, level of knowledge or experience, nationality, personal appearance, race, religion, sexual identity and orientation, or any other attribute. Community comes first. This policy supersedes all other project goals.
|
||||
|
||||
The maintainers of Mail-in-a-Box share the dual responsibility of leading by example and enforcing these policies as necessary to maintain an open and welcoming environment. All community members should be excellent to each other.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies to all places where Mail-in-a-Box community activity is ocurring, including on GitHub, in discussion forums, on Slack, on social media, and in real life. The Code of Conduct applies not only on websites/at events run by the Mail-in-a-Box community (e.g. our GitHub organization, our Slack team) but also at any other location where the Mail-in-a-Box community is present (e.g. in issues of other GitHub organizations where Mail-in-a-Box community members are discussing problems related to Mail-in-a-Box, or real-life professional conferences), or whenever a Mail-in-a-Box community member is representing Mail-in-a-Box to the public at large or acting on behalf of Mail-in-a-Box.
|
||||
|
||||
This code does not apply to activity on a server running Mail-in-a-Box software, unless your server is hosting a service for the Mail-in-a-Box community at large.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Showing empathy towards other community members
|
||||
* Making room for new and quieter voices
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or advances
|
||||
* Trolling, insulting/derogatory/unwelcome comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic address, without explicit permission
|
||||
* Aggressive and micro-aggressive behavior, such as unconstructive criticism, providing corrections that do not improve the conversation (sometimes referred to as "well actually"s), repeatedly interrupting or talking over someone else, feigning surprise at someone's lack of knowledge or awareness about a topic, or subtle prejudice (for example, comments like "That's so easy my grandmother could do it.", which is prejudicial toward grandmothers).
|
||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
* Retaliating against anyone who reports a violation of this code.
|
||||
|
||||
We will not tolerate harassment. Harassment is any unwelcome or hostile behavior towards another person for any reason. This includes, but is not limited to, offensive verbal comments related to personal characteristics or choices, sexual images or comments, deliberate intimidation, bullying, stalking, following, harassing photography or recording, sustained disruption of discussion or events, nonconsensual publication of private comments, inappropriate physical contact, or unwelcome sexual attention. Conduct need not be intentional to be harassment.
|
||||
|
||||
## Enforcement
|
||||
|
||||
We will remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not consistent with this Code of Conduct. We may ban, temporarily or permanently, any contributor for violating this code, when appropriate.
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project lead, [Joshua Tauberer](https://razor.occams.info/). All reports will be treated confidentially, impartially, consistently, and swiftly.
|
||||
|
||||
Because the need for confidentiality for all parties involved in an enforcement action outweighs the goals of openness, limited information will be shared with the Mail-in-a-Box community regarding enforcement actions that have taken place.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant, version 1.4](http://contributor-covenant.org/version/1/4) and the code of conduct of [Code for DC](http://codefordc.org/resources/codeofconduct.html).
|
||||
|
||||
@@ -1,3 +1,50 @@
|
||||
# Contributing
|
||||
|
||||
Mail-in-a-Box is an open source project. Your contributions and pull requests are welcome.
|
||||
|
||||
## Development
|
||||
|
||||
To start developing Mail-in-a-Box, [clone the repository](https://github.com/mail-in-a-box/mailinabox) and familiarize yourself with the code.
|
||||
|
||||
$ git clone https://github.com/mail-in-a-box/mailinabox
|
||||
|
||||
### Vagrant and VirtualBox
|
||||
|
||||
We recommend you use [Vagrant](https://www.vagrantup.com/intro/getting-started/install.html) and [VirtualBox](https://www.virtualbox.org/wiki/Downloads) for development. Please install them first.
|
||||
|
||||
With Vagrant set up, the following should boot up Mail-in-a-Box inside a virtual machine:
|
||||
|
||||
$ vagrant up --provision
|
||||
|
||||
_If you're seeing an error message about your *IP address being listed in the Spamhaus Block List*, simply uncomment the `export SKIP_NETWORK_CHECKS=1` line in `Vagrantfile`. It's normal, you're probably using a dynamic IP address assigned by your Internet provider–they're almost all listed._
|
||||
|
||||
### 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:
|
||||
|
||||
$ echo "192.168.50.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`.
|
||||
|
||||
### Making changes
|
||||
|
||||
Your working copy of Mail-in-a-Box will be mounted inside your VM at `/vagrant`. Any change you make locally will appear inside your VM automatically.
|
||||
|
||||
Running `vagrant up --provision` again will repeat the installation with your modifications.
|
||||
|
||||
Alternatively, you can also ssh into the VM using:
|
||||
|
||||
$ vagrant ssh
|
||||
|
||||
Once inside the VM, you can re-run individual parts of the setup like in this example:
|
||||
|
||||
vm$ cd /vagrant
|
||||
vm$ sudo setup/owncloud.sh # replace with script you'd like to re-run
|
||||
|
||||
### Tests
|
||||
|
||||
Mail-in-a-Box needs more tests. If you're still looking for a way to help out, writing and contributing tests would be a great start!
|
||||
|
||||
## Public domain
|
||||
|
||||
This project is in the public domain. Copyright and related rights in the work worldwide are waived through the [CC0 1.0 Universal public domain dedication][CC0]. See the LICENSE file in this directory.
|
||||
@@ -5,3 +52,7 @@ This project is in the public domain. Copyright and related rights in the work w
|
||||
All contributions to this project must be released under the same CC0 wavier. By submitting a pull request or patch, you are agreeing to comply with this waiver of copyright interest.
|
||||
|
||||
[CC0]: http://creativecommons.org/publicdomain/zero/1.0/
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
This project has a [Code of Conduct](CODE_OF_CONDUCT.md). Please review it when joining our community.
|
||||
|
||||
85
README.md
85
README.md
@@ -9,29 +9,88 @@ Mail-in-a-Box helps individuals take back control of their email by defining a o
|
||||
|
||||
* * *
|
||||
|
||||
I am trying to:
|
||||
Our goals are to:
|
||||
|
||||
* Make deploying a good mail server easy.
|
||||
* Promote [decentralization](http://redecentralize.org/), innovation, and privacy on the web.
|
||||
* Have automated, auditable, and [idempotent](http://sharknet.us/2014/02/01/automated-configuration-management-challenges-with-idempotency/) configuration.
|
||||
* **Not** be a mail server that the NSA cannot hack.
|
||||
* **Not** be customizable by power users.
|
||||
* Have automated, auditable, and [idempotent](https://sharknet.us/2014/02/01/automated-configuration-management-challenges-with-idempotency/) configuration.
|
||||
* **Not** make a totally unhackable, NSA-proof server.
|
||||
* **Not** make something customizable by power users.
|
||||
|
||||
The long-term goal is to have this be a one-click email appliance with *no* user-configurable setup options.
|
||||
|
||||
For more background, see [The Rationale](https://github.com/mail-in-a-box/mailinabox/wiki).
|
||||
|
||||
This setup is what has been powering my own personal email since September 2013.
|
||||
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
|
||||
-------
|
||||
|
||||
Mail-in-a-Box turns a fresh Ubuntu 14.04 LTS 64-bit machine into a working mail server, including SMTP ([postfix](http://www.postfix.org/)), IMAP ([dovecot](http://dovecot.org/)), Exchange ActiveSync ([z-push](https://github.com/fmbiete/Z-Push-contrib)), webmail ([Roundcube](http://roundcube.net/)), spam filtering ([spamassassin](https://spamassassin.apache.org/)), greylisting ([postgrey](http://postgrey.schweikert.ch/)), CardDAV/CalDAV ([ownCloud](http://owncloud.org/)), DNS, [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), [SSHFP](https://tools.ietf.org/html/rfc4255), and basic system services like a firewall, intrusion protection, and setting the system clock.
|
||||
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".
|
||||
|
||||
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/))
|
||||
* Webmail ([Roundcube](http://roundcube.net/)), static website hosting ([nginx](http://nginx.org/))
|
||||
* Spam filtering ([spamassassin](https://spamassassin.apache.org/)), 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
|
||||
* 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/))
|
||||
|
||||
It also includes:
|
||||
|
||||
* A control panel and API for adding/removing mail users, aliases, custom DNS records, etc. and detailed system monitoring.
|
||||
|
||||
For more information on how Mail-in-a-Box handles your privacy, see the [security details page](security.md).
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
See the [setup guide](https://mailinabox.email/guide.html) for detailed, user-friendly instructions.
|
||||
|
||||
For experts, start with a completely fresh (really, I mean it) Ubuntu 18.04 LTS 64-bit machine. On the machine...
|
||||
|
||||
Clone this repository:
|
||||
|
||||
$ git clone https://github.com/mail-in-a-box/mailinabox
|
||||
$ cd mailinabox
|
||||
|
||||
_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.42
|
||||
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.42
|
||||
|
||||
Begin the installation.
|
||||
|
||||
$ sudo setup/start.sh
|
||||
|
||||
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.
|
||||
|
||||
Contributing and Development
|
||||
----------------------------
|
||||
|
||||
Mail-in-a-Box is an open source project. Your contributions and pull requests are welcome. See [CONTRIBUTING](CONTRIBUTING.md) to get started.
|
||||
|
||||
|
||||
The Acknowledgements
|
||||
--------------------
|
||||
|
||||
This project was inspired in part by the ["NSA-proof your email in 2 hours"](http://sealedabstract.com/code/nsa-proof-your-e-mail-in-2-hours/) blog post by Drew Crawford, [Sovereign](https://github.com/al3x/sovereign) by Alex Payne, and conversations with <a href="http://twitter.com/shevski" target="_blank">@shevski</a>, <a href="https://github.com/konklone" target="_blank">@konklone</a>, and <a href="https://github.com/gregelin" target="_blank">@GregElin</a>.
|
||||
This project was inspired in part by the ["NSA-proof your email in 2 hours"](http://sealedabstract.com/code/nsa-proof-your-e-mail-in-2-hours/) blog post by Drew Crawford, [Sovereign](https://github.com/sovereign/sovereign) by Alex Payne, and conversations with <a href="https://twitter.com/shevski" target="_blank">@shevski</a>, <a href="https://github.com/konklone" target="_blank">@konklone</a>, and <a href="https://github.com/gregelin" target="_blank">@GregElin</a>.
|
||||
|
||||
Mail-in-a-Box is similar to [iRedMail](http://www.iredmail.org/) and [Modoboa](https://github.com/tonioo/modoboa).
|
||||
|
||||
@@ -39,5 +98,7 @@ The History
|
||||
-----------
|
||||
|
||||
* In 2007 I wrote a relatively popular Mozilla Thunderbird extension that added client-side SPF and DKIM checks to mail to warn users about possible phishing: [add-on page](https://addons.mozilla.org/en-us/thunderbird/addon/sender-verification-anti-phish/), [source](https://github.com/JoshData/thunderbird-spf).
|
||||
* In August 2013 I began Mail-in-a-Box by combining my own mail server configuration with the setup in ["NSA-proof your email in 2 hours"](http://sealedabstract.com/code/nsa-proof-your-e-mail-in-2-hours/) and making the setup steps reproducible with bash scripts.
|
||||
* Mail-in-a-Box was a semifinalist in the 2014 [Knight News Challenge](https://www.newschallenge.org/challenge/2014/submissions/mail-in-a-box), but it was not selected as a winner.
|
||||
* Mail-in-a-Box hit the front page of Hacker News in [April](https://news.ycombinator.com/item?id=7634514) and [September](https://news.ycombinator.com/item?id=8276171) 2014.
|
||||
* Mail-in-a-Box hit the front page of Hacker News in [April](https://news.ycombinator.com/item?id=7634514) 2014, [September](https://news.ycombinator.com/item?id=8276171) 2014, [May](https://news.ycombinator.com/item?id=9624267) 2015, and [November](https://news.ycombinator.com/item?id=13050500) 2016.
|
||||
* FastCompany mentioned Mail-in-a-Box a [roundup of privacy projects](http://www.fastcompany.com/3047645/your-own-private-cloud) on June 26, 2015.
|
||||
|
||||
12
Vagrantfile
vendored
12
Vagrantfile
vendored
@@ -2,27 +2,23 @@
|
||||
# vi: set ft=ruby :
|
||||
|
||||
Vagrant.configure("2") do |config|
|
||||
config.vm.box = "ubuntu14.04"
|
||||
config.vm.box_url = "http://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box"
|
||||
config.vm.box = "ubuntu/bionic64"
|
||||
|
||||
# Network config: Since it's a mail server, the machine must be connected
|
||||
# to the public web. However, we currently don't want to expose SSH since
|
||||
# the machine's box will let anyone log into it. So instead we'll put the
|
||||
# machine on a private network.
|
||||
config.vm.hostname = "mailinabox"
|
||||
config.vm.hostname = "mailinabox.lan"
|
||||
config.vm.network "private_network", ip: "192.168.50.4"
|
||||
|
||||
config.vm.provision :shell, :inline => <<-SH
|
||||
# Set environment variables so that the setup script does
|
||||
# not ask any questions during provisioning. We'll let the
|
||||
# machine figure out its own public IP and it'll take a
|
||||
# subdomain on our justtesting.email domain so we can get
|
||||
# started quickly.
|
||||
# machine figure out its own public IP.
|
||||
export NONINTERACTIVE=1
|
||||
export PUBLIC_IP=auto
|
||||
export PUBLIC_IPV6=auto
|
||||
export PRIMARY_HOSTNAME=auto-easy
|
||||
export CSR_COUNTRY=US
|
||||
export PRIMARY_HOSTNAME=auto
|
||||
#export SKIP_NETWORK_CHECKS=1
|
||||
|
||||
# Start the setup script.
|
||||
|
||||
63
conf/dovecot-mailboxes.conf
Normal file
63
conf/dovecot-mailboxes.conf
Normal file
@@ -0,0 +1,63 @@
|
||||
## NOTE: This file is automatically generated by Mail-in-a-Box.
|
||||
## Do not edit this file. It is continually updated by
|
||||
## Mail-in-a-Box and your changes will be lost.
|
||||
##
|
||||
## Mail-in-a-Box machines are not meant to be modified.
|
||||
## If you modify any system configuration you are on
|
||||
## your own --- please do not ask for help from us.
|
||||
|
||||
namespace inbox {
|
||||
# Automatically create & subscribe some folders.
|
||||
# * Create and subscribe the INBOX folder.
|
||||
# * Our sieve rule for spam expects that the Spam folder exists.
|
||||
# * Z-Push must be configured with the same settings in conf/zpush/backend_imap.php (#580).
|
||||
|
||||
# MUA notes:
|
||||
# * Roundcube will show an error if the user tries to delete a message before the Trash folder exists (#359).
|
||||
# * K-9 mail will poll every 90 seconds if a Drafts folder does not exist.
|
||||
# * Apple's OS X Mail app will create 'Sent Messages' if it doesn't see a folder with the \Sent flag (#571, #573) and won't be able to archive messages unless 'Archive' exists (#581).
|
||||
# * Thunderbird's default in its UI is 'Archives' (plural) but it will configure new accounts to use whatever we say here (#581).
|
||||
|
||||
# auto:
|
||||
# 'create' will automatically create this mailbox.
|
||||
# 'subscribe' will both create and subscribe to the mailbox.
|
||||
|
||||
# special_use is a space separated list of IMAP SPECIAL-USE
|
||||
# attributes as specified by RFC 6154:
|
||||
# \All \Archive \Drafts \Flagged \Junk \Sent \Trash
|
||||
|
||||
mailbox INBOX {
|
||||
auto = subscribe
|
||||
}
|
||||
mailbox Spam {
|
||||
special_use = \Junk
|
||||
auto = subscribe
|
||||
}
|
||||
mailbox Drafts {
|
||||
special_use = \Drafts
|
||||
auto = subscribe
|
||||
}
|
||||
mailbox Sent {
|
||||
special_use = \Sent
|
||||
auto = subscribe
|
||||
}
|
||||
mailbox Trash {
|
||||
special_use = \Trash
|
||||
auto = subscribe
|
||||
}
|
||||
mailbox Archive {
|
||||
special_use = \Archive
|
||||
auto = subscribe
|
||||
}
|
||||
|
||||
# dovevot's standard mailboxes configuration file marks two sent folders
|
||||
# with the \Sent attribute, just in case clients don't agree about which
|
||||
# they're using. We'll keep that, plus add Junk as an alterative for Spam.
|
||||
# These are not auto-created.
|
||||
mailbox "Sent Messages" {
|
||||
special_use = \Sent
|
||||
}
|
||||
mailbox Junk {
|
||||
special_use = \Junk
|
||||
}
|
||||
}
|
||||
22
conf/fail2ban/filter.d/dovecotimap.conf
Normal file
22
conf/fail2ban/filter.d/dovecotimap.conf
Normal file
@@ -0,0 +1,22 @@
|
||||
# Fail2Ban filter Dovecot authentication and pop3/imap server
|
||||
# For Mail-in-a-Box
|
||||
|
||||
[INCLUDES]
|
||||
|
||||
before = common.conf
|
||||
|
||||
[Definition]
|
||||
|
||||
_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*$
|
||||
|
||||
ignoreregex =
|
||||
|
||||
# DEV Notes:
|
||||
# * the first regex is essentially a copy of pam-generic.conf
|
||||
# * Probably doesn't do dovecot sql/ldap backends properly
|
||||
#
|
||||
# Author: Martin Waschbuesch
|
||||
# Daniel Black (rewrote with begin and end anchors)
|
||||
# Mail-in-a-Box (swapped session=...)
|
||||
12
conf/fail2ban/filter.d/miab-management-daemon.conf
Normal file
12
conf/fail2ban/filter.d/miab-management-daemon.conf
Normal file
@@ -0,0 +1,12 @@
|
||||
# Fail2Ban filter Mail-in-a-Box management daemon
|
||||
|
||||
[INCLUDES]
|
||||
|
||||
before = common.conf
|
||||
|
||||
[Definition]
|
||||
|
||||
_daemon = mailinabox
|
||||
|
||||
failregex = Mail-in-a-Box Management Daemon: Failed login attempt from ip <HOST> - timestamp .*
|
||||
ignoreregex =
|
||||
7
conf/fail2ban/filter.d/miab-munin.conf
Normal file
7
conf/fail2ban/filter.d/miab-munin.conf
Normal file
@@ -0,0 +1,7 @@
|
||||
[INCLUDES]
|
||||
|
||||
before = common.conf
|
||||
|
||||
[Definition]
|
||||
failregex=<HOST> - .*GET /admin/munin/.* HTTP/1.1\" 401.*
|
||||
ignoreregex =
|
||||
8
conf/fail2ban/filter.d/miab-owncloud.conf
Normal file
8
conf/fail2ban/filter.d/miab-owncloud.conf
Normal file
@@ -0,0 +1,8 @@
|
||||
[INCLUDES]
|
||||
|
||||
before = common.conf
|
||||
|
||||
[Definition]
|
||||
datepattern = %%Y-%%m-%%d %%H:%%M:%%S
|
||||
failregex=Login failed: .*Remote IP: '<HOST>[\)']
|
||||
ignoreregex =
|
||||
7
conf/fail2ban/filter.d/miab-postfix-submission.conf
Normal file
7
conf/fail2ban/filter.d/miab-postfix-submission.conf
Normal file
@@ -0,0 +1,7 @@
|
||||
[INCLUDES]
|
||||
|
||||
before = common.conf
|
||||
|
||||
[Definition]
|
||||
failregex=postfix/submission/smtpd.*warning.*\[<HOST>\]: .* authentication (failed|aborted)
|
||||
ignoreregex =
|
||||
9
conf/fail2ban/filter.d/miab-roundcube.conf
Normal file
9
conf/fail2ban/filter.d/miab-roundcube.conf
Normal file
@@ -0,0 +1,9 @@
|
||||
[INCLUDES]
|
||||
|
||||
before = common.conf
|
||||
|
||||
[Definition]
|
||||
|
||||
failregex = IMAP Error: Login failed for .*? from <HOST>\. AUTHENTICATE.*
|
||||
|
||||
ignoreregex =
|
||||
78
conf/fail2ban/jails.conf
Normal file
78
conf/fail2ban/jails.conf
Normal file
@@ -0,0 +1,78 @@
|
||||
# Fail2Ban configuration file for Mail-in-a-Box. Do not edit.
|
||||
# This file is re-generated on updates.
|
||||
|
||||
[DEFAULT]
|
||||
# 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
|
||||
# ours too. The string is substituted during installation.
|
||||
ignoreip = 127.0.0.1/8 PUBLIC_IP
|
||||
|
||||
[dovecot]
|
||||
enabled = true
|
||||
filter = dovecotimap
|
||||
logpath = /var/log/mail.log
|
||||
findtime = 30
|
||||
maxretry = 20
|
||||
|
||||
[miab-management]
|
||||
enabled = true
|
||||
filter = miab-management-daemon
|
||||
port = http,https
|
||||
logpath = /var/log/syslog
|
||||
maxretry = 20
|
||||
findtime = 30
|
||||
|
||||
[miab-munin]
|
||||
enabled = true
|
||||
port = http,https
|
||||
filter = miab-munin
|
||||
logpath = /var/log/nginx/access.log
|
||||
maxretry = 20
|
||||
findtime = 30
|
||||
|
||||
[miab-owncloud]
|
||||
enabled = true
|
||||
port = http,https
|
||||
filter = miab-owncloud
|
||||
logpath = STORAGE_ROOT/owncloud/nextcloud.log
|
||||
maxretry = 20
|
||||
findtime = 120
|
||||
|
||||
[miab-postfix587]
|
||||
enabled = true
|
||||
port = 587
|
||||
filter = miab-postfix-submission
|
||||
logpath = /var/log/mail.log
|
||||
maxretry = 20
|
||||
findtime = 30
|
||||
|
||||
[miab-roundcube]
|
||||
enabled = true
|
||||
port = http,https
|
||||
filter = miab-roundcube
|
||||
logpath = /var/log/roundcubemail/errors
|
||||
maxretry = 20
|
||||
findtime = 30
|
||||
|
||||
[recidive]
|
||||
enabled = true
|
||||
maxretry = 10
|
||||
action = iptables-allports[name=recidive]
|
||||
# In the recidive section of jail.conf the action contains:
|
||||
#
|
||||
# action = iptables-allports[name=recidive]
|
||||
# sendmail-whois-lines[name=recidive, logpath=/var/log/fail2ban.log]
|
||||
#
|
||||
# The last line on the action will sent an email to the configured address. This mail will
|
||||
# notify the administrator that someone has been repeatedly triggering one of the other jails.
|
||||
# By default we don't configure this address and no action is required from the admin anyway.
|
||||
# So the notification is ommited. This will prevent message appearing in the mail.log that mail
|
||||
# can't be delivered to fail2ban@$HOSTNAME.
|
||||
|
||||
[postfix-sasl]
|
||||
enabled = true
|
||||
|
||||
[sshd]
|
||||
enabled = true
|
||||
maxretry = 7
|
||||
bantime = 3600
|
||||
@@ -18,8 +18,6 @@
|
||||
<string>PRIMARY_HOSTNAME</string>
|
||||
<key>CalDAVPort</key>
|
||||
<real>443</real>
|
||||
<key>CalDAVPrincipalURL</key>
|
||||
<string>/cloud/remote.php/caldav/calendars/</string>
|
||||
<key>CalDAVUseSSL</key>
|
||||
<true/>
|
||||
<key>PayloadDescription</key>
|
||||
|
||||
10
conf/mailinabox.service
Normal file
10
conf/mailinabox.service
Normal file
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Mail-in-a-Box System Management Service
|
||||
After=multi-user.target
|
||||
|
||||
[Service]
|
||||
Type=idle
|
||||
ExecStart=/usr/local/lib/mailinabox/start
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -1,135 +0,0 @@
|
||||
#! /bin/sh
|
||||
### BEGIN INIT INFO
|
||||
# Provides: mailinabox
|
||||
# Required-Start: $all
|
||||
# Required-Stop: $all
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: Start and stop the Mail-in-a-Box management daemon.
|
||||
# Description: Start and stop the Mail-in-a-Box management daemon.
|
||||
### END INIT INFO
|
||||
|
||||
# Adapted from http://blog.codefront.net/2007/06/11/nginx-php-and-a-php-fastcgi-daemon-init-script/
|
||||
|
||||
PATH=/sbin:/usr/sbin:/bin:/usr/bin
|
||||
DESC="Mail-in-a-Box Management Daemon"
|
||||
NAME=mailinabox
|
||||
DAEMON=/usr/local/bin/mailinabox-daemon
|
||||
PIDFILE=/var/run/$NAME.pid
|
||||
SCRIPTNAME=/etc/init.d/$NAME
|
||||
|
||||
# Exit if the package is not installed
|
||||
[ -x "$DAEMON" ] || exit 0
|
||||
|
||||
# Set defaults.
|
||||
START=yes
|
||||
EXEC_AS_USER=root
|
||||
|
||||
# Ensure Python reads/writes files in UTF-8. If the machine
|
||||
# triggers some other locale in Python, like ASCII encoding,
|
||||
# Python may not be able to read/write files. Here and in
|
||||
# setup/start.sh (where the locale is also installed if not
|
||||
# already present).
|
||||
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
|
||||
|
||||
# Read configuration variable file if it is present
|
||||
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
|
||||
|
||||
# Load the VERBOSE setting and other rcS variables
|
||||
. /lib/init/vars.sh
|
||||
|
||||
# Define LSB log_* functions.
|
||||
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
|
||||
. /lib/lsb/init-functions
|
||||
|
||||
# If the daemon is not enabled, give the user a warning and then exit,
|
||||
# unless we are stopping the daemon
|
||||
if [ "$START" != "yes" -a "$1" != "stop" ]; then
|
||||
log_warning_msg "To enable $NAME, edit /etc/default/$NAME and set START=yes"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Process configuration
|
||||
#export ...
|
||||
DAEMON_ARGS=""
|
||||
|
||||
|
||||
do_start()
|
||||
{
|
||||
# Return
|
||||
# 0 if daemon has been started
|
||||
# 1 if daemon was already running
|
||||
# 2 if daemon could not be started
|
||||
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
|
||||
|| return 1
|
||||
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON \
|
||||
--background --make-pidfile --chuid $EXEC_AS_USER --startas $DAEMON -- \
|
||||
$DAEMON_ARGS \
|
||||
|| return 2
|
||||
}
|
||||
|
||||
do_stop()
|
||||
{
|
||||
# Return
|
||||
# 0 if daemon has been stopped
|
||||
# 1 if daemon was already stopped
|
||||
# 2 if daemon could not be stopped
|
||||
# other if a failure occurred
|
||||
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE > /dev/null # --name $DAEMON
|
||||
RETVAL="$?"
|
||||
[ "$RETVAL" = 2 ] && return 2
|
||||
# Wait for children to finish too if this is a daemon that forks
|
||||
# and if the daemon is only ever run from this initscript.
|
||||
# If the above conditions are not satisfied then add some other code
|
||||
# that waits for the process to drop all resources that could be
|
||||
# needed by services started subsequently. A last resort is to
|
||||
# sleep for some time.
|
||||
start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
|
||||
[ "$?" = 2 ] && return 2
|
||||
# Many daemons don't delete their pidfiles when they exit.
|
||||
rm -f $PIDFILE
|
||||
return "$RETVAL"
|
||||
}
|
||||
case "$1" in
|
||||
start)
|
||||
[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
|
||||
do_start
|
||||
case "$?" in
|
||||
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
|
||||
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
|
||||
esac
|
||||
;;
|
||||
stop)
|
||||
[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
|
||||
do_stop
|
||||
case "$?" in
|
||||
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
|
||||
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
|
||||
esac
|
||||
;;
|
||||
restart|force-reload)
|
||||
log_daemon_msg "Restarting $DESC" "$NAME"
|
||||
do_stop
|
||||
case "$?" in
|
||||
0|1)
|
||||
do_start
|
||||
case "$?" in
|
||||
0) log_end_msg 0 ;;
|
||||
1) log_end_msg 1 ;; # Old process is still running
|
||||
*) log_end_msg 1 ;; # Failed to start
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
# Failed to stop
|
||||
log_end_msg 1
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
|
||||
exit 3
|
||||
;;
|
||||
esac
|
||||
44
conf/mozilla-autoconfig.xml
Normal file
44
conf/mozilla-autoconfig.xml
Normal file
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0"?>
|
||||
<clientConfig version="1.1">
|
||||
<emailProvider id="PRIMARY_HOSTNAME">
|
||||
<domain>PRIMARY_HOSTNAME</domain>
|
||||
|
||||
<displayName>PRIMARY_HOSTNAME (Mail-in-a-Box)</displayName>
|
||||
<displayShortName>PRIMARY_HOSTNAME</displayShortName>
|
||||
|
||||
<incomingServer type="imap">
|
||||
<hostname>PRIMARY_HOSTNAME</hostname>
|
||||
<port>993</port>
|
||||
<socketType>SSL</socketType>
|
||||
<username>%EMAILADDRESS%</username>
|
||||
<authentication>password-cleartext</authentication>
|
||||
</incomingServer>
|
||||
|
||||
<outgoingServer type="smtp">
|
||||
<hostname>PRIMARY_HOSTNAME</hostname>
|
||||
<port>587</port>
|
||||
<socketType>STARTTLS</socketType>
|
||||
<username>%EMAILADDRESS%</username>
|
||||
<authentication>password-cleartext</authentication>
|
||||
<addThisServer>true</addThisServer>
|
||||
<useGlobalPreferredServer>true</useGlobalPreferredServer>
|
||||
</outgoingServer>
|
||||
|
||||
<documentation url="https://PRIMARY_HOSTNAME/">
|
||||
<descr lang="en">PRIMARY_HOSTNAME website.</descr>
|
||||
</documentation>
|
||||
</emailProvider>
|
||||
|
||||
<webMail>
|
||||
<loginPage url="https://PRIMARY_HOSTNAME/mail/" />
|
||||
<loginPageInfo url="https://PRIMARY_HOSTNAME/mail/" >
|
||||
<username>%EMAILADDRESS%</username>
|
||||
<usernameField id="rcmloginuser" name="_user" />
|
||||
<passwordField id="rcmloginpwd" name="_pass" />
|
||||
<loginButton id="rcmloginsubmit" />
|
||||
</loginPageInfo>
|
||||
</webMail>
|
||||
|
||||
<clientConfigUpdate url="https://PRIMARY_HOSTNAME/.well-known/autoconfig/mail/config-v1.1.xml" />
|
||||
|
||||
</clientConfig>
|
||||
10
conf/munin.service
Normal file
10
conf/munin.service
Normal file
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Munin System Monitoring Startup Script
|
||||
After=multi-user.target
|
||||
|
||||
[Service]
|
||||
Type=idle
|
||||
ExecStart=/usr/local/lib/mailinabox/munin_start.sh
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
82
conf/nginx-alldomains.conf
Normal file
82
conf/nginx-alldomains.conf
Normal file
@@ -0,0 +1,82 @@
|
||||
# Expose this directory as static files.
|
||||
root $ROOT;
|
||||
index index.html index.htm;
|
||||
|
||||
location = /robots.txt {
|
||||
log_not_found off;
|
||||
access_log off;
|
||||
}
|
||||
|
||||
location = /favicon.ico {
|
||||
log_not_found off;
|
||||
access_log off;
|
||||
}
|
||||
|
||||
location = /mailinabox.mobileconfig {
|
||||
alias /var/lib/mailinabox/mobileconfig.xml;
|
||||
}
|
||||
location = /.well-known/autoconfig/mail/config-v1.1.xml {
|
||||
alias /var/lib/mailinabox/mozilla-autoconfig.xml;
|
||||
}
|
||||
location = /mail/config-v1.1.xml {
|
||||
alias /var/lib/mailinabox/mozilla-autoconfig.xml;
|
||||
}
|
||||
|
||||
# Roundcube Webmail configuration.
|
||||
rewrite ^/mail$ /mail/ redirect;
|
||||
rewrite ^/mail/$ /mail/index.php;
|
||||
location /mail/ {
|
||||
index index.php;
|
||||
alias /usr/local/lib/roundcubemail/;
|
||||
}
|
||||
location ~ /mail/config/.* {
|
||||
# A ~-style location is needed to give this precedence over the next block.
|
||||
return 403;
|
||||
}
|
||||
location ~ /mail/.*\.php {
|
||||
# note: ~ has precendence over a regular location block
|
||||
include fastcgi_params;
|
||||
fastcgi_split_path_info ^/mail(/.*)()$;
|
||||
fastcgi_index index.php;
|
||||
fastcgi_param SCRIPT_FILENAME /usr/local/lib/roundcubemail/$fastcgi_script_name;
|
||||
fastcgi_pass php-fpm;
|
||||
|
||||
# Outgoing mail also goes through this endpoint, so increase the maximum
|
||||
# file upload limit to match the corresponding Postfix limit.
|
||||
client_max_body_size 128M;
|
||||
}
|
||||
|
||||
# Z-Push (Microsoft Exchange ActiveSync)
|
||||
location /Microsoft-Server-ActiveSync {
|
||||
include /etc/nginx/fastcgi_params;
|
||||
fastcgi_param SCRIPT_FILENAME /usr/local/lib/z-push/index.php;
|
||||
fastcgi_param PHP_VALUE "include_path=.:/usr/share/php:/usr/share/pear:/usr/share/awl/inc";
|
||||
fastcgi_read_timeout 630;
|
||||
fastcgi_pass php-fpm;
|
||||
|
||||
# Outgoing mail also goes through this endpoint, so increase the maximum
|
||||
# file upload limit to match the corresponding Postfix limit.
|
||||
client_max_body_size 128M;
|
||||
}
|
||||
location ~* ^/autodiscover/autodiscover.xml$ {
|
||||
include fastcgi_params;
|
||||
fastcgi_param SCRIPT_FILENAME /usr/local/lib/z-push/autodiscover/autodiscover.php;
|
||||
fastcgi_param PHP_VALUE "include_path=.:/usr/share/php:/usr/share/pear:/usr/share/awl/inc";
|
||||
fastcgi_pass php-fpm;
|
||||
}
|
||||
|
||||
|
||||
# ADDITIONAL DIRECTIVES HERE
|
||||
|
||||
# Disable viewing dotfiles (.htaccess, .svn, .git, etc.)
|
||||
# This block is placed at the end. Nginx's precedence rules means this block
|
||||
# takes precedence over all non-regex matches and only regex matches that
|
||||
# come after it (i.e. none of those, since this is the last one.) That means
|
||||
# we're blocking dotfiles in the static hosted sites but not the FastCGI-
|
||||
# handled locations for Nextcloud (which serves user-uploaded files that might
|
||||
# have this pattern, see #414) or some of the other services.
|
||||
location ~ /\.(ht|svn|git|hg|bzr) {
|
||||
log_not_found off;
|
||||
access_log off;
|
||||
deny all;
|
||||
}
|
||||
@@ -1,22 +1,41 @@
|
||||
# Control Panel
|
||||
# Proxy /admin to our Python based control panel daemon. It is
|
||||
# listening on IPv4 only so use an IP address and not 'localhost'.
|
||||
location /admin/assets {
|
||||
alias /usr/local/lib/mailinabox/vendor/assets;
|
||||
}
|
||||
rewrite ^/admin$ /admin/;
|
||||
rewrite ^/admin/munin$ /admin/munin/ redirect;
|
||||
location /admin/ {
|
||||
proxy_pass http://127.0.0.1:10222/;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
add_header X-Frame-Options "DENY";
|
||||
add_header X-Content-Type-Options nosniff;
|
||||
add_header Content-Security-Policy "frame-ancestors 'none';";
|
||||
}
|
||||
|
||||
# ownCloud configuration.
|
||||
# Nextcloud configuration.
|
||||
rewrite ^/cloud$ /cloud/ redirect;
|
||||
rewrite ^/cloud/$ /cloud/index.php;
|
||||
rewrite ^/cloud/(contacts|calendar|files)$ /cloud/index.php/apps/$1/ redirect;
|
||||
rewrite ^(/cloud/core/doc/[^\/]+/)$ $1/index.html;
|
||||
rewrite ^(/cloud/oc[sm]-provider)/$ $1/index.php redirect;
|
||||
location /cloud/ {
|
||||
alias /usr/local/lib/owncloud/;
|
||||
location ~ ^/(data|config|\.ht|db_structure\.xml|README) {
|
||||
location ~ ^/cloud/(build|tests|config|lib|3rdparty|templates|data|README)/ {
|
||||
deny all;
|
||||
}
|
||||
location ~ ^/cloud/(?:\.|autotest|occ|issue|indie|db_|console) {
|
||||
deny all;
|
||||
}
|
||||
# Enable paths for service and cloud federation discovery
|
||||
# Resolves warning in Nextcloud Settings panel
|
||||
location ~ ^/cloud/(oc[sm]-provider)?/([^/]+\.php)$ {
|
||||
index index.php;
|
||||
include fastcgi_params;
|
||||
fastcgi_param SCRIPT_FILENAME /usr/local/lib/owncloud/$1/$2;
|
||||
fastcgi_pass php-fpm;
|
||||
}
|
||||
}
|
||||
location ~ ^(/cloud)((?:/ocs)?/[^/]+\.php)(/.*)?$ {
|
||||
# note: ~ has precendence over a regular location block
|
||||
@@ -24,32 +43,34 @@
|
||||
# /cloud/index.php/apps/files/
|
||||
# /cloud/index.php/apps/files/ajax/scan.php (it's really index.php; see 6fdef379adfdeac86cc2220209bdf4eb9562268d)
|
||||
# /cloud/ocs/v1.php/apps/files_sharing/api/v1 (see #240)
|
||||
# /cloud/remote.php/webdav/yourfilehere...
|
||||
include fastcgi_params;
|
||||
fastcgi_param SCRIPT_FILENAME /usr/local/lib/owncloud/$2;
|
||||
fastcgi_param SCRIPT_NAME $1$2;
|
||||
fastcgi_param PATH_INFO $3;
|
||||
fastcgi_param MOD_X_ACCEL_REDIRECT_ENABLED on;
|
||||
fastcgi_param MOD_X_ACCEL_REDIRECT_PREFIX /owncloud-xaccel;
|
||||
fastcgi_read_timeout 630;
|
||||
fastcgi_pass php-fpm;
|
||||
error_page 403 /cloud/core/templates/403.php;
|
||||
error_page 404 /cloud/core/templates/404.php;
|
||||
client_max_body_size 1G;
|
||||
fastcgi_buffers 64 4K;
|
||||
}
|
||||
location ^~ /cloud/data {
|
||||
# In order to support MOD_X_ACCEL_REDIRECT_ENABLED, we need to expose
|
||||
# the data directory but only allow 'internal' redirects within nginx
|
||||
# so that this is not exposed to the world.
|
||||
location ^~ /owncloud-xaccel/ {
|
||||
# This directory is for MOD_X_ACCEL_REDIRECT_ENABLED. Nextcloud sends the full file
|
||||
# path on disk as a subdirectory under this virtual path.
|
||||
# We must only allow 'internal' redirects within nginx so that the filesystem
|
||||
# is not exposed to the world.
|
||||
internal;
|
||||
alias $STORAGE_ROOT/owncloud;
|
||||
alias /;
|
||||
}
|
||||
location ~ ^/((caldav|carddav|webdav).*)$ {
|
||||
# Z-Push doesn't like getting a redirect, and a plain rewrite didn't work either.
|
||||
# Properly proxying like this seems to work fine.
|
||||
proxy_pass https://$HOSTNAME/cloud/remote.php/$1;
|
||||
proxy_pass https://127.0.0.1/cloud/remote.php/$1;
|
||||
}
|
||||
rewrite ^/.well-known/host-meta /cloud/public.php?service=host-meta last;
|
||||
rewrite ^/.well-known/host-meta.json /cloud/public.php?service=host-meta-json last;
|
||||
rewrite ^/.well-known/carddav /cloud/remote.php/carddav/ redirect;
|
||||
rewrite ^/.well-known/caldav /cloud/remote.php/caldav/ redirect;
|
||||
|
||||
# ADDITIONAL DIRECTIVES HERE
|
||||
|
||||
@@ -1,75 +1,20 @@
|
||||
# from: https://gist.github.com/konklone/6532544
|
||||
###################################################################################
|
||||
# We track the Mozilla "intermediate" compatibility TLS recommendations.
|
||||
# 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_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_dhparam STORAGE_ROOT/ssl/dh2048.pem;
|
||||
|
||||
# Basically the nginx configuration I use at konklone.com.
|
||||
# I check it using https://www.ssllabs.com/ssltest/analyze.html?d=konklone.com
|
||||
#
|
||||
# To provide feedback, please tweet at @konklone or email eric@konklone.com.
|
||||
# Comments on gists don't notify the author.
|
||||
#
|
||||
# Thanks to WubTheCaptain (https://wubthecaptain.eu) for his help and ciphersuites.
|
||||
# Thanks to Ilya Grigorik (https://www.igvita.com) for constant inspiration.
|
||||
|
||||
# Path to certificate and private key.
|
||||
# The .crt may omit the root CA cert, if it's a standard CA that ships with clients.
|
||||
#ssl_certificate /path/to/unified.crt;
|
||||
#ssl_certificate_key /path/to/my-private-decrypted.key;
|
||||
|
||||
# Tell browsers to require SSL (warning: difficult to change your mind)
|
||||
add_header Strict-Transport-Security max-age=31536000;
|
||||
|
||||
# Prefer certain ciphersuites, to enforce Forward Secrecy and avoid known vulnerabilities.
|
||||
#
|
||||
# Forces forward secrecy in all browsers and clients that can use TLS,
|
||||
# but with a small exception (DES-CBC3-SHA) for IE8/XP users.
|
||||
#
|
||||
# Reference client: https://www.ssllabs.com/ssltest/analyze.html
|
||||
ssl_prefer_server_ciphers on;
|
||||
ssl_ciphers 'kEECDH+ECDSA+AES128 kEECDH+ECDSA+AES256 kEECDH+AES128 kEECDH+AES256 kEDH+AES128 kEDH+AES256 DES-CBC3-SHA +SHA !aNULL !eNULL !LOW !MD5 !EXP !DSS !PSK !SRP !kECDH !CAMELLIA !RC4 !SEED';
|
||||
|
||||
# Cut out (the old, broken) SSLv3 entirely.
|
||||
# This **excludes IE6 users** and (apparently) Yandexbot.
|
||||
# Just comment out if you need to support IE6, bless your soul.
|
||||
ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
|
||||
|
||||
# Turn on session resumption, using a 10 min cache shared across nginx processes,
|
||||
# as recommended by http://nginx.org/en/docs/http/configuring_https_servers.html
|
||||
ssl_session_cache shared:SSL:10m;
|
||||
ssl_session_timeout 10m;
|
||||
keepalive_timeout 70;
|
||||
ssl_session_cache shared:SSL:50m;
|
||||
ssl_session_timeout 1d;
|
||||
|
||||
# Buffer size of 1400 bytes fits in one MTU.
|
||||
# nginx 1.5.9+ ONLY
|
||||
#ssl_buffer_size 1400;
|
||||
ssl_buffer_size 1400;
|
||||
|
||||
# SPDY header compression (0 for none, 9 for slow/heavy compression). Preferred is 6.
|
||||
#
|
||||
# BUT: header compression is flawed and vulnerable in SPDY versions 1 - 3.
|
||||
# Disable with 0, until using a version of nginx with SPDY 4.
|
||||
spdy_headers_comp 0;
|
||||
|
||||
# Now let's really get fancy, and pre-generate a 2048 bit random parameter
|
||||
# for DH elliptic curves. If not created and specified, default is only 1024 bits.
|
||||
#
|
||||
# Generated by OpenSSL with the following command:
|
||||
# openssl dhparam -outform pem -out dhparam2048.pem 2048
|
||||
#
|
||||
# Note: raising the bits to 2048 excludes Java 6 clients. Comment out if a problem.
|
||||
ssl_dhparam STORAGE_ROOT/ssl/dh2048.pem;
|
||||
|
||||
|
||||
# OCSP stapling - means nginx will poll the CA for signed OCSP responses,
|
||||
# and send them to clients so clients don't make their own OCSP calls.
|
||||
# http://en.wikipedia.org/wiki/OCSP_stapling
|
||||
#
|
||||
# while the ssl_certificate above may omit the root cert if the CA is trusted,
|
||||
# ssl_trusted_certificate below must point to a chain of **all** certs
|
||||
# in the trust path - (your cert, intermediary certs, root cert)
|
||||
#
|
||||
# 8.8.8.8 and 8.8.4.4 below are Google's public IPv4 DNS servers.
|
||||
# nginx will use them to talk to the CA.
|
||||
ssl_stapling on;
|
||||
ssl_stapling_verify on;
|
||||
resolver 8.8.8.8 8.8.4.4 valid=86400;
|
||||
resolver 127.0.0.1 valid=86400;
|
||||
resolver_timeout 10;
|
||||
#ssl_trusted_certificate /path/to/all-certs-in-chain.crt;
|
||||
|
||||
# h/t https://gist.github.com/konklone/6532544
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
## your own --- please do not ask for help from us.
|
||||
|
||||
upstream php-fpm {
|
||||
server unix:/var/run/php5-fpm.sock;
|
||||
server unix:/var/run/php/php7.2-fpm.sock;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,87 +1,47 @@
|
||||
## $HOSTNAME
|
||||
|
||||
# Redirect all HTTP to HTTPS.
|
||||
# Redirect all HTTP to HTTPS *except* the ACME challenges (Let's Encrypt TLS certificate
|
||||
# domain validation challenges) path, which must be served over HTTP per the ACME spec
|
||||
# (due to some Apache vulnerability).
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
|
||||
server_name $HOSTNAME;
|
||||
root /tmp/invalid-path-nothing-here;
|
||||
rewrite ^/(.*)$ https://$HOSTNAME/$1 permanent;
|
||||
|
||||
# Improve privacy: Hide version an OS information on
|
||||
# error pages and in the "Server" HTTP-Header.
|
||||
server_tokens off;
|
||||
|
||||
location / {
|
||||
# Redirect using the 'return' directive and the built-in
|
||||
# variable '$request_uri' to avoid any capturing, matching
|
||||
# or evaluation of regular expressions.
|
||||
return 301 https://$HOSTNAME$request_uri;
|
||||
}
|
||||
|
||||
location /.well-known/acme-challenge/ {
|
||||
# This path must be served over HTTP for ACME domain validation.
|
||||
# We map this to a special path where our TLS cert provisioning
|
||||
# tool knows to store challenge response files.
|
||||
alias $STORAGE_ROOT/ssl/lets_encrypt/webroot/.well-known/acme-challenge/;
|
||||
}
|
||||
}
|
||||
|
||||
# The secure HTTPS server.
|
||||
server {
|
||||
listen 443 ssl;
|
||||
listen [::]:443 ssl;
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
|
||||
server_name $HOSTNAME;
|
||||
|
||||
# Improve privacy: Hide version an OS information on
|
||||
# error pages and in the "Server" HTTP-Header.
|
||||
server_tokens off;
|
||||
|
||||
ssl_certificate $SSL_CERTIFICATE;
|
||||
ssl_certificate_key $SSL_KEY;
|
||||
include /etc/nginx/nginx-ssl.conf;
|
||||
|
||||
# Expose this directory as static files.
|
||||
root $ROOT;
|
||||
index index.html index.htm;
|
||||
|
||||
location = /robots.txt {
|
||||
log_not_found off;
|
||||
access_log off;
|
||||
}
|
||||
|
||||
location = /favicon.ico {
|
||||
log_not_found off;
|
||||
access_log off;
|
||||
}
|
||||
|
||||
location = /mailinabox.mobileconfig {
|
||||
alias /var/lib/mailinabox/mobileconfig.xml;
|
||||
}
|
||||
|
||||
# Roundcube Webmail configuration.
|
||||
rewrite ^/mail$ /mail/ redirect;
|
||||
rewrite ^/mail/$ /mail/index.php;
|
||||
location /mail/ {
|
||||
index index.php;
|
||||
alias /usr/local/lib/roundcubemail/;
|
||||
}
|
||||
location ~ /mail/config/.* {
|
||||
# A ~-style location is needed to give this precedence over the next block.
|
||||
return 403;
|
||||
}
|
||||
location ~ /mail/.*\.php {
|
||||
# note: ~ has precendence over a regular location block
|
||||
include fastcgi_params;
|
||||
fastcgi_split_path_info ^/mail(/.*)()$;
|
||||
fastcgi_index index.php;
|
||||
fastcgi_param SCRIPT_FILENAME /usr/local/lib/roundcubemail/$fastcgi_script_name;
|
||||
fastcgi_pass php-fpm;
|
||||
|
||||
# Outgoing mail also goes through this endpoint, so increase the maximum
|
||||
# file upload limit to match the corresponding Postfix limit.
|
||||
client_max_body_size 128M;
|
||||
}
|
||||
|
||||
# Z-Push (Microsoft Exchange ActiveSync)
|
||||
location /Microsoft-Server-ActiveSync {
|
||||
include /etc/nginx/fastcgi_params;
|
||||
fastcgi_param SCRIPT_FILENAME /usr/local/lib/z-push/index.php;
|
||||
fastcgi_param PHP_VALUE "include_path=.:/usr/share/php:/usr/share/pear:/usr/share/awl/inc";
|
||||
fastcgi_read_timeout 630;
|
||||
fastcgi_pass php-fpm;
|
||||
|
||||
# Outgoing mail also goes through this endpoint, so increase the maximum
|
||||
# file upload limit to match the corresponding Postfix limit.
|
||||
client_max_body_size 128M;
|
||||
}
|
||||
location /autodiscover/autodiscover.xml {
|
||||
include fastcgi_params;
|
||||
fastcgi_param SCRIPT_FILENAME /usr/local/lib/z-push/autodiscover/autodiscover.php;
|
||||
fastcgi_param PHP_VALUE "include_path=.:/usr/share/php:/usr/share/pear:/usr/share/awl/inc";
|
||||
fastcgi_pass php-fpm;
|
||||
}
|
||||
|
||||
|
||||
# ADDITIONAL DIRECTIVES HERE
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
# Remove the first line of the Received: header. Note that we cannot fully remove the Received: header
|
||||
# because OpenDKIM requires that a header be present when signing outbound mail. The first line is
|
||||
# where the user's home IP address would be.
|
||||
/^\s*Received:[^\n]*(.*)/ REPLACE Received: from authenticated-user (unknown [127.0.0.1])$1
|
||||
/^\s*Received:[^\n]*(.*)/ REPLACE Received: from authenticated-user (PRIMARY_HOSTNAME [PUBLIC_IP])$1
|
||||
|
||||
# Remove other typically private information.
|
||||
/^\s*User-Agent:/ IGNORE
|
||||
/^\s*X-Enigmail:/ IGNORE
|
||||
/^\s*X-Mailer:/ IGNORE
|
||||
/^\s*X-Originating-IP:/ IGNORE
|
||||
/^\s*X-Pgp-Agent:/ IGNORE
|
||||
|
||||
# The Mime-Version header can leak the user agent too, e.g. in Mime-Version: 1.0 (Mac OS X Mail 8.1 \(2010.6\)).
|
||||
/^\s*(Mime-Version:\s*[0-9\.]+)\s.+/ REPLACE $1
|
||||
|
||||
@@ -5,11 +5,12 @@
|
||||
* Descr : Autodiscover configuration file
|
||||
************************************************/
|
||||
|
||||
define('TIMEZONE', '');
|
||||
|
||||
// Defines the base path on the server
|
||||
define('BASE_PATH', dirname($_SERVER['SCRIPT_FILENAME']). '/');
|
||||
|
||||
// The Z-Push server location for the autodiscover response
|
||||
define('SERVERURL', 'https://PRIMARY_HOSTNAME/Microsoft-Server-ActiveSync');
|
||||
define('ZPUSH_HOST', 'PRIMARY_HOSTNAME');
|
||||
|
||||
define('USE_FULLEMAIL_FOR_LOGIN', true);
|
||||
|
||||
@@ -18,6 +19,7 @@ define('LOGFILE', LOGFILEDIR . 'autodiscover.log');
|
||||
define('LOGERRORFILE', LOGFILEDIR . 'autodiscover-error.log');
|
||||
define('LOGLEVEL', LOGLEVEL_INFO);
|
||||
define('LOGUSERLEVEL', LOGLEVEL);
|
||||
$specialLogUsers = array();
|
||||
|
||||
// the backend data provider
|
||||
define('BACKEND_PROVIDER', 'BackendCombined');
|
||||
|
||||
@@ -5,10 +5,12 @@
|
||||
* Descr : CalDAV backend configuration file
|
||||
************************************************/
|
||||
|
||||
define('CALDAV_SERVER', 'https://localhost');
|
||||
define('CALDAV_PROTOCOL', 'https');
|
||||
define('CALDAV_SERVER', '127.0.0.1');
|
||||
define('CALDAV_PORT', '443');
|
||||
define('CALDAV_PATH', '/caldav/calendars/%u/');
|
||||
define('CALDAV_PERSONAL', '');
|
||||
define('CALDAV_SUPPORTS_SYNC', true);
|
||||
define('CALDAV_PERSONAL', 'PRINCIPAL');
|
||||
define('CALDAV_SUPPORTS_SYNC', false);
|
||||
define('CALDAV_MAX_SYNC_PERIOD', 2147483647);
|
||||
|
||||
?>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
|
||||
define('CARDDAV_PROTOCOL', 'https'); /* http or https */
|
||||
define('CARDDAV_SERVER', 'localhost');
|
||||
define('CARDDAV_SERVER', '127.0.0.1');
|
||||
define('CARDDAV_PORT', '443');
|
||||
define('CARDDAV_PATH', '/carddav/addressbooks/%u/');
|
||||
define('CARDDAV_DEFAULT_PATH', '/carddav/addressbooks/%u/contacts/'); /* subdirectory of the main path */
|
||||
@@ -17,7 +17,7 @@ define('CARDDAV_CONTACTS_FOLDER_NAME', '%u Addressbook');
|
||||
define('CARDDAV_SUPPORTS_SYNC', false);
|
||||
|
||||
// If the CardDAV server supports the FN attribute for searches
|
||||
// DAViCal supports it, but SabreDav, Owncloud and SOGo don't
|
||||
// DAViCal supports it, but SabreDav, Nextcloud and SOGo don't
|
||||
// Setting this to true will search by FN. If false will search by sn, givenName and email
|
||||
// It's safe to leave it as false
|
||||
define('CARDDAV_SUPPORTS_FN_SEARCH', false);
|
||||
|
||||
@@ -5,19 +5,37 @@
|
||||
* Descr : IMAP backend configuration file
|
||||
************************************************/
|
||||
|
||||
define('IMAP_SERVER', 'localhost');
|
||||
define('IMAP_SERVER', '127.0.0.1');
|
||||
define('IMAP_PORT', 993);
|
||||
define('IMAP_OPTIONS', '/ssl/norsh/novalidate-cert');
|
||||
define('IMAP_DEFAULTFROM', '');
|
||||
define('IMAP_DEFAULTFROM', 'sql');
|
||||
|
||||
// not used
|
||||
define('IMAP_FROM_SQL_DSN', '');
|
||||
define('SYSTEM_MIME_TYPES_MAPPING', '/etc/mime.types');
|
||||
define('IMAP_AUTOSEEN_ON_DELETE', false);
|
||||
define('IMAP_FOLDER_CONFIGURED', true);
|
||||
define('IMAP_FOLDER_PREFIX', '');
|
||||
define('IMAP_FOLDER_PREFIX_IN_INBOX', false);
|
||||
// see our conf/dovecot-mailboxes.conf file for IMAP special flags settings
|
||||
define('IMAP_FOLDER_INBOX', 'INBOX');
|
||||
define('IMAP_FOLDER_SENT', 'SENT');
|
||||
define('IMAP_FOLDER_DRAFT', 'DRAFTS');
|
||||
define('IMAP_FOLDER_TRASH', 'TRASH');
|
||||
define('IMAP_FOLDER_SPAM', 'SPAM');
|
||||
define('IMAP_FOLDER_ARCHIVE', 'ARCHIVE');
|
||||
|
||||
define('IMAP_INLINE_FORWARD', true);
|
||||
define('IMAP_EXCLUDED_FOLDERS', '');
|
||||
|
||||
define('IMAP_FROM_SQL_DSN', 'sqlite:STORAGE_ROOT/mail/roundcube/roundcube.sqlite');
|
||||
define('IMAP_FROM_SQL_USER', '');
|
||||
define('IMAP_FROM_SQL_PASSWORD', '');
|
||||
define('IMAP_FROM_SQL_OPTIONS', serialize(array(PDO::ATTR_PERSISTENT => true)));
|
||||
define('IMAP_FROM_SQL_QUERY', "select first_name, last_name, mail_address from users where mail_address = '#username@#domain'");
|
||||
define('IMAP_FROM_SQL_FIELDS', serialize(array('first_name', 'last_name', 'mail_address')));
|
||||
define('IMAP_FROM_SQL_FROM', '#first_name #last_name <#mail_address>');
|
||||
define('IMAP_FROM_SQL_QUERY', "SELECT name, email FROM identities i INNER JOIN users u ON i.user_id = u.user_id WHERE u.username = '#username' AND i.standard = 1 AND i.del = 0 AND i.name <> ''");
|
||||
define('IMAP_FROM_SQL_FIELDS', serialize(array('name', 'email')));
|
||||
define('IMAP_FROM_SQL_FROM', '#name <#email>');
|
||||
define('IMAP_FROM_SQL_FULLNAME', '#name');
|
||||
|
||||
// not used
|
||||
define('IMAP_FROM_LDAP_SERVER', '');
|
||||
define('IMAP_FROM_LDAP_SERVER_PORT', '389');
|
||||
define('IMAP_FROM_LDAP_USER', 'cn=zpush,ou=servers,dc=zpush,dc=org');
|
||||
@@ -26,17 +44,14 @@ define('IMAP_FROM_LDAP_BASE', 'dc=zpush,dc=org');
|
||||
define('IMAP_FROM_LDAP_QUERY', '(mail=#username@#domain)');
|
||||
define('IMAP_FROM_LDAP_FIELDS', serialize(array('givenname', 'sn', 'mail')));
|
||||
define('IMAP_FROM_LDAP_FROM', '#givenname #sn <#mail>');
|
||||
define('IMAP_FROM_LDAP_FULLNAME', '#givenname #sn');
|
||||
|
||||
|
||||
// copy outgoing mail to this folder. If not set z-push will try the default folders
|
||||
define('IMAP_SENTFOLDER', '');
|
||||
define('IMAP_INLINE_FORWARD', true);
|
||||
define('IMAP_EXCLUDED_FOLDERS', '');
|
||||
define('IMAP_SMTP_METHOD', 'sendmail');
|
||||
|
||||
global $imap_smtp_params;
|
||||
$imap_smtp_params = array('host' => 'ssl://localhost', 'port' => 587, 'auth' => true, 'username' => 'imap_username', 'password' => 'imap_password');
|
||||
$imap_smtp_params = array('host' => 'ssl://127.0.0.1', 'port' => 587, 'auth' => true, 'username' => 'imap_username', 'password' => 'imap_password');
|
||||
|
||||
define('MAIL_MIMEPART_CRLF', "\r\n");
|
||||
define('IMAP_MEETING_USE_CALDAV', true);
|
||||
|
||||
?>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import base64, os, os.path
|
||||
import base64, os, os.path, hmac
|
||||
|
||||
from flask import make_response
|
||||
|
||||
import utils
|
||||
from mailconfig import get_mail_user_privileges
|
||||
from mailconfig import get_mail_password, get_mail_user_privileges
|
||||
|
||||
DEFAULT_KEY_PATH = '/var/lib/mailinabox/api.key'
|
||||
DEFAULT_AUTH_REALM = 'Mail-in-a-Box Management Server'
|
||||
@@ -40,10 +40,12 @@ class KeyAuthService:
|
||||
with create_file_with_mode(self.key_path, 0o640) as key_file:
|
||||
key_file.write(self.key + '\n')
|
||||
|
||||
def is_authenticated(self, request, env):
|
||||
def authenticate(self, request, env):
|
||||
"""Test if the client key passed in HTTP Authorization header matches the service key
|
||||
or if the or username/password passed in the header matches an administrator user.
|
||||
Returns 'OK' if the key is good or the user is an administrator, otherwise an error message."""
|
||||
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.
|
||||
If the user used an API key, the user's email is returned as None."""
|
||||
|
||||
def decode(s):
|
||||
return base64.b64decode(s.encode('ascii')).decode('ascii')
|
||||
@@ -63,46 +65,73 @@ class KeyAuthService:
|
||||
|
||||
header = request.headers.get('Authorization')
|
||||
if not header:
|
||||
return "No authorization header provided."
|
||||
raise ValueError("No authorization header provided.")
|
||||
|
||||
username, password = parse_basic_auth(header)
|
||||
|
||||
if username in (None, ""):
|
||||
return "Authorization header invalid."
|
||||
raise ValueError("Authorization header invalid.")
|
||||
elif username == self.key:
|
||||
return "OK"
|
||||
# The user passed the API key which grants administrative privs.
|
||||
return (None, ["admin"])
|
||||
else:
|
||||
return self.check_imap_login( username, password, env)
|
||||
# The user is trying to log in with a username and user-specific
|
||||
# API key or password. Raises or returns privs.
|
||||
return (username, self.get_user_credentials(username, password, env))
|
||||
|
||||
def check_imap_login(self, email, pw, env):
|
||||
# Validate a user's credentials.
|
||||
def get_user_credentials(self, email, pw, env):
|
||||
# Validate a user's credentials. On success returns a list of
|
||||
# privileges (e.g. [] or ['admin']). On failure raises a ValueError
|
||||
# with a login error message.
|
||||
|
||||
# Sanity check.
|
||||
if email == "" or pw == "":
|
||||
return "Enter an email address and password."
|
||||
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:
|
||||
# Get the hashed password of the user. Raise a ValueError if the
|
||||
# email address does not correspond to a user.
|
||||
pw_hash = get_mail_password(email, env)
|
||||
|
||||
# Authenticate.
|
||||
try:
|
||||
# Use doveadm 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,
|
||||
# and check_call will raise an exception in that case.
|
||||
utils.shell('check_call', [
|
||||
"/usr/bin/doveadm",
|
||||
"auth", "test",
|
||||
email, pw
|
||||
"/usr/bin/doveadm", "pw",
|
||||
"-p", pw,
|
||||
"-t", pw_hash,
|
||||
])
|
||||
except:
|
||||
# Login failed.
|
||||
return "Invalid email address or password."
|
||||
raise ValueError("Invalid password.")
|
||||
|
||||
# Authorize.
|
||||
# (This call should never fail on a valid user.)
|
||||
# Get privileges for authorization. This call should never fail because by this
|
||||
# point we know the email address is a valid user. But on error the call will
|
||||
# return a tuple of an error message and an HTTP status code.
|
||||
privs = get_mail_user_privileges(email, env)
|
||||
if isinstance(privs, tuple): raise Exception("Error getting privileges.")
|
||||
if "admin" not in privs:
|
||||
return "You are not an administrator for this system."
|
||||
if isinstance(privs, tuple): raise ValueError(privs[0])
|
||||
|
||||
return "OK"
|
||||
# Return a list of privileges.
|
||||
return privs
|
||||
|
||||
def create_user_key(self, email, env):
|
||||
# Store an HMAC with the client. The hashed message of the HMAC will be the user's
|
||||
# email address & hashed password and the key will be the master API key. The user of
|
||||
# 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):
|
||||
raw_key = os.urandom(32)
|
||||
|
||||
@@ -1,33 +1,43 @@
|
||||
#!/usr/bin/python3
|
||||
#!/usr/local/lib/mailinabox/env/bin/python
|
||||
|
||||
# This script performs a backup of all user data:
|
||||
# 1) System services are stopped while a copy of user data is made.
|
||||
# 2) An incremental backup is made using duplicity into the
|
||||
# directory STORAGE_ROOT/backup/duplicity.
|
||||
# 3) The stopped services are restarted.
|
||||
# 4) The backup files are encrypted with a long password (stored in
|
||||
# backup/secret_key.txt) to STORAGE_ROOT/backup/encrypted.
|
||||
# 5) STORAGE_ROOT/backup/after-backup is executd if it exists.
|
||||
# 1) System services are stopped.
|
||||
# 2) STORAGE_ROOT/backup/before-backup is executed if it exists.
|
||||
# 3) An incremental encrypted backup is made using duplicity.
|
||||
# 4) The stopped services are restarted.
|
||||
# 5) STORAGE_ROOT/backup/after-backup is executed if it exists.
|
||||
|
||||
import os, os.path, shutil, glob, re, datetime
|
||||
import os, os.path, shutil, glob, re, datetime, sys
|
||||
import dateutil.parser, dateutil.relativedelta, dateutil.tz
|
||||
import rtyaml
|
||||
from exclusiveprocess import Lock
|
||||
|
||||
from utils import exclusive_process, load_environment, shell
|
||||
from utils import load_environment, shell, wait_for_service, fix_boto
|
||||
|
||||
# destroy backups when the most recent increment in the chain
|
||||
# that depends on it is this many days old.
|
||||
keep_backups_for_days = 3
|
||||
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):
|
||||
# What is the current status of backups?
|
||||
# Loop through all of the files in STORAGE_ROOT/backup/duplicity to
|
||||
# get a list of all of the backups taken and sum up file sizes to
|
||||
# see how large the storage is.
|
||||
# If backups are dissbled, return no status.
|
||||
config = get_backup_config(env)
|
||||
if config["target"] == "off":
|
||||
return { }
|
||||
|
||||
# Query duplicity to get a list of all full and incremental
|
||||
# backups available.
|
||||
|
||||
backups = { }
|
||||
now = datetime.datetime.now(dateutil.tz.tzlocal())
|
||||
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
|
||||
backup_cache_dir = os.path.join(backup_root, 'cache')
|
||||
|
||||
def reldate(date, ref, clip):
|
||||
if ref < date: return clip
|
||||
rd = dateutil.relativedelta.relativedelta(ref, date)
|
||||
if rd.years > 1: return "%d years, %d months" % (rd.years, rd.months)
|
||||
if rd.years == 1: return "%d year, %d months" % (rd.years, rd.months)
|
||||
if rd.months > 1: return "%d months, %d days" % (rd.months, rd.days)
|
||||
if rd.months == 1: return "%d month, %d days" % (rd.months, rd.days)
|
||||
if rd.days >= 7: return "%d days" % rd.days
|
||||
@@ -35,65 +45,118 @@ def backup_status(env):
|
||||
if rd.days == 1: return "%d day, %d hours" % (rd.days, rd.hours)
|
||||
return "%d hours, %d minutes" % (rd.hours, rd.minutes)
|
||||
|
||||
backups = { }
|
||||
basedir = os.path.join(env['STORAGE_ROOT'], 'backup/duplicity/')
|
||||
encdir = os.path.join(env['STORAGE_ROOT'], 'backup/encrypted/')
|
||||
os.makedirs(basedir, exist_ok=True) # os.listdir fails if directory does not exist
|
||||
for fn in os.listdir(basedir):
|
||||
m = re.match(r"duplicity-(full|full-signatures|(inc|new-signatures)\.(?P<incbase>\d+T\d+Z)\.to)\.(?P<date>\d+T\d+Z)\.", fn)
|
||||
if not m: raise ValueError(fn)
|
||||
|
||||
key = m.group("date")
|
||||
if key not in backups:
|
||||
date = dateutil.parser.parse(m.group("date"))
|
||||
backups[key] = {
|
||||
"date": m.group("date"),
|
||||
"date_str": date.strftime("%x %X"),
|
||||
# Get duplicity collection status and parse for a list of backups.
|
||||
def parse_line(line):
|
||||
keys = line.strip().split()
|
||||
date = dateutil.parser.parse(keys[1]).astimezone(dateutil.tz.tzlocal())
|
||||
return {
|
||||
"date": keys[1],
|
||||
"date_str": date.strftime("%Y-%m-%d %X") + " " + now.tzname(),
|
||||
"date_delta": reldate(date, now, "the future?"),
|
||||
"full": m.group("incbase") is None,
|
||||
"previous": m.group("incbase"),
|
||||
"size": 0,
|
||||
"encsize": 0,
|
||||
"full": keys[0] == "full",
|
||||
"size": 0, # collection-status doesn't give us the size
|
||||
"volumes": int(keys[2]), # number of archive volumes for this backup (not really helpful)
|
||||
}
|
||||
|
||||
backups[key]["size"] += os.path.getsize(os.path.join(basedir, fn))
|
||||
code, collection_status = shell('check_output', [
|
||||
"/usr/bin/duplicity",
|
||||
"collection-status",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--gpg-options", "--cipher-algo=AES256",
|
||||
"--log-fd", "1",
|
||||
config["target"],
|
||||
] + rsync_ssh_options,
|
||||
get_env(env),
|
||||
trap=True)
|
||||
if code != 0:
|
||||
# Command failed. This is likely due to an improperly configured remote
|
||||
# destination for the backups or the last backup job terminated unexpectedly.
|
||||
raise Exception("Something is wrong with the backup: " + collection_status)
|
||||
for line in collection_status.split('\n'):
|
||||
if line.startswith(" full") or line.startswith(" inc"):
|
||||
backup = parse_line(line)
|
||||
backups[backup["date"]] = backup
|
||||
|
||||
# Also check encrypted size.
|
||||
encfn = os.path.join(encdir, fn + ".enc")
|
||||
if os.path.exists(encfn):
|
||||
backups[key]["encsize"] += os.path.getsize(encfn)
|
||||
# Look at the target directly to get the sizes of each of the backups. There is more than one file per backup.
|
||||
# Starting with duplicity in Ubuntu 18.04, "signatures" files have dates in their
|
||||
# filenames that are a few seconds off the backup date and so don't line up
|
||||
# with the list of backups we have. Track unmatched files so we know how much other
|
||||
# space is used for those.
|
||||
unmatched_file_size = 0
|
||||
for fn, size in list_target_files(config):
|
||||
m = re.match(r"duplicity-(full|full-signatures|(inc|new-signatures)\.(?P<incbase>\d+T\d+Z)\.to)\.(?P<date>\d+T\d+Z)\.", fn)
|
||||
if not m: continue # not a part of a current backup chain
|
||||
key = m.group("date")
|
||||
if key in backups:
|
||||
backups[key]["size"] += size
|
||||
else:
|
||||
unmatched_file_size += size
|
||||
|
||||
# Ensure the rows are sorted reverse chronologically.
|
||||
# This is relied on by should_force_full() and the next step.
|
||||
backups = sorted(backups.values(), key = lambda b : b["date"], reverse=True)
|
||||
|
||||
# When will a backup be deleted?
|
||||
saw_full = False
|
||||
# Get the average size of incremental backups, the size of the
|
||||
# most recent full backup, and the date of the most recent
|
||||
# backup and the most recent full backup.
|
||||
incremental_count = 0
|
||||
incremental_size = 0
|
||||
first_date = None
|
||||
first_full_size = None
|
||||
first_full_date = None
|
||||
for bak in backups:
|
||||
if first_date is None:
|
||||
first_date = dateutil.parser.parse(bak["date"])
|
||||
if bak["full"]:
|
||||
first_full_size = bak["size"]
|
||||
first_full_date = dateutil.parser.parse(bak["date"])
|
||||
break
|
||||
incremental_count += 1
|
||||
incremental_size += bak["size"]
|
||||
|
||||
# When will the most recent backup be deleted? It won't be deleted if the next
|
||||
# backup is incremental, because the increments rely on all past increments.
|
||||
# So first guess how many more incremental backups will occur until the next
|
||||
# full backup. That full backup frees up this one to be deleted. But, the backup
|
||||
# must also be at least min_age_in_days old too.
|
||||
deleted_in = None
|
||||
days_ago = now - datetime.timedelta(days=keep_backups_for_days)
|
||||
if incremental_count > 0 and incremental_size > 0 and first_full_size is not None:
|
||||
# How many days until the next incremental backup? First, the part of
|
||||
# the algorithm based on increment sizes:
|
||||
est_days_to_next_full = (.5 * first_full_size - incremental_size) / (incremental_size/incremental_count)
|
||||
est_time_of_next_full = first_date + datetime.timedelta(days=est_days_to_next_full)
|
||||
|
||||
# ...And then the part of the algorithm based on full backup age:
|
||||
est_time_of_next_full = min(est_time_of_next_full, first_full_date + datetime.timedelta(days=config["min_age_in_days"]*10+1))
|
||||
|
||||
# It still can't be deleted until it's old enough.
|
||||
est_deleted_on = max(est_time_of_next_full, first_date + datetime.timedelta(days=config["min_age_in_days"]))
|
||||
|
||||
deleted_in = "approx. %d days" % round((est_deleted_on-now).total_seconds()/60/60/24 + .5)
|
||||
|
||||
# When will a backup be deleted? Set the deleted_in field of each backup.
|
||||
saw_full = False
|
||||
for bak in backups:
|
||||
if deleted_in:
|
||||
# Subsequent backups are deleted when the most recent increment
|
||||
# in the chain would be deleted.
|
||||
# The most recent increment in a chain and all of the previous backups
|
||||
# it relies on are deleted at the same time.
|
||||
bak["deleted_in"] = deleted_in
|
||||
if bak["full"]:
|
||||
# Reset when we get to a full backup. A new chain start next.
|
||||
# Reset when we get to a full backup. A new chain start *next*.
|
||||
saw_full = True
|
||||
deleted_in = None
|
||||
elif saw_full and not deleted_in:
|
||||
# Mark deleted_in only on the first increment after a full backup.
|
||||
deleted_in = reldate(days_ago, dateutil.parser.parse(bak["date"]), "on next daily backup")
|
||||
# We're now on backups prior to the most recent full backup. These are
|
||||
# free to be deleted as soon as they are min_age_in_days old.
|
||||
deleted_in = reldate(now, dateutil.parser.parse(bak["date"]) + datetime.timedelta(days=config["min_age_in_days"]), "on next daily backup")
|
||||
bak["deleted_in"] = deleted_in
|
||||
|
||||
return {
|
||||
"directory": basedir,
|
||||
"encpwfile": os.path.join(env['STORAGE_ROOT'], 'backup/secret_key.txt'),
|
||||
"encdirectory": encdir,
|
||||
"tz": now.tzname(),
|
||||
"backups": backups,
|
||||
"unmatched_file_size": unmatched_file_size,
|
||||
}
|
||||
|
||||
def should_force_full(env):
|
||||
def should_force_full(config, env):
|
||||
# Force a full backup when the total size of the increments
|
||||
# since the last full backup is greater than half the size
|
||||
# of that full backup.
|
||||
@@ -105,108 +168,394 @@ def should_force_full(env):
|
||||
inc_size += bak["size"]
|
||||
else:
|
||||
# ...until we reach the most recent full backup.
|
||||
# Return if we should to a full backup.
|
||||
return inc_size > .5*bak["size"]
|
||||
# Return if we should to a full backup, which is based
|
||||
# on the size of the increments relative to the full
|
||||
# backup, as well as the age of the full backup.
|
||||
if inc_size > .5*bak["size"]:
|
||||
return True
|
||||
if dateutil.parser.parse(bak["date"]) + datetime.timedelta(days=config["min_age_in_days"]*10+1) < datetime.datetime.now(dateutil.tz.tzlocal()):
|
||||
return True
|
||||
return False
|
||||
else:
|
||||
# If we got here there are no (full) backups, so make one.
|
||||
# (I love for/else blocks. Here it's just to show off.)
|
||||
return True
|
||||
|
||||
def get_passphrase(env):
|
||||
# Get the encryption passphrase. secret_key.txt is 2048 random
|
||||
# bits base64-encoded and with line breaks every 65 characters.
|
||||
# gpg will only take the first line of text, so sanity check that
|
||||
# that line is long enough to be a reasonable passphrase. It
|
||||
# only needs to be 43 base64-characters to match AES256's key
|
||||
# length of 32 bytes.
|
||||
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
|
||||
with open(os.path.join(backup_root, 'secret_key.txt')) as f:
|
||||
passphrase = f.readline().strip()
|
||||
if len(passphrase) < 43: raise Exception("secret_key.txt's first line is too short!")
|
||||
|
||||
return passphrase
|
||||
|
||||
def get_env(env):
|
||||
config = get_backup_config(env)
|
||||
|
||||
env = { "PASSPHRASE" : get_passphrase(env) }
|
||||
|
||||
if get_target_type(config) == 's3':
|
||||
env["AWS_ACCESS_KEY_ID"] = config["target_user"]
|
||||
env["AWS_SECRET_ACCESS_KEY"] = config["target_pass"]
|
||||
|
||||
return env
|
||||
|
||||
def get_target_type(config):
|
||||
protocol = config["target"].split(":")[0]
|
||||
return protocol
|
||||
|
||||
def perform_backup(full_backup):
|
||||
env = load_environment()
|
||||
|
||||
exclusive_process("backup")
|
||||
# Create an global exclusive lock so that the backup script
|
||||
# cannot be run more than one.
|
||||
Lock(die=True).forever()
|
||||
|
||||
# Ensure the backup directory exists.
|
||||
backup_dir = os.path.join(env["STORAGE_ROOT"], 'backup')
|
||||
backup_duplicity_dir = os.path.join(backup_dir, 'duplicity')
|
||||
os.makedirs(backup_duplicity_dir, exist_ok=True)
|
||||
config = get_backup_config(env)
|
||||
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
|
||||
backup_cache_dir = os.path.join(backup_root, 'cache')
|
||||
backup_dir = os.path.join(backup_root, 'encrypted')
|
||||
|
||||
# Are backups disabled?
|
||||
if config["target"] == "off":
|
||||
return
|
||||
|
||||
# On the first run, always do a full backup. Incremental
|
||||
# will fail. Otherwise do a full backup when the size of
|
||||
# the increments since the most recent full backup are
|
||||
# large.
|
||||
full_backup = full_backup or should_force_full(env)
|
||||
try:
|
||||
full_backup = full_backup or should_force_full(config, env)
|
||||
except Exception as e:
|
||||
# This was the first call to duplicity, and there might
|
||||
# be an error already.
|
||||
print(e)
|
||||
sys.exit(1)
|
||||
|
||||
# Stop services.
|
||||
shell('check_call', ["/usr/sbin/service", "dovecot", "stop"])
|
||||
shell('check_call', ["/usr/sbin/service", "postfix", "stop"])
|
||||
def service_command(service, command, quit=None):
|
||||
# Execute silently, but if there is an error then display the output & exit.
|
||||
code, ret = shell('check_output', ["/usr/sbin/service", service, command], capture_stderr=True, trap=True)
|
||||
if code != 0:
|
||||
print(ret)
|
||||
if quit:
|
||||
sys.exit(code)
|
||||
|
||||
# Update the backup mirror directory which mirrors the current
|
||||
# STORAGE_ROOT (but excluding the backups themselves!).
|
||||
service_command("php7.2-fpm", "stop", quit=True)
|
||||
service_command("postfix", "stop", quit=True)
|
||||
service_command("dovecot", "stop", quit=True)
|
||||
|
||||
# Execute a pre-backup script that copies files outside the homedir.
|
||||
# Run as the STORAGE_USER user, not as root. Pass our settings in
|
||||
# environment variables so the script has access to STORAGE_ROOT.
|
||||
pre_script = os.path.join(backup_root, 'before-backup')
|
||||
if os.path.exists(pre_script):
|
||||
shell('check_call',
|
||||
['su', env['STORAGE_USER'], '-c', pre_script, config["target"]],
|
||||
env=env)
|
||||
|
||||
# Run a backup of STORAGE_ROOT (but excluding the backups themselves!).
|
||||
# --allow-source-mismatch is needed in case the box's hostname is changed
|
||||
# after the first backup. See #396.
|
||||
try:
|
||||
shell('check_call', [
|
||||
"/usr/bin/duplicity",
|
||||
"full" if full_backup else "incr",
|
||||
"--no-encryption",
|
||||
"--archive-dir", "/tmp/duplicity-archive-dir",
|
||||
"--name", "mailinabox",
|
||||
"--exclude", backup_dir,
|
||||
"--volsize", "100",
|
||||
"--verbosity", "warning",
|
||||
"--verbosity", "warning", "--no-print-statistics",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--exclude", backup_root,
|
||||
"--volsize", "250",
|
||||
"--gpg-options", "--cipher-algo=AES256",
|
||||
env["STORAGE_ROOT"],
|
||||
"file://" + backup_duplicity_dir
|
||||
])
|
||||
config["target"],
|
||||
"--allow-source-mismatch"
|
||||
] + rsync_ssh_options,
|
||||
get_env(env))
|
||||
finally:
|
||||
# Start services again.
|
||||
shell('check_call', ["/usr/sbin/service", "dovecot", "start"])
|
||||
shell('check_call', ["/usr/sbin/service", "postfix", "start"])
|
||||
service_command("dovecot", "start", quit=False)
|
||||
service_command("postfix", "start", quit=False)
|
||||
service_command("php7.2-fpm", "start", quit=False)
|
||||
|
||||
# Remove old backups. This deletes all backup data no longer needed
|
||||
# from more than 31 days ago. Must do this before destroying the
|
||||
# cache directory or else this command will re-create it.
|
||||
# from more than 3 days ago.
|
||||
shell('check_call', [
|
||||
"/usr/bin/duplicity",
|
||||
"remove-older-than",
|
||||
"%dD" % keep_backups_for_days,
|
||||
"--archive-dir", "/tmp/duplicity-archive-dir",
|
||||
"--name", "mailinabox",
|
||||
"%dD" % config["min_age_in_days"],
|
||||
"--verbosity", "error",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--force",
|
||||
"--verbosity", "warning",
|
||||
"file://" + backup_duplicity_dir
|
||||
])
|
||||
config["target"]
|
||||
] + rsync_ssh_options,
|
||||
get_env(env))
|
||||
|
||||
# Remove duplicity's cache directory because it's redundant with our backup directory.
|
||||
shutil.rmtree("/tmp/duplicity-archive-dir")
|
||||
|
||||
# Encrypt all of the new files.
|
||||
backup_encrypted_dir = os.path.join(backup_dir, 'encrypted')
|
||||
os.makedirs(backup_encrypted_dir, exist_ok=True)
|
||||
for fn in os.listdir(backup_duplicity_dir):
|
||||
fn2 = os.path.join(backup_encrypted_dir, fn) + ".enc"
|
||||
if os.path.exists(fn2): continue
|
||||
|
||||
# Encrypt the backup using the backup private key.
|
||||
# From duplicity's manual:
|
||||
# "This should only be necessary after a duplicity session fails or is
|
||||
# aborted prematurely."
|
||||
# That may be unlikely here but we may as well ensure we tidy up if
|
||||
# that does happen - it might just have been a poorly timed reboot.
|
||||
shell('check_call', [
|
||||
"/usr/bin/openssl",
|
||||
"enc",
|
||||
"-aes-256-cbc",
|
||||
"-a",
|
||||
"-salt",
|
||||
"-in", os.path.join(backup_duplicity_dir, fn),
|
||||
"-out", fn2,
|
||||
"-pass", "file:%s" % os.path.join(backup_dir, "secret_key.txt"),
|
||||
])
|
||||
"/usr/bin/duplicity",
|
||||
"cleanup",
|
||||
"--verbosity", "error",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--force",
|
||||
config["target"]
|
||||
] + rsync_ssh_options,
|
||||
get_env(env))
|
||||
|
||||
# The backup can be decrypted with:
|
||||
# openssl enc -d -aes-256-cbc -a -in latest.tgz.enc -out /dev/stdout -pass file:secret_key.txt | tar -z
|
||||
|
||||
# Remove encrypted backups that are no longer needed.
|
||||
for fn in os.listdir(backup_encrypted_dir):
|
||||
fn2 = os.path.join(backup_duplicity_dir, fn.replace(".enc", ""))
|
||||
if os.path.exists(fn2): continue
|
||||
os.unlink(os.path.join(backup_encrypted_dir, fn))
|
||||
# Change ownership of backups to the user-data user, so that the after-bcakup
|
||||
# script can access them.
|
||||
if get_target_type(config) == 'file':
|
||||
shell('check_call', ["/bin/chown", "-R", env["STORAGE_USER"], backup_dir])
|
||||
|
||||
# Execute a post-backup script that does the copying to a remote server.
|
||||
# Run as the STORAGE_USER user, not as root. Pass our settings in
|
||||
# environment variables so the script has access to STORAGE_ROOT.
|
||||
post_script = os.path.join(backup_dir, 'after-backup')
|
||||
post_script = os.path.join(backup_root, 'after-backup')
|
||||
if os.path.exists(post_script):
|
||||
shell('check_call',
|
||||
['su', env['STORAGE_USER'], '-c', post_script],
|
||||
['su', env['STORAGE_USER'], '-c', post_script, config["target"]],
|
||||
env=env)
|
||||
|
||||
# Our nightly cron job executes system status checks immediately after this
|
||||
# backup. Since it checks that dovecot and postfix are running, block for a
|
||||
# bit (maximum of 10 seconds each) to give each a chance to finish restarting
|
||||
# before the status checks might catch them down. See #381.
|
||||
wait_for_service(25, True, env, 10)
|
||||
wait_for_service(993, True, env, 10)
|
||||
|
||||
def run_duplicity_verification():
|
||||
env = load_environment()
|
||||
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
|
||||
config = get_backup_config(env)
|
||||
backup_cache_dir = os.path.join(backup_root, 'cache')
|
||||
|
||||
shell('check_call', [
|
||||
"/usr/bin/duplicity",
|
||||
"--verbosity", "info",
|
||||
"verify",
|
||||
"--compare-data",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--exclude", backup_root,
|
||||
config["target"],
|
||||
env["STORAGE_ROOT"],
|
||||
] + rsync_ssh_options, get_env(env))
|
||||
|
||||
def run_duplicity_restore(args):
|
||||
env = load_environment()
|
||||
config = get_backup_config(env)
|
||||
backup_cache_dir = os.path.join(env["STORAGE_ROOT"], 'backup', 'cache')
|
||||
shell('check_call', [
|
||||
"/usr/bin/duplicity",
|
||||
"restore",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
config["target"],
|
||||
] + rsync_ssh_options + args,
|
||||
get_env(env))
|
||||
|
||||
def list_target_files(config):
|
||||
import urllib.parse
|
||||
try:
|
||||
target = urllib.parse.urlparse(config["target"])
|
||||
except ValueError:
|
||||
return "invalid target"
|
||||
|
||||
if target.scheme == "file":
|
||||
return [(fn, os.path.getsize(os.path.join(target.path, fn))) for fn in os.listdir(target.path)]
|
||||
|
||||
elif target.scheme == "rsync":
|
||||
rsync_fn_size_re = re.compile(r'.* ([^ ]*) [^ ]* [^ ]* (.*)')
|
||||
rsync_target = '{host}:{path}'
|
||||
|
||||
target_path = target.path
|
||||
if not target_path.endswith('/'):
|
||||
target_path = target_path + '/'
|
||||
if target_path.startswith('/'):
|
||||
target_path = target_path[1:]
|
||||
|
||||
rsync_command = [ 'rsync',
|
||||
'-e',
|
||||
'/usr/bin/ssh -i /root/.ssh/id_rsa_miab -oStrictHostKeyChecking=no -oBatchMode=yes',
|
||||
'--list-only',
|
||||
'-r',
|
||||
rsync_target.format(
|
||||
host=target.netloc,
|
||||
path=target_path)
|
||||
]
|
||||
|
||||
code, listing = shell('check_output', rsync_command, trap=True, capture_stderr=True)
|
||||
if code == 0:
|
||||
ret = []
|
||||
for l in listing.split('\n'):
|
||||
match = rsync_fn_size_re.match(l)
|
||||
if match:
|
||||
ret.append( (match.groups()[1], int(match.groups()[0].replace(',',''))) )
|
||||
return ret
|
||||
else:
|
||||
if 'Permission denied (publickey).' in listing:
|
||||
reason = "Invalid user or check you correctly copied the SSH key."
|
||||
elif 'No such file or directory' in listing:
|
||||
reason = "Provided path {} is invalid.".format(target_path)
|
||||
elif 'Network is unreachable' in listing:
|
||||
reason = "The IP address {} is unreachable.".format(target.hostname)
|
||||
elif 'Could not resolve hostname':
|
||||
reason = "The hostname {} cannot be resolved.".format(target.hostname)
|
||||
else:
|
||||
reason = "Unknown error." \
|
||||
"Please check running 'python management/backup.py --verify'" \
|
||||
"from mailinabox sources to debug the issue."
|
||||
raise ValueError("Connection to rsync host failed: {}".format(reason))
|
||||
|
||||
elif target.scheme == "s3":
|
||||
# match to a Region
|
||||
fix_boto() # must call prior to importing boto
|
||||
import boto.s3
|
||||
from boto.exception import BotoServerError
|
||||
custom_region = False
|
||||
for region in boto.s3.regions():
|
||||
if region.endpoint == target.hostname:
|
||||
break
|
||||
else:
|
||||
# If region is not found this is a custom region
|
||||
custom_region = True
|
||||
|
||||
bucket = target.path[1:].split('/')[0]
|
||||
path = '/'.join(target.path[1:].split('/')[1:]) + '/'
|
||||
|
||||
# Create a custom region with custom endpoint
|
||||
if custom_region:
|
||||
from boto.s3.connection import S3Connection
|
||||
region = boto.s3.S3RegionInfo(name=bucket, endpoint=target.hostname, connection_cls=S3Connection)
|
||||
|
||||
# If no prefix is specified, set the path to '', otherwise boto won't list the files
|
||||
if path == '/':
|
||||
path = ''
|
||||
|
||||
if bucket == "":
|
||||
raise ValueError("Enter an S3 bucket name.")
|
||||
|
||||
# connect to the region & bucket
|
||||
try:
|
||||
conn = region.connect(aws_access_key_id=config["target_user"], aws_secret_access_key=config["target_pass"])
|
||||
bucket = conn.get_bucket(bucket)
|
||||
except BotoServerError as e:
|
||||
if e.status == 403:
|
||||
raise ValueError("Invalid S3 access key or secret access key.")
|
||||
elif e.status == 404:
|
||||
raise ValueError("Invalid S3 bucket name.")
|
||||
elif e.status == 301:
|
||||
raise ValueError("Incorrect region for this bucket.")
|
||||
raise ValueError(e.reason)
|
||||
|
||||
return [(key.name[len(path):], key.size) for key in bucket.list(prefix=path)]
|
||||
|
||||
else:
|
||||
raise ValueError(config["target"])
|
||||
|
||||
|
||||
def backup_set_custom(env, target, target_user, target_pass, min_age):
|
||||
config = get_backup_config(env, for_save=True)
|
||||
|
||||
# min_age must be an int
|
||||
if isinstance(min_age, str):
|
||||
min_age = int(min_age)
|
||||
|
||||
config["target"] = target
|
||||
config["target_user"] = target_user
|
||||
config["target_pass"] = target_pass
|
||||
config["min_age_in_days"] = min_age
|
||||
|
||||
# Validate.
|
||||
try:
|
||||
if config["target"] not in ("off", "local"):
|
||||
# these aren't supported by the following function, which expects a full url in the target key,
|
||||
# which is what is there except when loading the config prior to saving
|
||||
list_target_files(config)
|
||||
except ValueError as e:
|
||||
return str(e)
|
||||
|
||||
write_backup_config(env, config)
|
||||
|
||||
return "OK"
|
||||
|
||||
def get_backup_config(env, for_save=False, for_ui=False):
|
||||
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
|
||||
|
||||
# Defaults.
|
||||
config = {
|
||||
"min_age_in_days": 3,
|
||||
"target": "local",
|
||||
}
|
||||
|
||||
# Merge in anything written to custom.yaml.
|
||||
try:
|
||||
custom_config = rtyaml.load(open(os.path.join(backup_root, 'custom.yaml')))
|
||||
if not isinstance(custom_config, dict): raise ValueError() # caught below
|
||||
config.update(custom_config)
|
||||
except:
|
||||
pass
|
||||
|
||||
# When updating config.yaml, don't do any further processing on what we find.
|
||||
if for_save:
|
||||
return config
|
||||
|
||||
# When passing this back to the admin to show the current settings, do not include
|
||||
# authentication details. The user will have to re-enter it.
|
||||
if for_ui:
|
||||
for field in ("target_user", "target_pass"):
|
||||
if field in config:
|
||||
del config[field]
|
||||
|
||||
# helper fields for the admin
|
||||
config["file_target_directory"] = os.path.join(backup_root, 'encrypted')
|
||||
config["enc_pw_file"] = os.path.join(backup_root, 'secret_key.txt')
|
||||
if config["target"] == "local":
|
||||
# Expand to the full URL.
|
||||
config["target"] = "file://" + config["file_target_directory"]
|
||||
ssh_pub_key = os.path.join('/root', '.ssh', 'id_rsa_miab.pub')
|
||||
if os.path.exists(ssh_pub_key):
|
||||
config["ssh_pub_key"] = open(ssh_pub_key, 'r').read()
|
||||
|
||||
return config
|
||||
|
||||
def write_backup_config(env, newconfig):
|
||||
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
|
||||
with open(os.path.join(backup_root, 'custom.yaml'), "w") as f:
|
||||
f.write(rtyaml.dump(newconfig))
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
if sys.argv[-1] == "--verify":
|
||||
# Run duplicity's verification command to check a) the backup files
|
||||
# are readable, and b) report if they are up to date.
|
||||
run_duplicity_verification()
|
||||
|
||||
elif sys.argv[-1] == "--list":
|
||||
# List the saved backup files.
|
||||
for fn, size in list_target_files(get_backup_config(load_environment())):
|
||||
print("{}\t{}".format(fn, size))
|
||||
|
||||
elif sys.argv[-1] == "--status":
|
||||
# Show backup status.
|
||||
ret = backup_status(load_environment())
|
||||
print(rtyaml.dump(ret["backups"]))
|
||||
print("Storage for unmatched files:", ret["unmatched_file_size"])
|
||||
|
||||
elif len(sys.argv) >= 2 and sys.argv[1] == "--restore":
|
||||
# Run duplicity restore. Rest of command line passed as arguments
|
||||
# to duplicity. The restore path should be specified.
|
||||
run_duplicity_restore(sys.argv[2:])
|
||||
|
||||
else:
|
||||
# Perform a backup. Add --full to force a full backup rather than
|
||||
# possibly performing an incremental backup.
|
||||
full_backup = "--full" in sys.argv
|
||||
perform_backup(full_backup)
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
# Helps you purchase a SSL certificate from Gandi.net using
|
||||
# their API.
|
||||
#
|
||||
# Before you begin:
|
||||
# 1) Create an account on Gandi.net.
|
||||
# 2) Pre-pay $16 into your account at https://www.gandi.net/prepaid/operations. Wait until the payment goes through.
|
||||
# 3) Activate your API key first on the test platform (wait a while, refresh the page) and then activate the production API at https://www.gandi.net/admin/api_key.
|
||||
|
||||
import sys, re, os.path, urllib.request
|
||||
import xmlrpc.client
|
||||
import rtyaml
|
||||
|
||||
from utils import load_environment, shell
|
||||
from web_update import get_web_domains, get_domain_ssl_files, get_web_root
|
||||
from status_checks import check_certificate
|
||||
|
||||
def buy_ssl_certificate(api_key, domain, command, env):
|
||||
if domain != env['PRIMARY_HOSTNAME'] \
|
||||
and domain not in get_web_domains(env):
|
||||
raise ValueError("Domain is not %s or a domain we're serving a website for." % env['PRIMARY_HOSTNAME'])
|
||||
|
||||
# Initialize.
|
||||
|
||||
gandi = xmlrpc.client.ServerProxy('https://rpc.gandi.net/xmlrpc/')
|
||||
|
||||
try:
|
||||
existing_certs = gandi.cert.list(api_key)
|
||||
except Exception as e:
|
||||
if "Invalid API key" in str(e):
|
||||
print("Invalid API key. Check that you copied the API Key correctly from https://www.gandi.net/admin/api_key.")
|
||||
sys.exit(1)
|
||||
else:
|
||||
raise
|
||||
|
||||
# Where is the SSL cert stored?
|
||||
|
||||
ssl_key, ssl_certificate, ssl_csr_path = get_domain_ssl_files(domain, env)
|
||||
|
||||
# Have we already created a cert for this domain?
|
||||
|
||||
for cert in existing_certs:
|
||||
if cert['cn'] == domain:
|
||||
break
|
||||
else:
|
||||
# No existing cert found. Purchase one.
|
||||
if command != 'purchase':
|
||||
print("No certificate or order found yet. If you haven't yet purchased a certificate, run ths script again with the 'purchase' command. Otherwise wait a moment and try again.")
|
||||
sys.exit(1)
|
||||
else:
|
||||
# Start an order for a single standard SSL certificate.
|
||||
# Use DNS validation. Web-based validation won't work because they
|
||||
# require a file on HTTP but not HTTPS w/o redirects and we don't
|
||||
# serve anything plainly over HTTP. Email might be another way but
|
||||
# DNS is easier to automate.
|
||||
op = gandi.cert.create(api_key, {
|
||||
"csr": open(ssl_csr_path).read(),
|
||||
"dcv_method": "dns",
|
||||
"duration": 1, # year?
|
||||
"package": "cert_std_1_0_0",
|
||||
})
|
||||
print("An SSL certificate has been ordered.")
|
||||
print()
|
||||
print(op)
|
||||
print()
|
||||
print("In a moment please run this script again with the 'setup' command.")
|
||||
|
||||
if cert['status'] == 'pending':
|
||||
# Get the information we need to update our DNS with a code so that
|
||||
# Gandi can verify that we own the domain.
|
||||
|
||||
dcv = gandi.cert.get_dcv_params(api_key, {
|
||||
"csr": open(ssl_csr_path).read(),
|
||||
"cert_id": cert['id'],
|
||||
"dcv_method": "dns",
|
||||
"duration": 1, # year?
|
||||
"package": "cert_std_1_0_0",
|
||||
})
|
||||
if dcv["dcv_method"] != "dns":
|
||||
raise Exception("Certificate ordered with an unknown validation method.")
|
||||
|
||||
# Update our DNS data.
|
||||
|
||||
dns_config = env['STORAGE_ROOT'] + '/dns/custom.yaml'
|
||||
if os.path.exists(dns_config):
|
||||
dns_records = rtyaml.load(open(dns_config))
|
||||
else:
|
||||
dns_records = { }
|
||||
|
||||
qname = dcv['md5'] + '.' + domain
|
||||
value = dcv['sha1'] + '.comodoca.com.'
|
||||
dns_records[qname] = { "CNAME": value }
|
||||
|
||||
with open(dns_config, 'w') as f:
|
||||
f.write(rtyaml.dump(dns_records))
|
||||
|
||||
shell('check_call', ['tools/dns_update'])
|
||||
|
||||
# Okay, done with this step.
|
||||
|
||||
print("DNS has been updated. Gandi will check within 60 minutes.")
|
||||
print()
|
||||
print("See https://www.gandi.net/admin/ssl/%d/details for the status of this order." % cert['id'])
|
||||
|
||||
elif cert['status'] == 'valid':
|
||||
# The certificate is ready.
|
||||
|
||||
# Check before we overwrite something we shouldn't.
|
||||
if os.path.exists(ssl_certificate):
|
||||
cert_status, cert_status_details = check_certificate(None, ssl_certificate, None)
|
||||
if cert_status != "SELF-SIGNED":
|
||||
print("Please back up and delete the file %s so I can save your new certificate." % ssl_certificate)
|
||||
sys.exit(1)
|
||||
|
||||
# Form the certificate.
|
||||
|
||||
# The certificate comes as a long base64-encoded string. Break in
|
||||
# into lines in the usual way.
|
||||
pem = "-----BEGIN CERTIFICATE-----\n"
|
||||
pem += "\n".join(chunk for chunk in re.split(r"(.{64})", cert['cert']) if chunk != "")
|
||||
pem += "\n-----END CERTIFICATE-----\n\n"
|
||||
|
||||
# Append intermediary certificates.
|
||||
pem += urllib.request.urlopen("https://www.gandi.net/static/CAs/GandiStandardSSLCA.pem").read().decode("ascii")
|
||||
|
||||
# Write out.
|
||||
|
||||
with open(ssl_certificate, "w") as f:
|
||||
f.write(pem)
|
||||
|
||||
print("The certificate has been installed in %s. Restarting services..." % ssl_certificate)
|
||||
|
||||
# Restart dovecot and if this is for PRIMARY_HOSTNAME.
|
||||
|
||||
if domain == env['PRIMARY_HOSTNAME']:
|
||||
shell('check_call', ["/usr/sbin/service", "dovecot", "restart"])
|
||||
shell('check_call', ["/usr/sbin/service", "postfix", "restart"])
|
||||
|
||||
# Restart nginx in all cases.
|
||||
|
||||
shell('check_call', ["/usr/sbin/service", "nginx", "restart"])
|
||||
|
||||
else:
|
||||
print("The certificate has an unknown status. Please check https://www.gandi.net/admin/ssl/%d/details for the status of this order." % cert['id'])
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) < 4:
|
||||
print("Usage: python management/buy_certificate.py gandi_api_key domain_name {purchase, setup}")
|
||||
sys.exit(1)
|
||||
api_key = sys.argv[1]
|
||||
domain_name = sys.argv[2]
|
||||
cmd = sys.argv[3]
|
||||
buy_ssl_certificate(api_key, domain_name, cmd, load_environment())
|
||||
|
||||
@@ -1,27 +1,28 @@
|
||||
# This list is derived from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2.
|
||||
# The columns are ISO_3166-1_alpha-2 code, display name, Wikipedia page name.
|
||||
# The top 20 countries by number of Internet users are grouped first, see
|
||||
# The top 21 countries by number of Internet users are grouped first, see
|
||||
# https://en.wikipedia.org/wiki/List_of_countries_by_number_of_Internet_users.
|
||||
BR Brazil
|
||||
CA Canada
|
||||
CN China
|
||||
EG Egypt
|
||||
FR France
|
||||
DE Germany
|
||||
IN India
|
||||
ID Indonesia
|
||||
IT Italy
|
||||
JP Japan
|
||||
MX Mexico
|
||||
NG Nigeria
|
||||
PH Philippines
|
||||
RU Russian Federation Russia
|
||||
ES Spain
|
||||
KR South Korea
|
||||
TR Turkey
|
||||
GB United Kingdom
|
||||
US United States
|
||||
JP Japan
|
||||
BR Brazil
|
||||
RU Russian Federation Russia
|
||||
DE Germany
|
||||
NG Nigeria
|
||||
GB United Kingdom
|
||||
FR France
|
||||
MX Mexico
|
||||
EG Egypt
|
||||
KR South Korea
|
||||
VN Vietnam
|
||||
ID Indonesia
|
||||
PH Philippines
|
||||
TR Turkey
|
||||
IT Italy
|
||||
PK Pakistan
|
||||
ES Spain
|
||||
CA Canada
|
||||
AD Andorra
|
||||
AE United Arab Emirates
|
||||
AF Afghanistan
|
||||
@@ -183,7 +184,6 @@ PA Panama
|
||||
PE Peru
|
||||
PF French Polynesia
|
||||
PG Papua New Guinea
|
||||
PK Pakistan
|
||||
PL Poland
|
||||
PM Saint Pierre and Miquelon
|
||||
PN Pitcairn Pitcairn Islands
|
||||
|
@@ -1,12 +1,11 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
import os, os.path, re, json
|
||||
import os, os.path, re, json, time
|
||||
import subprocess
|
||||
|
||||
from functools import wraps
|
||||
|
||||
from flask import Flask, request, render_template, abort, Response
|
||||
from flask import Flask, request, render_template, abort, Response, send_from_directory, make_response
|
||||
|
||||
import auth, utils
|
||||
import auth, utils, multiprocessing.pool
|
||||
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_aliases, get_mail_aliases_ex, get_mail_domains, add_mail_alias, remove_mail_alias
|
||||
@@ -22,21 +21,45 @@ try:
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# for generating CSRs we need a list of country codes
|
||||
csr_country_codes = []
|
||||
with open(os.path.join(os.path.dirname(me), "csr_country_codes.tsv")) as f:
|
||||
for line in f:
|
||||
if line.strip() == "" or line.startswith("#"): continue
|
||||
code, name = line.strip().split("\t")[0:2]
|
||||
csr_country_codes.append((code, name))
|
||||
|
||||
app = Flask(__name__, template_folder=os.path.abspath(os.path.join(os.path.dirname(me), "templates")))
|
||||
|
||||
# Decorator to protect views that require authentication.
|
||||
# Decorator to protect views that require a user with 'admin' privileges.
|
||||
def authorized_personnel_only(viewfunc):
|
||||
@wraps(viewfunc)
|
||||
def newview(*args, **kwargs):
|
||||
# Check if the user is authorized.
|
||||
authorized_status = auth_service.is_authenticated(request, env)
|
||||
if authorized_status == "OK":
|
||||
# Authorized. Call view func.
|
||||
# Authenticate the passed credentials, which is either the API key or a username:password pair.
|
||||
error = None
|
||||
try:
|
||||
email, privs = auth_service.authenticate(request, env)
|
||||
except ValueError as e:
|
||||
# Authentication failed.
|
||||
privs = []
|
||||
error = "Incorrect username or password"
|
||||
|
||||
# Write a line in the log recording the failed login
|
||||
log_failed_login(request)
|
||||
|
||||
# Authorized to access an API view?
|
||||
if "admin" in privs:
|
||||
# Call view func.
|
||||
return viewfunc(*args, **kwargs)
|
||||
elif not error:
|
||||
error = "You are not an administrator."
|
||||
|
||||
# Not authorized. Return a 401 (send auth) and a prompt to authorize by default.
|
||||
status = 401
|
||||
headers = { 'WWW-Authenticate': 'Basic realm="{0}"'.format(auth_service.auth_realm) }
|
||||
headers = {
|
||||
'WWW-Authenticate': 'Basic realm="{0}"'.format(auth_service.auth_realm),
|
||||
'X-Reason': error,
|
||||
}
|
||||
|
||||
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
||||
# Don't issue a 401 to an AJAX request because the user will
|
||||
@@ -46,13 +69,13 @@ def authorized_personnel_only(viewfunc):
|
||||
|
||||
if request.headers.get('Accept') in (None, "", "*/*"):
|
||||
# Return plain text output.
|
||||
return Response(authorized_status+"\n", status=status, mimetype='text/plain', headers=headers)
|
||||
return Response(error+"\n", status=status, mimetype='text/plain', headers=headers)
|
||||
else:
|
||||
# Return JSON output.
|
||||
return Response(json.dumps({
|
||||
"status": "error",
|
||||
"reason": authorized_status
|
||||
}+"\n"), status=status, mimetype='application/json', headers=headers)
|
||||
"reason": error,
|
||||
})+"\n", status=status, mimetype='application/json', headers=headers)
|
||||
|
||||
return newview
|
||||
|
||||
@@ -61,7 +84,7 @@ def unauthorized(error):
|
||||
return auth_service.make_unauthorized_response()
|
||||
|
||||
def json_response(data):
|
||||
return Response(json.dumps(data), status=200, mimetype='application/json')
|
||||
return Response(json.dumps(data, indent=2, sort_keys=True)+'\n', status=200, mimetype='application/json')
|
||||
|
||||
###################################
|
||||
|
||||
@@ -71,34 +94,59 @@ def json_response(data):
|
||||
def index():
|
||||
# Render the control panel. This route does not require user authentication
|
||||
# so it must be safe!
|
||||
|
||||
no_users_exist = (len(get_mail_users(env)) == 0)
|
||||
no_admins_exist = (len(get_admins(env)) == 0)
|
||||
|
||||
utils.fix_boto() # must call prior to importing boto
|
||||
import boto.s3
|
||||
backup_s3_hosts = [(r.name, r.endpoint) for r in boto.s3.regions()]
|
||||
|
||||
return render_template('index.html',
|
||||
hostname=env['PRIMARY_HOSTNAME'],
|
||||
storage_root=env['STORAGE_ROOT'],
|
||||
|
||||
no_users_exist=no_users_exist,
|
||||
no_admins_exist=no_admins_exist,
|
||||
|
||||
backup_s3_hosts=backup_s3_hosts,
|
||||
csr_country_codes=csr_country_codes,
|
||||
)
|
||||
|
||||
@app.route('/me')
|
||||
def me():
|
||||
# Is the caller authorized?
|
||||
authorized_status = auth_service.is_authenticated(request, env)
|
||||
if authorized_status != "OK":
|
||||
try:
|
||||
email, privs = auth_service.authenticate(request, env)
|
||||
except ValueError as e:
|
||||
# Log the failed login
|
||||
log_failed_login(request)
|
||||
|
||||
return json_response({
|
||||
"status": "not-authorized",
|
||||
"reason": authorized_status,
|
||||
})
|
||||
return json_response({
|
||||
"status": "authorized",
|
||||
"api_key": auth_service.key,
|
||||
"status": "invalid",
|
||||
"reason": "Incorrect username or password",
|
||||
})
|
||||
|
||||
resp = {
|
||||
"status": "ok",
|
||||
"email": email,
|
||||
"privileges": privs,
|
||||
}
|
||||
|
||||
# Is authorized as admin? Return an API key for future use.
|
||||
if "admin" in privs:
|
||||
resp["api_key"] = auth_service.create_user_key(email, env)
|
||||
|
||||
# Return.
|
||||
return json_response(resp)
|
||||
|
||||
# MAIL
|
||||
|
||||
@app.route('/mail/users')
|
||||
@authorized_personnel_only
|
||||
def mail_users():
|
||||
if request.args.get("format", "") == "json":
|
||||
return json_response(get_mail_users_ex(env, with_archived=True, with_slow_info=True))
|
||||
return json_response(get_mail_users_ex(env, with_archived=True))
|
||||
else:
|
||||
return "".join(x+"\n" for x in get_mail_users(env))
|
||||
|
||||
@@ -148,14 +196,15 @@ def mail_aliases():
|
||||
if request.args.get("format", "") == "json":
|
||||
return json_response(get_mail_aliases_ex(env))
|
||||
else:
|
||||
return "".join(x+"\t"+y+"\n" for x, y in get_mail_aliases(env))
|
||||
return "".join(address+"\t"+receivers+"\t"+(senders or "")+"\n" for address, receivers, senders in get_mail_aliases(env))
|
||||
|
||||
@app.route('/mail/aliases/add', methods=['POST'])
|
||||
@authorized_personnel_only
|
||||
def mail_aliases_add():
|
||||
return add_mail_alias(
|
||||
request.form.get('source', ''),
|
||||
request.form.get('destination', ''),
|
||||
request.form.get('address', ''),
|
||||
request.form.get('forwards_to', ''),
|
||||
request.form.get('permitted_senders', ''),
|
||||
env,
|
||||
update_if_exists=(request.form.get('update_if_exists', '') == '1')
|
||||
)
|
||||
@@ -163,7 +212,7 @@ def mail_aliases_add():
|
||||
@app.route('/mail/aliases/remove', methods=['POST'])
|
||||
@authorized_personnel_only
|
||||
def mail_aliases_remove():
|
||||
return remove_mail_alias(request.form.get('source', ''), env)
|
||||
return remove_mail_alias(request.form.get('address', ''), env)
|
||||
|
||||
@app.route('/mail/domains')
|
||||
@authorized_personnel_only
|
||||
@@ -190,50 +239,82 @@ def dns_update():
|
||||
@app.route('/dns/secondary-nameserver')
|
||||
@authorized_personnel_only
|
||||
def dns_get_secondary_nameserver():
|
||||
from dns_update import get_custom_dns_config
|
||||
return json_response({ "hostname": get_custom_dns_config(env).get("_secondary_nameserver") })
|
||||
from dns_update import get_custom_dns_config, get_secondary_dns
|
||||
return json_response({ "hostnames": get_secondary_dns(get_custom_dns_config(env), mode=None) })
|
||||
|
||||
@app.route('/dns/secondary-nameserver', methods=['POST'])
|
||||
@authorized_personnel_only
|
||||
def dns_set_secondary_nameserver():
|
||||
from dns_update import set_secondary_dns
|
||||
try:
|
||||
return set_secondary_dns(request.form.get('hostname'), env)
|
||||
return set_secondary_dns([ns.strip() for ns in re.split(r"[, ]+", request.form.get('hostnames') or "") if ns.strip() != ""], env)
|
||||
except ValueError as e:
|
||||
return (str(e), 400)
|
||||
|
||||
@app.route('/dns/set')
|
||||
@app.route('/dns/custom')
|
||||
@authorized_personnel_only
|
||||
def dns_get_records():
|
||||
from dns_update import get_custom_dns_config, get_custom_records
|
||||
additional_records = get_custom_dns_config(env)
|
||||
records = get_custom_records(None, additional_records, env)
|
||||
return json_response([{
|
||||
def dns_get_records(qname=None, rtype=None):
|
||||
from dns_update import get_custom_dns_config
|
||||
return json_response([
|
||||
{
|
||||
"qname": r[0],
|
||||
"rtype": r[1],
|
||||
"value": r[2],
|
||||
} for r in records])
|
||||
}
|
||||
for r in get_custom_dns_config(env)
|
||||
if r[0] != "_secondary_nameserver"
|
||||
and (not qname or r[0] == qname)
|
||||
and (not rtype or r[1] == rtype) ])
|
||||
|
||||
@app.route('/dns/set/<qname>', methods=['POST'])
|
||||
@app.route('/dns/set/<qname>/<rtype>', methods=['POST'])
|
||||
@app.route('/dns/set/<qname>/<rtype>/<value>', methods=['POST'])
|
||||
@app.route('/dns/custom/<qname>', methods=['GET', 'POST', 'PUT', 'DELETE'])
|
||||
@app.route('/dns/custom/<qname>/<rtype>', methods=['GET', 'POST', 'PUT', 'DELETE'])
|
||||
@authorized_personnel_only
|
||||
def dns_set_record(qname, rtype="A", value=None):
|
||||
def dns_set_record(qname, rtype="A"):
|
||||
from dns_update import do_dns_update, set_custom_dns_record
|
||||
try:
|
||||
# Get the value from the URL, then the POST parameters, or if it is not set then
|
||||
# use the remote IP address of the request --- makes dynamic DNS easy. To clear a
|
||||
# value, '' must be explicitly passed.
|
||||
if value is None:
|
||||
value = request.form.get("value")
|
||||
if value is None:
|
||||
# Normalize.
|
||||
rtype = rtype.upper()
|
||||
|
||||
# Read the record value from the request BODY, which must be
|
||||
# ASCII-only. Not used with GET.
|
||||
value = request.stream.read().decode("ascii", "ignore").strip()
|
||||
|
||||
if request.method == "GET":
|
||||
# Get the existing records matching the qname and rtype.
|
||||
return dns_get_records(qname, rtype)
|
||||
|
||||
elif request.method in ("POST", "PUT"):
|
||||
# There is a default value for A/AAAA records.
|
||||
if rtype in ("A", "AAAA") and value == "":
|
||||
value = request.environ.get("HTTP_X_FORWARDED_FOR") # normally REMOTE_ADDR but we're behind nginx as a reverse proxy
|
||||
if value == '' or value == '__delete__':
|
||||
# request deletion
|
||||
|
||||
# Cannot add empty records.
|
||||
if value == '':
|
||||
return ("No value for the record provided.", 400)
|
||||
|
||||
if request.method == "POST":
|
||||
# Add a new record (in addition to any existing records
|
||||
# for this qname-rtype pair).
|
||||
action = "add"
|
||||
elif request.method == "PUT":
|
||||
# In REST, PUT is supposed to be idempotent, so we'll
|
||||
# make this action set (replace all records for this
|
||||
# qname-rtype pair) rather than add (add a new record).
|
||||
action = "set"
|
||||
|
||||
elif request.method == "DELETE":
|
||||
if value == '':
|
||||
# Delete all records for this qname-type pair.
|
||||
value = None
|
||||
if set_custom_dns_record(qname, rtype, value, env):
|
||||
return do_dns_update(env)
|
||||
else:
|
||||
# Delete just the qname-rtype-value record exactly.
|
||||
pass
|
||||
action = "remove"
|
||||
|
||||
if set_custom_dns_record(qname, rtype, value, action, env):
|
||||
return do_dns_update(env) or "Something isn't right."
|
||||
return "OK"
|
||||
|
||||
except ValueError as e:
|
||||
return (str(e), 400)
|
||||
|
||||
@@ -245,22 +326,64 @@ def dns_get_dump():
|
||||
|
||||
# SSL
|
||||
|
||||
@app.route('/ssl/status')
|
||||
@authorized_personnel_only
|
||||
def ssl_get_status():
|
||||
from ssl_certificates import get_certificates_to_provision
|
||||
from web_update import get_web_domains_info, get_web_domains
|
||||
|
||||
# What domains can we provision certificates for? What unexpected problems do we have?
|
||||
provision, cant_provision = get_certificates_to_provision(env, show_valid_certs=False)
|
||||
|
||||
# What's the current status of TLS certificates on all of the domain?
|
||||
domains_status = get_web_domains_info(env)
|
||||
domains_status = [
|
||||
{
|
||||
"domain": d["domain"],
|
||||
"status": d["ssl_certificate"][0],
|
||||
"text": d["ssl_certificate"][1] + ((" " + cant_provision[d["domain"]] if d["domain"] in cant_provision else ""))
|
||||
} for d in domains_status ]
|
||||
|
||||
# Warn the user about domain names not hosted here because of other settings.
|
||||
for domain in set(get_web_domains(env, exclude_dns_elsewhere=False)) - set(get_web_domains(env)):
|
||||
domains_status.append({
|
||||
"domain": domain,
|
||||
"status": "not-applicable",
|
||||
"text": "The domain's website is hosted elsewhere.",
|
||||
})
|
||||
|
||||
return json_response({
|
||||
"can_provision": utils.sort_domains(provision, env),
|
||||
"status": domains_status,
|
||||
})
|
||||
|
||||
@app.route('/ssl/csr/<domain>', methods=['POST'])
|
||||
@authorized_personnel_only
|
||||
def ssl_get_csr(domain):
|
||||
from web_update import get_domain_ssl_files, create_csr
|
||||
ssl_key, ssl_certificate, csr_path = get_domain_ssl_files(domain, env)
|
||||
return create_csr(domain, ssl_key, env)
|
||||
from ssl_certificates import create_csr
|
||||
ssl_private_key = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_private_key.pem'))
|
||||
return create_csr(domain, ssl_private_key, request.form.get('countrycode', ''), env)
|
||||
|
||||
@app.route('/ssl/install', methods=['POST'])
|
||||
@authorized_personnel_only
|
||||
def ssl_install_cert():
|
||||
from web_update import install_cert
|
||||
from web_update import get_web_domains
|
||||
from ssl_certificates import install_cert
|
||||
domain = request.form.get('domain')
|
||||
ssl_cert = request.form.get('cert')
|
||||
ssl_chain = request.form.get('chain')
|
||||
if domain not in get_web_domains(env):
|
||||
return "Invalid domain name."
|
||||
return install_cert(domain, ssl_cert, ssl_chain, env)
|
||||
|
||||
@app.route('/ssl/provision', methods=['POST'])
|
||||
@authorized_personnel_only
|
||||
def ssl_provision_certs():
|
||||
from ssl_certificates import provision_certificates
|
||||
requests = provision_certificates(env, limit_domains=None)
|
||||
return json_response({ "requests": requests })
|
||||
|
||||
|
||||
# WEB
|
||||
|
||||
@app.route('/web/domains')
|
||||
@@ -277,6 +400,24 @@ def web_update():
|
||||
|
||||
# System
|
||||
|
||||
@app.route('/system/version', methods=["GET"])
|
||||
@authorized_personnel_only
|
||||
def system_version():
|
||||
from status_checks import what_version_is_this
|
||||
try:
|
||||
return what_version_is_this(env)
|
||||
except Exception as e:
|
||||
return (str(e), 500)
|
||||
|
||||
@app.route('/system/latest-upstream-version', methods=["POST"])
|
||||
@authorized_personnel_only
|
||||
def system_latest_upstream_version():
|
||||
from status_checks import get_latest_miab_version
|
||||
try:
|
||||
return get_latest_miab_version()
|
||||
except Exception as e:
|
||||
return (str(e), 500)
|
||||
|
||||
@app.route('/system/status', methods=["POST"])
|
||||
@authorized_personnel_only
|
||||
def system_status():
|
||||
@@ -295,7 +436,10 @@ def system_status():
|
||||
def print_line(self, message, monospace=False):
|
||||
self.items[-1]["extra"].append({ "text": message, "monospace": monospace })
|
||||
output = WebOutput()
|
||||
run_checks(env, output)
|
||||
# Create a temporary pool of processes for the status checks
|
||||
pool = multiprocessing.pool.Pool(processes=5)
|
||||
run_checks(False, env, output, pool)
|
||||
pool.terminate()
|
||||
return json_response(output.items)
|
||||
|
||||
@app.route('/system/updates')
|
||||
@@ -315,11 +459,148 @@ def do_updates():
|
||||
"DEBIAN_FRONTEND": "noninteractive"
|
||||
})
|
||||
|
||||
|
||||
@app.route('/system/reboot', methods=["GET"])
|
||||
@authorized_personnel_only
|
||||
def needs_reboot():
|
||||
from status_checks import is_reboot_needed_due_to_package_installation
|
||||
if is_reboot_needed_due_to_package_installation():
|
||||
return json_response(True)
|
||||
else:
|
||||
return json_response(False)
|
||||
|
||||
@app.route('/system/reboot', methods=["POST"])
|
||||
@authorized_personnel_only
|
||||
def do_reboot():
|
||||
# To keep the attack surface low, we don't allow a remote reboot if one isn't necessary.
|
||||
from status_checks import is_reboot_needed_due_to_package_installation
|
||||
if is_reboot_needed_due_to_package_installation():
|
||||
return utils.shell("check_output", ["/sbin/shutdown", "-r", "now"], capture_stderr=True)
|
||||
else:
|
||||
return "No reboot is required, so it is not allowed."
|
||||
|
||||
|
||||
@app.route('/system/backup/status')
|
||||
@authorized_personnel_only
|
||||
def backup_status():
|
||||
from backup import backup_status
|
||||
try:
|
||||
return json_response(backup_status(env))
|
||||
except Exception as e:
|
||||
return json_response({ "error": str(e) })
|
||||
|
||||
@app.route('/system/backup/config', methods=["GET"])
|
||||
@authorized_personnel_only
|
||||
def backup_get_custom():
|
||||
from backup import get_backup_config
|
||||
return json_response(get_backup_config(env, for_ui=True))
|
||||
|
||||
@app.route('/system/backup/config', methods=["POST"])
|
||||
@authorized_personnel_only
|
||||
def backup_set_custom():
|
||||
from backup import backup_set_custom
|
||||
return json_response(backup_set_custom(env,
|
||||
request.form.get('target', ''),
|
||||
request.form.get('target_user', ''),
|
||||
request.form.get('target_pass', ''),
|
||||
request.form.get('min_age', '')
|
||||
))
|
||||
|
||||
@app.route('/system/privacy', methods=["GET"])
|
||||
@authorized_personnel_only
|
||||
def privacy_status_get():
|
||||
config = utils.load_settings(env)
|
||||
return json_response(config.get("privacy", True))
|
||||
|
||||
@app.route('/system/privacy', methods=["POST"])
|
||||
@authorized_personnel_only
|
||||
def privacy_status_set():
|
||||
config = utils.load_settings(env)
|
||||
config["privacy"] = (request.form.get('value') == "private")
|
||||
utils.write_settings(config, env)
|
||||
return "OK"
|
||||
|
||||
# MUNIN
|
||||
|
||||
@app.route('/munin/')
|
||||
@app.route('/munin/<path:filename>')
|
||||
@authorized_personnel_only
|
||||
def munin(filename=""):
|
||||
# Checks administrative access (@authorized_personnel_only) and then just proxies
|
||||
# the request to static files.
|
||||
if filename == "": filename = "index.html"
|
||||
return send_from_directory("/var/cache/munin/www", filename)
|
||||
|
||||
@app.route('/munin/cgi-graph/<path:filename>')
|
||||
@authorized_personnel_only
|
||||
def munin_cgi(filename):
|
||||
""" Relay munin cgi dynazoom requests
|
||||
/usr/lib/munin/cgi/munin-cgi-graph is a perl cgi script in the munin package
|
||||
that is responsible for generating binary png images _and_ associated HTTP
|
||||
headers based on parameters in the requesting URL. All output is written
|
||||
to stdout which munin_cgi splits into response headers and binary response
|
||||
data.
|
||||
munin-cgi-graph reads environment variables to determine
|
||||
what it should do. It expects a path to be in the env-var PATH_INFO, and a
|
||||
querystring to be in the env-var QUERY_STRING.
|
||||
munin-cgi-graph has several failure modes. Some write HTTP Status headers and
|
||||
others return nonzero exit codes.
|
||||
Situating munin_cgi between the user-agent and munin-cgi-graph enables keeping
|
||||
the cgi script behind mailinabox's auth mechanisms and avoids additional
|
||||
support infrastructure like spawn-fcgi.
|
||||
"""
|
||||
|
||||
COMMAND = 'su - munin --preserve-environment --shell=/bin/bash -c /usr/lib/munin/cgi/munin-cgi-graph'
|
||||
# su changes user, we use the munin user here
|
||||
# --preserve-environment retains the environment, which is where Popen's `env` data is
|
||||
# --shell=/bin/bash ensures the shell used is bash
|
||||
# -c "/usr/lib/munin/cgi/munin-cgi-graph" passes the command to run as munin
|
||||
# "%s" is a placeholder for where the request's querystring will be added
|
||||
|
||||
if filename == "":
|
||||
return ("a path must be specified", 404)
|
||||
|
||||
query_str = request.query_string.decode("utf-8", 'ignore')
|
||||
|
||||
env = {'PATH_INFO': '/%s/' % filename, 'REQUEST_METHOD': 'GET', 'QUERY_STRING': query_str}
|
||||
code, binout = utils.shell('check_output',
|
||||
COMMAND.split(" ", 5),
|
||||
# Using a maxsplit of 5 keeps the last arguments together
|
||||
env=env,
|
||||
return_bytes=True,
|
||||
trap=True)
|
||||
|
||||
if code != 0:
|
||||
# nonzero returncode indicates error
|
||||
app.logger.error("munin_cgi: munin-cgi-graph returned nonzero exit code, %s", code)
|
||||
return ("error processing graph image", 500)
|
||||
|
||||
# /usr/lib/munin/cgi/munin-cgi-graph returns both headers and binary png when successful.
|
||||
# A double-Windows-style-newline always indicates the end of HTTP headers.
|
||||
headers, image_bytes = binout.split(b'\r\n\r\n', 1)
|
||||
response = make_response(image_bytes)
|
||||
for line in headers.splitlines():
|
||||
name, value = line.decode("utf8").split(':', 1)
|
||||
response.headers[name] = value
|
||||
if 'Status' in response.headers and '404' in response.headers['Status']:
|
||||
app.logger.warning("munin_cgi: munin-cgi-graph returned 404 status code. PATH_INFO=%s", env['PATH_INFO'])
|
||||
return response
|
||||
|
||||
def log_failed_login(request):
|
||||
# We need to figure out the ip to list in the message, all our calls are routed
|
||||
# through nginx who will put the original ip in X-Forwarded-For.
|
||||
# During setup we call the management interface directly to determine the user
|
||||
# status. So we can't always use X-Forwarded-For because during setup that header
|
||||
# will not be present.
|
||||
if request.headers.getlist("X-Forwarded-For"):
|
||||
ip = request.headers.getlist("X-Forwarded-For")[0]
|
||||
else:
|
||||
ip = request.remote_addr
|
||||
|
||||
# We need to add a timestamp to the log message, otherwise /dev/log will eat the "duplicate"
|
||||
# message.
|
||||
app.logger.warning( "Mail-in-a-Box Management Daemon: Failed login attempt from ip %s - timestamp %s" % (ip, time.time()))
|
||||
|
||||
|
||||
# APP
|
||||
|
||||
@@ -340,4 +621,3 @@ if __name__ == '__main__':
|
||||
|
||||
# Start the application server. Listens on 127.0.0.1 (IPv4 only).
|
||||
app.run(port=10222)
|
||||
|
||||
|
||||
25
management/daily_tasks.sh
Executable file
25
management/daily_tasks.sh
Executable file
@@ -0,0 +1,25 @@
|
||||
#!/bin/bash
|
||||
# This script is run daily (at 3am each night).
|
||||
|
||||
# Set character encoding flags to ensure that any non-ASCII
|
||||
# characters don't cause problems. See setup/start.sh and
|
||||
# the management daemon startup script.
|
||||
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
|
||||
|
||||
# On Mondays, i.e. once a week, send the administrator a report of total emails
|
||||
# sent and received so the admin might notice server abuse.
|
||||
if [ `date "+%u"` -eq 1 ]; then
|
||||
management/mail_log.py -t week | management/email_administrator.py "Mail-in-a-Box Usage Report"
|
||||
fi
|
||||
|
||||
# Take a backup.
|
||||
management/backup.py | management/email_administrator.py "Backup Status"
|
||||
|
||||
# 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"
|
||||
|
||||
# Run status checks and email the administrator if anything changed.
|
||||
management/status_checks.py --show-changes | management/email_administrator.py "Status Checks Change Notice"
|
||||
@@ -1,10 +1,10 @@
|
||||
#!/usr/bin/python3
|
||||
#!/usr/local/lib/mailinabox/env/bin/python
|
||||
|
||||
# Creates DNS zone files for all of the domains of all of the mail users
|
||||
# and mail aliases and restarts nsd.
|
||||
########################################################################
|
||||
|
||||
import os, os.path, urllib.parse, datetime, re, hashlib, base64
|
||||
import sys, os, os.path, urllib.parse, datetime, re, hashlib, base64
|
||||
import ipaddress
|
||||
import rtyaml
|
||||
import dns.resolver
|
||||
@@ -12,6 +12,12 @@ import dns.resolver
|
||||
from mailconfig import get_mail_domains
|
||||
from utils import shell, load_env_vars_from_file, safe_domain_name, sort_domains
|
||||
|
||||
# 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,
|
||||
# underscores, as well as asteriks which are allowed in domain names but not hostnames (i.e. allowed in
|
||||
# DNS but not in URLs), which are common in certain record types like for DKIM.
|
||||
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):
|
||||
# Add all domain names in use by email users and mail aliases and ensure
|
||||
# PRIMARY_HOSTNAME is in the list.
|
||||
@@ -50,31 +56,14 @@ def get_dns_zones(env):
|
||||
|
||||
return zonefiles
|
||||
|
||||
def get_custom_dns_config(env):
|
||||
try:
|
||||
return rtyaml.load(open(os.path.join(env['STORAGE_ROOT'], 'dns/custom.yaml')))
|
||||
except:
|
||||
return { }
|
||||
|
||||
def write_custom_dns_config(config, env):
|
||||
config_yaml = rtyaml.dump(config)
|
||||
with open(os.path.join(env['STORAGE_ROOT'], 'dns/custom.yaml'), "w") as f:
|
||||
f.write(config_yaml)
|
||||
|
||||
def do_dns_update(env, force=False):
|
||||
# What domains (and their zone filenames) should we build?
|
||||
domains = get_dns_domains(env)
|
||||
zonefiles = get_dns_zones(env)
|
||||
|
||||
# Custom records to add to zones.
|
||||
additional_records = get_custom_dns_config(env)
|
||||
|
||||
# Write zone files.
|
||||
os.makedirs('/etc/nsd/zones', exist_ok=True)
|
||||
zonefiles = []
|
||||
updated_domains = []
|
||||
for i, (domain, zonefile) in enumerate(zonefiles):
|
||||
# Build the records to put in the zone.
|
||||
records = build_zone(domain, domains, additional_records, env)
|
||||
for (domain, zonefile, records) in build_zones(env):
|
||||
# The final set of files will be signed.
|
||||
zonefiles.append((domain, zonefile + ".signed"))
|
||||
|
||||
# See if the zone has changed, and if so update the serial number
|
||||
# and write the zone file.
|
||||
@@ -82,14 +71,6 @@ def do_dns_update(env, force=False):
|
||||
# Zone was not updated. There were no changes.
|
||||
continue
|
||||
|
||||
# If this is a .justtesting.email domain, then post the update.
|
||||
try:
|
||||
justtestingdotemail(domain, records)
|
||||
except:
|
||||
# Hmm. Might be a network issue. If we stop now, will we end
|
||||
# up in an inconsistent state? Let's just continue.
|
||||
pass
|
||||
|
||||
# Mark that we just updated this domain.
|
||||
updated_domains.append(domain)
|
||||
|
||||
@@ -104,14 +85,8 @@ def do_dns_update(env, force=False):
|
||||
# and return True so we get a chance to re-sign it.
|
||||
sign_zone(domain, zonefile, env)
|
||||
|
||||
# Now that all zones are signed (some might not have changed and so didn't
|
||||
# just get signed now, but were before) update the zone filename so nsd.conf
|
||||
# uses the signed file.
|
||||
for i in range(len(zonefiles)):
|
||||
zonefiles[i][1] += ".signed"
|
||||
|
||||
# Write the main nsd.conf file.
|
||||
if write_nsd_conf(zonefiles, additional_records, env):
|
||||
if write_nsd_conf(zonefiles, list(get_custom_dns_config(env)), env):
|
||||
# Make sure updated_domains contains *something* if we wrote an updated
|
||||
# nsd.conf so that we know to restart nsd.
|
||||
if len(updated_domains) == 0:
|
||||
@@ -121,14 +96,18 @@ def do_dns_update(env, force=False):
|
||||
if len(updated_domains) > 0:
|
||||
shell('check_call', ["/usr/sbin/service", "nsd", "restart"])
|
||||
|
||||
# Write the OpenDKIM configuration tables.
|
||||
if write_opendkim_tables(zonefiles, env):
|
||||
# Write the OpenDKIM configuration tables for all of the domains.
|
||||
if write_opendkim_tables(get_mail_domains(env), env):
|
||||
# Settings changed. Kick opendkim.
|
||||
shell('check_call', ["/usr/sbin/service", "opendkim", "restart"])
|
||||
if len(updated_domains) == 0:
|
||||
# If this is the only thing that changed?
|
||||
updated_domains.append("OpenDKIM configuration")
|
||||
|
||||
# Clear bind9's DNS cache so our own DNS resolver is up to date.
|
||||
# (ignore errors with trap=True)
|
||||
shell('check_call', ["/usr/sbin/rndc", "flush"], trap=True)
|
||||
|
||||
if len(updated_domains) == 0:
|
||||
# if nothing was updated (except maybe OpenDKIM's files), don't show any output
|
||||
return ""
|
||||
@@ -137,7 +116,23 @@ def do_dns_update(env, force=False):
|
||||
|
||||
########################################################################
|
||||
|
||||
def build_zone(domain, all_domains, additional_records, env, is_zone=True):
|
||||
def build_zones(env):
|
||||
# What domains (and their zone filenames) should we build?
|
||||
domains = get_dns_domains(env)
|
||||
zonefiles = get_dns_zones(env)
|
||||
|
||||
# Custom records to add to zones.
|
||||
additional_records = list(get_custom_dns_config(env))
|
||||
from web_update import get_web_domains
|
||||
www_redirect_domains = set(get_web_domains(env)) - set(get_web_domains(env, include_www_redirects=False))
|
||||
|
||||
# Build DNS records for each zone.
|
||||
for domain, zonefile in zonefiles:
|
||||
# Build the records to put in the zone.
|
||||
records = build_zone(domain, domains, additional_records, www_redirect_domains, env)
|
||||
yield (domain, zonefile, records)
|
||||
|
||||
def build_zone(domain, all_domains, additional_records, www_redirect_domains, env, is_zone=True):
|
||||
records = []
|
||||
|
||||
# For top-level zones, define the authoritative name servers.
|
||||
@@ -153,7 +148,10 @@ def build_zone(domain, all_domains, additional_records, env, is_zone=True):
|
||||
records.append((None, "NS", "ns1.%s." % env["PRIMARY_HOSTNAME"], False))
|
||||
|
||||
# Define ns2.PRIMARY_HOSTNAME or whatever the user overrides.
|
||||
secondary_ns = additional_records.get("_secondary_nameserver", "ns2." + env["PRIMARY_HOSTNAME"])
|
||||
# User may provide one or more additional nameservers
|
||||
secondary_ns_list = get_secondary_dns(additional_records, mode="NS") \
|
||||
or ["ns2." + env["PRIMARY_HOSTNAME"]]
|
||||
for secondary_ns in secondary_ns_list:
|
||||
records.append((None, "NS", secondary_ns+'.', False))
|
||||
|
||||
|
||||
@@ -176,23 +174,19 @@ def build_zone(domain, all_domains, additional_records, env, is_zone=True):
|
||||
# Add a DANE TLSA record for SMTP.
|
||||
records.append(("_25._tcp", "TLSA", build_tlsa_record(env), "Recommended when DNSSEC is enabled. Advertises to mail servers connecting to the box that mandatory encryption should be used."))
|
||||
|
||||
# Add a DANE TLSA record for HTTPS, which some browser extensions might make use of.
|
||||
records.append(("_443._tcp", "TLSA", build_tlsa_record(env), "Optional. When DNSSEC is enabled, provides out-of-band HTTPS certificate validation for a few web clients that support it."))
|
||||
|
||||
# Add a SSHFP records to help SSH key validation. One per available SSH key on this system.
|
||||
for value in build_sshfp_records():
|
||||
records.append((None, "SSHFP", value, "Optional. Provides an out-of-band method for verifying an SSH key before connecting. Use 'VerifyHostKeyDNS yes' (or 'VerifyHostKeyDNS ask') when connecting with ssh."))
|
||||
|
||||
# The MX record says where email for the domain should be delivered: Here!
|
||||
records.append((None, "MX", "10 %s." % env["PRIMARY_HOSTNAME"], "Required. Specifies the hostname (and priority) of the machine that handles @%s mail." % domain))
|
||||
|
||||
# SPF record: Permit the box ('mx', see above) to send mail on behalf of
|
||||
# the domain, and no one else.
|
||||
records.append((None, "TXT", 'v=spf1 mx -all', "Recommended. Specifies that only the box is permitted to send @%s mail." % domain))
|
||||
|
||||
# Add DNS records for any subdomains of this domain. We should not have a zone for
|
||||
# both a domain and one of its subdomains.
|
||||
subdomains = [d for d in all_domains if d.endswith("." + domain)]
|
||||
for subdomain in subdomains:
|
||||
subdomain_qname = subdomain[0:-len("." + domain)]
|
||||
subzone = build_zone(subdomain, [], additional_records, env, is_zone=False)
|
||||
subzone = build_zone(subdomain, [], additional_records, www_redirect_domains, env, is_zone=False)
|
||||
for child_qname, child_rtype, child_value, child_explanation in subzone:
|
||||
if child_qname == None:
|
||||
child_qname = subdomain_qname
|
||||
@@ -200,49 +194,108 @@ def build_zone(domain, all_domains, additional_records, env, is_zone=True):
|
||||
child_qname += "." + subdomain_qname
|
||||
records.append((child_qname, child_rtype, child_value, child_explanation))
|
||||
|
||||
has_rec_base = list(records) # clone current state
|
||||
def has_rec(qname, rtype, prefix=None):
|
||||
for rec in records:
|
||||
for rec in has_rec_base:
|
||||
if rec[0] == qname and rec[1] == rtype and (prefix is None or rec[2].startswith(prefix)):
|
||||
return True
|
||||
return False
|
||||
|
||||
# The user may set other records that don't conflict with our settings.
|
||||
for qname, rtype, value in get_custom_records(domain, additional_records, env):
|
||||
# Don't put any TXT records above this line, or it'll prevent any custom TXT records.
|
||||
for qname, rtype, value in filter_custom_records(domain, additional_records):
|
||||
# Don't allow custom records for record types that override anything above.
|
||||
# But allow multiple custom records for the same rtype --- see how has_rec_base is used.
|
||||
if has_rec(qname, rtype): continue
|
||||
|
||||
# The "local" keyword on A/AAAA records are short-hand for our own IP.
|
||||
# This also flags for web configuration that the user wants a website here.
|
||||
if rtype == "A" and value == "local":
|
||||
value = env["PUBLIC_IP"]
|
||||
if rtype == "AAAA" and value == "local":
|
||||
if "PUBLIC_IPV6" in env:
|
||||
value = env["PUBLIC_IPV6"]
|
||||
else:
|
||||
continue
|
||||
records.append((qname, rtype, value, "(Set by user.)"))
|
||||
|
||||
# Add 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,
|
||||
# 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
|
||||
# during this process.
|
||||
has_rec_base = list(records)
|
||||
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),
|
||||
("www", "A", env["PUBLIC_IP"], "Optional. Sets the IP address that www.%s resolves to, e.g. for web hosting." % 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),
|
||||
("www", "AAAA", env.get('PUBLIC_IPV6'), "Optional. Sets the IPv6 address that www.%s resolves to, e.g. for web hosting." % 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:
|
||||
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 has_rec(qname, rtype):
|
||||
# Set the default record, but not if:
|
||||
# (1) there is not a user-set record of the same type already
|
||||
# (2) there is not a CNAME record already, since you can't set both and who knows what takes precedence
|
||||
# (2) there is not an A record already (if this is an A record this is a dup of (1), and if this is an AAAA record then don't set a default AAAA record if the user sets a custom A record, since the default wouldn't make sense and it should not resolve if the user doesn't provide a new AAAA record)
|
||||
if not has_rec(qname, rtype) and not has_rec(qname, "CNAME") and not has_rec(qname, "A"):
|
||||
records.append((qname, rtype, value, explanation))
|
||||
|
||||
# Don't pin the list of records that has_rec checks against anymore.
|
||||
has_rec_base = records
|
||||
|
||||
# The MX record says where email for the domain should be delivered: Here!
|
||||
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))
|
||||
|
||||
# SPF record: Permit the box ('mx', see above) to send mail on behalf of
|
||||
# the domain, and no one else.
|
||||
# Skip if the user has set a custom SPF record.
|
||||
if not has_rec(None, "TXT", prefix="v=spf1 "):
|
||||
records.append((None, "TXT", 'v=spf1 mx -all', "Recommended. Specifies that only the box is permitted to send @%s mail." % domain))
|
||||
|
||||
# Append the DKIM TXT record to the zone as generated by OpenDKIM.
|
||||
# Skip if the user has set a DKIM record already.
|
||||
opendkim_record_file = os.path.join(env['STORAGE_ROOT'], 'mail/dkim/mail.txt')
|
||||
with open(opendkim_record_file) as orf:
|
||||
m = re.match(r'(\S+)\s+IN\s+TXT\s+\( "([^"]+)"\s+"([^"]+)"\s*\)', orf.read(), re.S)
|
||||
val = m.group(2) + m.group(3)
|
||||
m = re.match(r'(\S+)\s+IN\s+TXT\s+\( ((?:"[^"]+"\s+)+)\)', orf.read(), re.S)
|
||||
val = "".join(re.findall(r'"([^"]+)"', m.group(2)))
|
||||
if not has_rec(m.group(1), "TXT", prefix="v=DKIM1; "):
|
||||
records.append((m.group(1), "TXT", val, "Recommended. Provides a way for recipients to verify that this machine sent @%s mail." % domain))
|
||||
|
||||
# Append a DMARC record.
|
||||
records.append(("_dmarc", "TXT", 'v=DMARC1; p=quarantine', "Optional. Specifies that mail that does not originate from the box but claims to be from @%s is suspect and should be quarantined by the recipient's mail system." % domain))
|
||||
# Skip if the user has set a DMARC record already.
|
||||
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))
|
||||
|
||||
# For any subdomain with an A record but no SPF or DMARC record, add strict policy records.
|
||||
all_resolvable_qnames = set(r[0] for r in records if r[1] in ("A", "AAAA"))
|
||||
for qname in all_resolvable_qnames:
|
||||
if not has_rec(qname, "TXT", prefix="v=spf1 "):
|
||||
records.append((qname, "TXT", 'v=spf1 a mx -all', "Prevents unauthorized use of this domain name for outbound mail by requiring outbound mail to originate from the indicated host(s)."))
|
||||
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', "Prevents unauthorized use of this domain name for outbound mail by requiring a valid DKIM signature."))
|
||||
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).
|
||||
if domain != env["PRIMARY_HOSTNAME"]:
|
||||
for dav in ("card", "cal"):
|
||||
qname = "_" + dav + "davs._tcp"
|
||||
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."))
|
||||
|
||||
# Adds autoconfiguration A records for all domains.
|
||||
# This allows the following clients to automatically configure email addresses in the respective applications.
|
||||
# autodiscover.* - Z-Push ActiveSync Autodiscover
|
||||
# autoconfig.* - Thunderbird Autoconfig
|
||||
if not has_rec("autodiscover", "A"):
|
||||
records.append(("autodiscover", "A", env["PUBLIC_IP"], "Provides email configuration autodiscovery support for Z-Push ActiveSync Autodiscover."))
|
||||
if not has_rec("autoconfig", "A"):
|
||||
records.append(("autoconfig", "A", env["PUBLIC_IP"], "Provides email configuration autodiscovery support for Thunderbird Autoconfig."))
|
||||
|
||||
# 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 ""))
|
||||
@@ -251,70 +304,42 @@ def build_zone(domain, all_domains, additional_records, env, is_zone=True):
|
||||
|
||||
########################################################################
|
||||
|
||||
def get_custom_records(domain, additional_records, env):
|
||||
for qname, value in additional_records.items():
|
||||
# Is this record for the domain or one of its subdomains?
|
||||
# If `domain` is None, return records for all domains.
|
||||
if domain is not None and qname != domain and not qname.endswith("." + domain): continue
|
||||
|
||||
# Turn the fully qualified domain name in the YAML file into
|
||||
# our short form (None => domain, or a relative QNAME) if
|
||||
# domain is not None.
|
||||
if domain is not None:
|
||||
if qname == domain:
|
||||
qname = None
|
||||
else:
|
||||
qname = qname[0:len(qname)-len("." + domain)]
|
||||
|
||||
# Short form. Mapping a domain name to a string is short-hand
|
||||
# for creating A records.
|
||||
if isinstance(value, str):
|
||||
values = [("A", value)]
|
||||
if value == "local" and env.get("PUBLIC_IPV6"):
|
||||
values.append( ("AAAA", value) )
|
||||
|
||||
# A mapping creates multiple records.
|
||||
elif isinstance(value, dict):
|
||||
values = value.items()
|
||||
|
||||
# No other type of data is allowed.
|
||||
else:
|
||||
raise ValueError()
|
||||
|
||||
for rtype, value2 in values:
|
||||
# The "local" keyword on A/AAAA records are short-hand for our own IP.
|
||||
# This also flags for web configuration that the user wants a website here.
|
||||
if rtype == "A" and value2 == "local":
|
||||
value2 = env["PUBLIC_IP"]
|
||||
if rtype == "AAAA" and value2 == "local":
|
||||
if "PUBLIC_IPV6" not in env: continue # no IPv6 address is available so don't set anything
|
||||
value2 = env["PUBLIC_IPV6"]
|
||||
yield (qname, rtype, value2)
|
||||
|
||||
########################################################################
|
||||
|
||||
def build_tlsa_record(env):
|
||||
# A DANE TLSA record in DNS specifies that connections on a port
|
||||
# must use TLS and the certificate must match a particular certificate.
|
||||
# must use TLS and the certificate must match a particular criteria.
|
||||
#
|
||||
# Thanks to http://blog.huque.com/2012/10/dnssec-and-certificates.html
|
||||
# for explaining all of this!
|
||||
# and https://community.letsencrypt.org/t/please-avoid-3-0-1-and-3-0-2-dane-tlsa-records-with-le-certificates/7022
|
||||
# for explaining all of this! Also see https://tools.ietf.org/html/rfc6698#section-2.1
|
||||
# and https://github.com/mail-in-a-box/mailinabox/issues/268#issuecomment-167160243.
|
||||
#
|
||||
# There are several criteria. We used to use "3 0 1" criteria, which
|
||||
# meant to pin a leaf (3) certificate (0) with SHA256 hash (1). But
|
||||
# certificates change, and especially as we move to short-lived certs
|
||||
# they change often. The TLSA record handily supports the criteria of
|
||||
# a leaf certificate (3)'s subject public key (1) with SHA256 hash (1).
|
||||
# The subject public key is the public key portion of the private key
|
||||
# that generated the CSR that generated the certificate. Since we
|
||||
# generate a private key once the first time Mail-in-a-Box is set up
|
||||
# and reuse it for all subsequent certificates, the TLSA record will
|
||||
# remain valid indefinitely.
|
||||
|
||||
# Get the hex SHA256 of the DER-encoded server certificate:
|
||||
certder = shell("check_output", [
|
||||
"/usr/bin/openssl",
|
||||
"x509",
|
||||
"-in", os.path.join(env["STORAGE_ROOT"], "ssl", "ssl_certificate.pem"),
|
||||
"-outform", "DER"
|
||||
],
|
||||
return_bytes=True)
|
||||
certhash = hashlib.sha256(certder).hexdigest()
|
||||
from ssl_certificates import load_cert_chain, load_pem
|
||||
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
||||
|
||||
fn = os.path.join(env["STORAGE_ROOT"], "ssl", "ssl_certificate.pem")
|
||||
cert = load_pem(load_cert_chain(fn)[0])
|
||||
|
||||
subject_public_key = cert.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
|
||||
# We could have also loaded ssl_private_key.pem and called priv_key.public_key().public_bytes(...)
|
||||
|
||||
pk_hash = hashlib.sha256(subject_public_key).hexdigest()
|
||||
|
||||
# Specify the TLSA parameters:
|
||||
# 3: This is the certificate that the client should trust. No CA is needed.
|
||||
# 0: The whole certificate is matched.
|
||||
# 1: The certificate is SHA256'd here.
|
||||
return "3 0 1 " + certhash
|
||||
# 3: Match the (leaf) certificate. (No CA, no trust path needed.)
|
||||
# 1: Match its subject public key.
|
||||
# 1: Use SHA256.
|
||||
return "3 1 1 " + pk_hash
|
||||
|
||||
def build_sshfp_records():
|
||||
# The SSHFP record is a way for us to embed this server's SSH public
|
||||
@@ -332,13 +357,26 @@ def build_sshfp_records():
|
||||
"ssh-rsa": 1,
|
||||
"ssh-dss": 2,
|
||||
"ecdsa-sha2-nistp256": 3,
|
||||
"ssh-ed25519": 4,
|
||||
}
|
||||
|
||||
# Get our local fingerprints by running ssh-keyscan. The output looks
|
||||
# like the known_hosts file: hostname, keytype, fingerprint. The order
|
||||
# of the output is arbitrary, so sort it to prevent spurrious updates
|
||||
# to the zone file (that trigger bumping the serial number).
|
||||
keys = shell("check_output", ["ssh-keyscan", "localhost"])
|
||||
# to the zone file (that trigger bumping the serial number). However,
|
||||
# if SSH has been configured to listen on a nonstandard port, we must
|
||||
# specify that port to sshkeyscan.
|
||||
port = 22
|
||||
with open('/etc/ssh/sshd_config', 'r') as f:
|
||||
for line in f:
|
||||
s = line.rstrip().split()
|
||||
if len(s) == 2 and s[0] == 'Port':
|
||||
try:
|
||||
port = int(s[1])
|
||||
except ValueError:
|
||||
pass
|
||||
break
|
||||
keys = shell("check_output", ["ssh-keyscan", "-t", "rsa,dsa,ecdsa,ed25519", "-p", str(port), "localhost"])
|
||||
for key in sorted(keys.split("\n")):
|
||||
if key.strip() == "" or key[0] == "#": continue
|
||||
try:
|
||||
@@ -389,9 +427,16 @@ $TTL 1800 ; default time to live
|
||||
zone += subdomain
|
||||
zone += "\tIN\t" + querytype + "\t"
|
||||
if querytype == "TXT":
|
||||
value = value.replace('\\', '\\\\') # escape backslashes
|
||||
value = value.replace('"', '\\"') # escape quotes
|
||||
value = '"' + value + '"' # wrap in quotes
|
||||
# Divide into 255-byte max substrings.
|
||||
v2 = ""
|
||||
while len(value) > 0:
|
||||
s = value[0:255]
|
||||
value = value[255:]
|
||||
s = s.replace('\\', '\\\\') # escape backslashes
|
||||
s = s.replace('"', '\\"') # escape quotes
|
||||
s = '"' + s + '"' # wrap in quotes
|
||||
v2 += s + " "
|
||||
value = v2
|
||||
zone += value + "\n"
|
||||
|
||||
# DNSSEC requires re-signing a zone periodically. That requires
|
||||
@@ -459,25 +504,9 @@ $TTL 1800 ; default time to live
|
||||
########################################################################
|
||||
|
||||
def write_nsd_conf(zonefiles, additional_records, env):
|
||||
# Basic header.
|
||||
nsdconf = """
|
||||
server:
|
||||
hide-version: yes
|
||||
|
||||
# identify the server (CH TXT ID.SERVER entry).
|
||||
identity: ""
|
||||
|
||||
# The directory for zonefile: files.
|
||||
zonesdir: "/etc/nsd/zones"
|
||||
"""
|
||||
|
||||
# Since we have bind9 listening on localhost for locally-generated
|
||||
# DNS queries that require a recursive nameserver, and the system
|
||||
# might have other network interfaces for e.g. tunnelling, we have
|
||||
# to be specific about the network interfaces that nsd binds to.
|
||||
for ipaddr in (env.get("PRIVATE_IP", "") + " " + env.get("PRIVATE_IPV6", "")).split(" "):
|
||||
if ipaddr == "": continue
|
||||
nsdconf += " ip-address: %s\n" % ipaddr
|
||||
# Write the list of zones to a configuration file.
|
||||
nsd_conf_file = "/etc/nsd/zones.conf"
|
||||
nsdconf = ""
|
||||
|
||||
# Append the zones.
|
||||
for domain, zonefile in zonefiles:
|
||||
@@ -487,39 +516,35 @@ zone:
|
||||
zonefile: %s
|
||||
""" % (domain, zonefile)
|
||||
|
||||
# If a custom secondary nameserver has been set, allow zone transfers
|
||||
# and notifies to that nameserver.
|
||||
if additional_records.get("_secondary_nameserver"):
|
||||
# Get the IP address of the nameserver by resolving it.
|
||||
hostname = additional_records.get("_secondary_nameserver")
|
||||
resolver = dns.resolver.get_default_resolver()
|
||||
response = dns.resolver.query(hostname+'.', "A")
|
||||
ipaddr = str(response[0])
|
||||
nsdconf += """\tnotify: %s NOKEY
|
||||
provide-xfr: %s NOKEY
|
||||
""" % (ipaddr, ipaddr)
|
||||
# If custom secondary nameservers have been set, allow zone transfers
|
||||
# and notifies to them.
|
||||
for ipaddr in get_secondary_dns(additional_records, mode="xfr"):
|
||||
nsdconf += "\n\tnotify: %s NOKEY\n\tprovide-xfr: %s NOKEY\n" % (ipaddr, ipaddr)
|
||||
|
||||
|
||||
# Check if the nsd.conf 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.
|
||||
with open("/etc/nsd/nsd.conf") as f:
|
||||
if os.path.exists(nsd_conf_file):
|
||||
with open(nsd_conf_file) as f:
|
||||
if f.read() == nsdconf:
|
||||
return False
|
||||
|
||||
with open("/etc/nsd/nsd.conf", "w") as f:
|
||||
# Write out new contents and return True to signal that
|
||||
# configuration changed.
|
||||
with open(nsd_conf_file, "w") as f:
|
||||
f.write(nsdconf)
|
||||
|
||||
return True
|
||||
|
||||
########################################################################
|
||||
|
||||
def dnssec_choose_algo(domain, env):
|
||||
if '.' in domain and domain.rsplit('.')[-1] in \
|
||||
("email", "guide", "fund"):
|
||||
("email", "guide", "fund", "be", "lv"):
|
||||
# At GoDaddy, RSASHA256 is the only algorithm supported
|
||||
# for .email and .guide.
|
||||
# A variety of algorithms are supported for .fund. This
|
||||
# is preferred.
|
||||
# Gandi tells me that .be does not support RSASHA1-NSEC3-SHA1
|
||||
# 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
|
||||
@@ -599,8 +624,9 @@ def sign_zone(domain, zonefile, env):
|
||||
|
||||
########################################################################
|
||||
|
||||
def write_opendkim_tables(zonefiles, env):
|
||||
# Append a record to OpenDKIM's KeyTable and SigningTable for each domain.
|
||||
def write_opendkim_tables(domains, env):
|
||||
# Append a record to OpenDKIM's KeyTable and SigningTable for each domain
|
||||
# that we send mail from (zones and all subdomains).
|
||||
|
||||
opendkim_key_file = os.path.join(env['STORAGE_ROOT'], 'mail/dkim/mail.private')
|
||||
|
||||
@@ -619,7 +645,7 @@ def write_opendkim_tables(zonefiles, env):
|
||||
"SigningTable":
|
||||
"".join(
|
||||
"*@{domain} {domain}\n".format(domain=domain)
|
||||
for domain, zonefile in zonefiles
|
||||
for domain in domains
|
||||
),
|
||||
|
||||
# The KeyTable specifies the signing domain, the DKIM selector, and the
|
||||
@@ -628,7 +654,7 @@ def write_opendkim_tables(zonefiles, env):
|
||||
"KeyTable":
|
||||
"".join(
|
||||
"{domain} {domain}:mail:{key_file}\n".format(domain=domain, key_file=opendkim_key_file)
|
||||
for domain, zonefile in zonefiles
|
||||
for domain in domains
|
||||
),
|
||||
}
|
||||
|
||||
@@ -651,7 +677,94 @@ def write_opendkim_tables(zonefiles, env):
|
||||
|
||||
########################################################################
|
||||
|
||||
def set_custom_dns_record(qname, rtype, value, env):
|
||||
def get_custom_dns_config(env):
|
||||
try:
|
||||
custom_dns = rtyaml.load(open(os.path.join(env['STORAGE_ROOT'], 'dns/custom.yaml')))
|
||||
if not isinstance(custom_dns, dict): raise ValueError() # caught below
|
||||
except:
|
||||
return [ ]
|
||||
|
||||
for qname, value in custom_dns.items():
|
||||
# Short form. Mapping a domain name to a string is short-hand
|
||||
# for creating A records.
|
||||
if isinstance(value, str):
|
||||
values = [("A", value)]
|
||||
|
||||
# A mapping creates multiple records.
|
||||
elif isinstance(value, dict):
|
||||
values = value.items()
|
||||
|
||||
# No other type of data is allowed.
|
||||
else:
|
||||
raise ValueError()
|
||||
|
||||
for rtype, value2 in values:
|
||||
if isinstance(value2, str):
|
||||
yield (qname, rtype, value2)
|
||||
elif isinstance(value2, list):
|
||||
for value3 in value2:
|
||||
yield (qname, rtype, value3)
|
||||
# No other type of data is allowed.
|
||||
else:
|
||||
raise ValueError()
|
||||
|
||||
def filter_custom_records(domain, custom_dns_iter):
|
||||
for qname, rtype, value in custom_dns_iter:
|
||||
# We don't count the secondary nameserver config (if present) as a record - that would just be
|
||||
# confusing to users. Instead it is accessed/manipulated directly via (get/set)_custom_dns_config.
|
||||
if qname == "_secondary_nameserver": continue
|
||||
|
||||
# Is this record for the domain or one of its subdomains?
|
||||
# If `domain` is None, return records for all domains.
|
||||
if domain is not None and qname != domain and not qname.endswith("." + domain): continue
|
||||
|
||||
# Turn the fully qualified domain name in the YAML file into
|
||||
# our short form (None => domain, or a relative QNAME) if
|
||||
# domain is not None.
|
||||
if domain is not None:
|
||||
if qname == domain:
|
||||
qname = None
|
||||
else:
|
||||
qname = qname[0:len(qname)-len("." + domain)]
|
||||
|
||||
yield (qname, rtype, value)
|
||||
|
||||
def write_custom_dns_config(config, env):
|
||||
# We get a list of (qname, rtype, value) triples. Convert this into a
|
||||
# nice dictionary format for storage on disk.
|
||||
from collections import OrderedDict
|
||||
config = list(config)
|
||||
dns = OrderedDict()
|
||||
seen_qnames = set()
|
||||
|
||||
# Process the qnames in the order we see them.
|
||||
for qname in [rec[0] for rec in config]:
|
||||
if qname in seen_qnames: continue
|
||||
seen_qnames.add(qname)
|
||||
|
||||
records = [(rec[1], rec[2]) for rec in config if rec[0] == qname]
|
||||
if len(records) == 1 and records[0][0] == "A":
|
||||
dns[qname] = records[0][1]
|
||||
else:
|
||||
dns[qname] = OrderedDict()
|
||||
seen_rtypes = set()
|
||||
|
||||
# Process the rtypes in the order we see them.
|
||||
for rtype in [rec[0] for rec in records]:
|
||||
if rtype in seen_rtypes: continue
|
||||
seen_rtypes.add(rtype)
|
||||
|
||||
values = [rec[1] for rec in records if rec[0] == rtype]
|
||||
if len(values) == 1:
|
||||
values = values[0]
|
||||
dns[qname][rtype] = values
|
||||
|
||||
# Write.
|
||||
config_yaml = rtyaml.dump(dns)
|
||||
with open(os.path.join(env['STORAGE_ROOT'], 'dns/custom.yaml'), "w") as f:
|
||||
f.write(config_yaml)
|
||||
|
||||
def set_custom_dns_record(qname, rtype, value, action, env):
|
||||
# validate qname
|
||||
for zone, fn in get_dns_zones(env):
|
||||
# It must match a zone apex or be a subdomain of a zone
|
||||
@@ -660,153 +773,156 @@ def set_custom_dns_record(qname, rtype, value, env):
|
||||
break
|
||||
else:
|
||||
# No match.
|
||||
if qname != "_secondary_nameserver":
|
||||
raise ValueError("%s is not a domain name or a subdomain of a domain name managed by this box." % qname)
|
||||
|
||||
# validate rtype
|
||||
rtype = rtype.upper()
|
||||
if value is not None:
|
||||
if value is not None and qname != "_secondary_nameserver":
|
||||
if not re.search(DOMAIN_RE, qname):
|
||||
raise ValueError("Invalid name.")
|
||||
|
||||
if rtype in ("A", "AAAA"):
|
||||
v = ipaddress.ip_address(value)
|
||||
if value != "local": # "local" is a special flag for us
|
||||
v = ipaddress.ip_address(value) # raises a ValueError if there's a problem
|
||||
if rtype == "A" and not isinstance(v, ipaddress.IPv4Address): raise ValueError("That's an IPv6 address.")
|
||||
if rtype == "AAAA" and not isinstance(v, ipaddress.IPv6Address): raise ValueError("That's an IPv4 address.")
|
||||
elif rtype in ("CNAME", "TXT", "SRV"):
|
||||
elif rtype in ("CNAME", "NS"):
|
||||
if rtype == "NS" and qname == zone:
|
||||
raise ValueError("NS records can only be set for subdomains.")
|
||||
|
||||
# ensure value has a trailing dot
|
||||
if not value.endswith("."):
|
||||
value = value + "."
|
||||
|
||||
if not re.search(DOMAIN_RE, value):
|
||||
raise ValueError("Invalid value.")
|
||||
elif rtype in ("CNAME", "TXT", "SRV", "MX", "SSHFP", "CAA"):
|
||||
# anything goes
|
||||
pass
|
||||
else:
|
||||
raise ValueError("Unknown record type '%s'." % rtype)
|
||||
|
||||
# load existing config
|
||||
config = get_custom_dns_config(env)
|
||||
config = list(get_custom_dns_config(env))
|
||||
|
||||
# update
|
||||
if qname not in config:
|
||||
if value is None:
|
||||
# Is asking to delete a record that does not exist.
|
||||
newconfig = []
|
||||
made_change = False
|
||||
needs_add = True
|
||||
for _qname, _rtype, _value in config:
|
||||
if action == "add":
|
||||
if (_qname, _rtype, _value) == (qname, rtype, value):
|
||||
# Record already exists. Bail.
|
||||
return False
|
||||
elif rtype == "A":
|
||||
# Add this record using the short form 'qname: value'.
|
||||
config[qname] = value
|
||||
elif action == "set":
|
||||
if (_qname, _rtype) == (qname, rtype):
|
||||
if _value == value:
|
||||
# Flag that the record already exists, don't
|
||||
# need to add it.
|
||||
needs_add = False
|
||||
else:
|
||||
# Add this record. This is the qname's first record.
|
||||
config[qname] = { rtype: value }
|
||||
# Drop any other values for this (qname, rtype).
|
||||
made_change = True
|
||||
continue
|
||||
elif action == "remove":
|
||||
if (_qname, _rtype, _value) == (qname, rtype, value):
|
||||
# Drop this record.
|
||||
made_change = True
|
||||
continue
|
||||
if value == None and (_qname, _rtype) == (qname, rtype):
|
||||
# Drop all qname-rtype records.
|
||||
made_change = True
|
||||
continue
|
||||
else:
|
||||
if isinstance(config[qname], str):
|
||||
# This is a short-form 'qname: value' implicit-A record.
|
||||
if value is None and rtype != "A":
|
||||
# Is asking to delete a record that doesn't exist.
|
||||
return False
|
||||
elif value is None and rtype == "A":
|
||||
# Delete record.
|
||||
del config[qname]
|
||||
elif rtype == "A":
|
||||
# Update, keeping short form.
|
||||
if config[qname] == "value":
|
||||
# No change.
|
||||
return False
|
||||
config[qname] = value
|
||||
else:
|
||||
# Expand short form so we can add a new record type.
|
||||
config[qname] = { "A": config[qname], rtype: value }
|
||||
else:
|
||||
# This is the qname: { ... } (dict) format.
|
||||
if value is None:
|
||||
if rtype not in config[qname]:
|
||||
# Is asking to delete a record that doesn't exist.
|
||||
return False
|
||||
else:
|
||||
# Delete the record. If it's the last record, delete the domain.
|
||||
del config[qname][rtype]
|
||||
if len(config[qname]) == 0:
|
||||
del config[qname]
|
||||
else:
|
||||
# Update the record.
|
||||
if config[qname].get(rtype) == "value":
|
||||
# No change.
|
||||
return False
|
||||
config[qname][rtype] = value
|
||||
raise ValueError("Invalid action: " + action)
|
||||
|
||||
# Preserve this record.
|
||||
newconfig.append((_qname, _rtype, _value))
|
||||
|
||||
if action in ("add", "set") and needs_add and value is not None:
|
||||
newconfig.append((qname, rtype, value))
|
||||
made_change = True
|
||||
|
||||
if made_change:
|
||||
# serialize & save
|
||||
write_custom_dns_config(config, env)
|
||||
|
||||
return True
|
||||
write_custom_dns_config(newconfig, env)
|
||||
return made_change
|
||||
|
||||
########################################################################
|
||||
|
||||
def set_secondary_dns(hostname, env):
|
||||
config = get_custom_dns_config(env)
|
||||
|
||||
if hostname in (None, ""):
|
||||
# Clear.
|
||||
if "_secondary_nameserver" in config:
|
||||
del config["_secondary_nameserver"]
|
||||
else:
|
||||
# Validate.
|
||||
hostname = hostname.strip().lower()
|
||||
def get_secondary_dns(custom_dns, mode=None):
|
||||
resolver = dns.resolver.get_default_resolver()
|
||||
resolver.timeout = 10
|
||||
|
||||
values = []
|
||||
for qname, rtype, value in custom_dns:
|
||||
if qname != '_secondary_nameserver': continue
|
||||
for hostname in value.split(" "):
|
||||
hostname = hostname.strip()
|
||||
if mode == None:
|
||||
# Just return the setting.
|
||||
values.append(hostname)
|
||||
continue
|
||||
|
||||
# This is a hostname. Before including in zone xfr lines,
|
||||
# resolve to an IP address. Otherwise just return the hostname.
|
||||
if not hostname.startswith("xfr:"):
|
||||
if mode == "xfr":
|
||||
response = dns.resolver.query(hostname+'.', "A")
|
||||
hostname = str(response[0])
|
||||
values.append(hostname)
|
||||
|
||||
# This is a zone-xfer-only IP address. Do not return if
|
||||
# we're querying for NS record hostnames. Only return if
|
||||
# we're querying for zone xfer IP addresses - return the
|
||||
# IP address.
|
||||
elif mode == "xfr":
|
||||
values.append(hostname[4:])
|
||||
|
||||
return values
|
||||
|
||||
def set_secondary_dns(hostnames, env):
|
||||
if len(hostnames) > 0:
|
||||
# Validate that all hostnames are valid and that all zone-xfer IP addresses are valid.
|
||||
resolver = dns.resolver.get_default_resolver()
|
||||
resolver.timeout = 5
|
||||
for item in hostnames:
|
||||
if not item.startswith("xfr:"):
|
||||
# Resolve hostname.
|
||||
try:
|
||||
response = dns.resolver.query(hostname, "A")
|
||||
response = resolver.query(item, "A")
|
||||
except (dns.resolver.NoNameservers, dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
|
||||
raise ValueError("Could not resolve the IP address of %s." % hostname)
|
||||
raise ValueError("Could not resolve the IP address of %s." % item)
|
||||
else:
|
||||
# Validate IP address.
|
||||
try:
|
||||
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:
|
||||
raise ValueError("'%s' is not an IPv4 address." % item[4:])
|
||||
|
||||
# Set.
|
||||
config["_secondary_nameserver"] = hostname
|
||||
set_custom_dns_record("_secondary_nameserver", "A", " ".join(hostnames), "set", env)
|
||||
else:
|
||||
# Clear.
|
||||
set_custom_dns_record("_secondary_nameserver", "A", None, "set", env)
|
||||
|
||||
# Save and apply.
|
||||
write_custom_dns_config(config, env)
|
||||
# Apply.
|
||||
return do_dns_update(env)
|
||||
|
||||
|
||||
########################################################################
|
||||
|
||||
def justtestingdotemail(domain, records):
|
||||
# If the domain is a subdomain of justtesting.email, which we own,
|
||||
# automatically populate the zone where it is set up on dns4e.com.
|
||||
# Ideally if dns4e.com supported NS records we would just have it
|
||||
# delegate DNS to us, but instead we will populate the whole zone.
|
||||
|
||||
import subprocess, json, urllib.parse
|
||||
|
||||
if not domain.endswith(".justtesting.email"):
|
||||
return
|
||||
|
||||
for subdomain, querytype, value, explanation in records:
|
||||
if querytype in ("NS",): continue
|
||||
if subdomain in ("www", "ns1", "ns2"): continue # don't do unnecessary things
|
||||
|
||||
if subdomain == None:
|
||||
subdomain = domain
|
||||
else:
|
||||
subdomain = subdomain + "." + domain
|
||||
|
||||
if querytype == "TXT":
|
||||
# nsd requires parentheses around txt records with multiple parts,
|
||||
# but DNS4E requires there be no parentheses; also it goes into
|
||||
# nsd with a newline and a tab, which we replace with a space here
|
||||
value = re.sub("^\s*\(\s*([\w\W]*)\)", r"\1", value)
|
||||
value = re.sub("\s+", " ", value)
|
||||
else:
|
||||
continue
|
||||
|
||||
print("Updating DNS for %s/%s..." % (subdomain, querytype))
|
||||
resp = json.loads(subprocess.check_output([
|
||||
"curl",
|
||||
"-s",
|
||||
"https://api.dns4e.com/v7/%s/%s" % (urllib.parse.quote(subdomain), querytype.lower()),
|
||||
"--user", "2ddbd8e88ed1495fa0ec:A97TDJV26CVUJS6hqAs0CKnhj4HvjTM7MwAAg8xb",
|
||||
"--data", "record=%s" % urllib.parse.quote(value),
|
||||
]).decode("utf8"))
|
||||
print("\t...", resp.get("message", "?"))
|
||||
def get_custom_dns_records(custom_dns, qname, rtype):
|
||||
for qname1, rtype1, value in custom_dns:
|
||||
if qname1 == qname and rtype1 == rtype:
|
||||
yield value
|
||||
return None
|
||||
|
||||
########################################################################
|
||||
|
||||
def build_recommended_dns(env):
|
||||
ret = []
|
||||
domains = get_dns_domains(env)
|
||||
zonefiles = get_dns_zones(env)
|
||||
additional_records = get_custom_dns_config(env)
|
||||
for domain, zonefile in zonefiles:
|
||||
records = build_zone(domain, domains, additional_records, env)
|
||||
|
||||
for (domain, zonefile, records) in build_zones(env):
|
||||
# remove records that we don't dislay
|
||||
records = [r for r in records if r[3] is not False]
|
||||
|
||||
@@ -834,6 +950,9 @@ def build_recommended_dns(env):
|
||||
if __name__ == "__main__":
|
||||
from utils import load_environment
|
||||
env = load_environment()
|
||||
if sys.argv[-1] == "--lint":
|
||||
write_custom_dns_config(get_custom_dns_config(env), env)
|
||||
else:
|
||||
for zone, records in build_recommended_dns(env):
|
||||
for record in records:
|
||||
print("; " + record['explanation'])
|
||||
|
||||
60
management/email_administrator.py
Executable file
60
management/email_administrator.py
Executable file
@@ -0,0 +1,60 @@
|
||||
#!/usr/local/lib/mailinabox/env/bin/python
|
||||
|
||||
# Reads in STDIN. If the stream is not empty, mail it to the system administrator.
|
||||
|
||||
import sys
|
||||
|
||||
import html
|
||||
import smtplib
|
||||
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
|
||||
# In Python 3.6:
|
||||
#from email.message import Message
|
||||
|
||||
from utils import load_environment
|
||||
|
||||
# Load system environment info.
|
||||
env = load_environment()
|
||||
|
||||
# Process command line args.
|
||||
subject = sys.argv[1]
|
||||
|
||||
# Administrator's email address.
|
||||
admin_addr = "administrator@" + env['PRIMARY_HOSTNAME']
|
||||
|
||||
# Read in STDIN.
|
||||
content = sys.stdin.read().strip()
|
||||
|
||||
# If there's nothing coming in, just exit.
|
||||
if content == "":
|
||||
sys.exit(0)
|
||||
|
||||
# create MIME message
|
||||
msg = MIMEMultipart('alternative')
|
||||
|
||||
# In Python 3.6:
|
||||
#msg = Message()
|
||||
|
||||
msg['From'] = "\"%s\" <%s>" % (env['PRIMARY_HOSTNAME'], admin_addr)
|
||||
msg['To'] = admin_addr
|
||||
msg['Subject'] = "[%s] %s" % (env['PRIMARY_HOSTNAME'], subject)
|
||||
|
||||
content_html = "<html><body><pre>{}</pre></body></html>".format(html.escape(content))
|
||||
|
||||
msg.attach(MIMEText(content, 'plain'))
|
||||
msg.attach(MIMEText(content_html, 'html'))
|
||||
|
||||
# In Python 3.6:
|
||||
#msg.set_content(content)
|
||||
#msg.add_alternative(content_html, "html")
|
||||
|
||||
# send
|
||||
smtpclient = smtplib.SMTP('127.0.0.1', 25)
|
||||
smtpclient.ehlo()
|
||||
smtpclient.sendmail(
|
||||
admin_addr, # MAIL FROM
|
||||
admin_addr, # RCPT TO
|
||||
msg.as_string())
|
||||
smtpclient.quit()
|
||||
@@ -1,121 +1,895 @@
|
||||
#!/usr/bin/python3
|
||||
#!/usr/local/lib/mailinabox/env/bin/python
|
||||
import argparse
|
||||
import datetime
|
||||
import gzip
|
||||
import os.path
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import textwrap
|
||||
from collections import defaultdict, OrderedDict
|
||||
|
||||
import re, os.path
|
||||
import dateutil.parser
|
||||
import time
|
||||
|
||||
from dateutil.relativedelta import relativedelta
|
||||
|
||||
import mailconfig
|
||||
import utils
|
||||
|
||||
def scan_mail_log(logger, env):
|
||||
|
||||
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',
|
||||
)
|
||||
|
||||
TIME_DELTAS = OrderedDict([
|
||||
('all', datetime.timedelta(weeks=52)),
|
||||
('month', datetime.timedelta(weeks=4)),
|
||||
('2weeks', datetime.timedelta(days=14)),
|
||||
('week', datetime.timedelta(days=7)),
|
||||
('2days', datetime.timedelta(days=2)),
|
||||
('day', datetime.timedelta(days=1)),
|
||||
('12hours', datetime.timedelta(hours=12)),
|
||||
('6hours', datetime.timedelta(hours=6)),
|
||||
('hour', datetime.timedelta(hours=1)),
|
||||
('30min', datetime.timedelta(minutes=30)),
|
||||
('10min', datetime.timedelta(minutes=10)),
|
||||
('5min', datetime.timedelta(minutes=5)),
|
||||
('min', datetime.timedelta(minutes=1)),
|
||||
('today', datetime.datetime.now() - datetime.datetime.now().replace(hour=0, minute=0, second=0))
|
||||
])
|
||||
|
||||
# Start date > end date!
|
||||
START_DATE = datetime.datetime.now()
|
||||
END_DATE = None
|
||||
|
||||
VERBOSE = False
|
||||
|
||||
# List of strings to filter users with
|
||||
FILTERS = None
|
||||
|
||||
# What to show (with defaults)
|
||||
SCAN_OUT = True # Outgoing email
|
||||
SCAN_IN = True # Incoming email
|
||||
SCAN_DOVECOT_LOGIN = True # Dovecot Logins
|
||||
SCAN_GREY = False # Greylisted email
|
||||
SCAN_BLOCKED = False # Rejected email
|
||||
|
||||
|
||||
def scan_files(collector):
|
||||
""" Scan files until they run out or the earliest date is reached """
|
||||
|
||||
stop_scan = False
|
||||
|
||||
for fn in LOG_FILES:
|
||||
|
||||
tmp_file = None
|
||||
|
||||
if not os.path.exists(fn):
|
||||
continue
|
||||
elif fn[-3:] == '.gz':
|
||||
tmp_file = tempfile.NamedTemporaryFile()
|
||||
shutil.copyfileobj(gzip.open(fn), tmp_file)
|
||||
|
||||
if VERBOSE:
|
||||
print("Processing file", fn, "...")
|
||||
fn = tmp_file.name if tmp_file else fn
|
||||
|
||||
for line in reverse_readline(fn):
|
||||
if scan_mail_log_line(line.strip(), collector) is False:
|
||||
if stop_scan:
|
||||
return
|
||||
stop_scan = True
|
||||
else:
|
||||
stop_scan = False
|
||||
|
||||
|
||||
|
||||
def scan_mail_log(env):
|
||||
""" Scan the system's mail log files and collect interesting data
|
||||
|
||||
This function scans the 2 most recent mail log files in /var/log/.
|
||||
|
||||
Args:
|
||||
env (dict): Dictionary containing MiaB settings
|
||||
|
||||
"""
|
||||
|
||||
collector = {
|
||||
"scan_count": 0, # Number of lines scanned
|
||||
"parse_count": 0, # Number of lines parsed (i.e. that had their contents examined)
|
||||
"scan_time": time.time(), # The time in seconds the scan took
|
||||
"sent_mail": OrderedDict(), # Data about email sent by users
|
||||
"received_mail": OrderedDict(), # Data about email received by users
|
||||
"logins": OrderedDict(), # Data about login activity
|
||||
"postgrey": {}, # Data about greylisting of email addresses
|
||||
"rejected": OrderedDict(), # Emails that were blocked
|
||||
"known_addresses": None, # Addresses handled by the Miab installation
|
||||
"other-services": set(),
|
||||
"imap-logins": { },
|
||||
"postgrey": { },
|
||||
"rejected-mail": { },
|
||||
}
|
||||
|
||||
collector["real_mail_addresses"] = set(mailconfig.get_mail_users(env)) | set(alias[0] for alias in mailconfig.get_mail_aliases(env))
|
||||
|
||||
for fn in ('/var/log/mail.log.1', '/var/log/mail.log'):
|
||||
if not os.path.exists(fn): continue
|
||||
with open(fn, 'rb') as log:
|
||||
for line in log:
|
||||
line = line.decode("utf8", errors='replace')
|
||||
scan_mail_log_line(line.strip(), collector)
|
||||
|
||||
if collector["imap-logins"]:
|
||||
logger.add_heading("Recent IMAP Logins")
|
||||
logger.print_block("The most recent login from each remote IP adddress is show.")
|
||||
for k in utils.sort_email_addresses(collector["imap-logins"], env):
|
||||
for ip, date in sorted(collector["imap-logins"][k].items(), key = lambda kv : kv[1]):
|
||||
logger.print_line(k + "\t" + str(date) + "\t" + ip)
|
||||
|
||||
if collector["postgrey"]:
|
||||
logger.add_heading("Greylisted Mail")
|
||||
logger.print_block("The following mail was greylisted, meaning the emails were temporarily rejected. Legitimate senders will try again within ten minutes.")
|
||||
logger.print_line("recipient" + "\t" + "received" + "\t" + "sender" + "\t" + "delivered")
|
||||
for recipient in utils.sort_email_addresses(collector["postgrey"], env):
|
||||
for (client_address, sender), (first_date, delivered_date) in sorted(collector["postgrey"][recipient].items(), key = lambda kv : kv[1][0]):
|
||||
logger.print_line(recipient + "\t" + str(first_date) + "\t" + sender + "\t" + (("delivered " + str(delivered_date)) if delivered_date else "no retry yet"))
|
||||
|
||||
if collector["rejected-mail"]:
|
||||
logger.add_heading("Rejected Mail")
|
||||
logger.print_block("The following incoming mail was rejected.")
|
||||
for k in utils.sort_email_addresses(collector["rejected-mail"], env):
|
||||
for date, sender, message in collector["rejected-mail"][k]:
|
||||
logger.print_line(k + "\t" + str(date) + "\t" + sender + "\t" + message)
|
||||
|
||||
if len(collector["other-services"]) > 0:
|
||||
logger.add_heading("Other")
|
||||
logger.print_block("Unrecognized services in the log: " + ", ".join(collector["other-services"]))
|
||||
|
||||
def scan_mail_log_line(line, collector):
|
||||
m = re.match(r"(\S+ \d+ \d+:\d+:\d+) (\S+) (\S+?)(\[\d+\])?: (.*)", line)
|
||||
if not m: return
|
||||
|
||||
date, system, service, pid, log = m.groups()
|
||||
date = dateutil.parser.parse(date)
|
||||
|
||||
if service == "dovecot":
|
||||
scan_dovecot_line(date, log, collector)
|
||||
|
||||
elif service == "postgrey":
|
||||
scan_postgrey_line(date, log, collector)
|
||||
|
||||
elif service == "postfix/smtpd":
|
||||
scan_postfix_smtpd_line(date, log, collector)
|
||||
|
||||
elif service in ("postfix/qmgr", "postfix/pickup", "postfix/cleanup",
|
||||
"postfix/scache", "spampd", "postfix/anvil", "postfix/master",
|
||||
"opendkim", "postfix/lmtp", "postfix/tlsmgr"):
|
||||
# nothing to look at
|
||||
try:
|
||||
import mailconfig
|
||||
collector["known_addresses"] = (set(mailconfig.get_mail_users(env)) |
|
||||
set(alias[0] for alias in mailconfig.get_mail_aliases(env)))
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
print("Scanning logs from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}".format(
|
||||
END_DATE, START_DATE)
|
||||
)
|
||||
|
||||
# Scan the lines in the log files until the date goes out of range
|
||||
scan_files(collector)
|
||||
|
||||
if not collector["scan_count"]:
|
||||
print("No log lines scanned...")
|
||||
return
|
||||
|
||||
collector["scan_time"] = time.time() - collector["scan_time"]
|
||||
|
||||
print("{scan_count} Log lines scanned, {parse_count} lines parsed in {scan_time:.2f} "
|
||||
"seconds\n".format(**collector))
|
||||
|
||||
# Print Sent Mail report
|
||||
|
||||
if collector["sent_mail"]:
|
||||
msg = "Sent email"
|
||||
print_header(msg)
|
||||
|
||||
data = OrderedDict(sorted(collector["sent_mail"].items(), key=email_sort))
|
||||
|
||||
print_user_table(
|
||||
data.keys(),
|
||||
data=[
|
||||
("sent", [u["sent_count"] for u in data.values()]),
|
||||
("hosts", [len(u["hosts"]) for u in data.values()]),
|
||||
],
|
||||
sub_data=[
|
||||
("sending hosts", [u["hosts"] for u in data.values()]),
|
||||
],
|
||||
activity=[
|
||||
("sent", [u["activity-by-hour"] for u in data.values()]),
|
||||
],
|
||||
earliest=[u["earliest"] for u in data.values()],
|
||||
latest=[u["latest"] for u in data.values()],
|
||||
)
|
||||
|
||||
accum = defaultdict(int)
|
||||
data = collector["sent_mail"].values()
|
||||
|
||||
for h in range(24):
|
||||
accum[h] = sum(d["activity-by-hour"][h] for d in data)
|
||||
|
||||
print_time_table(
|
||||
["sent"],
|
||||
[accum]
|
||||
)
|
||||
|
||||
# Print Received Mail report
|
||||
|
||||
if collector["received_mail"]:
|
||||
msg = "Received email"
|
||||
print_header(msg)
|
||||
|
||||
data = OrderedDict(sorted(collector["received_mail"].items(), key=email_sort))
|
||||
|
||||
print_user_table(
|
||||
data.keys(),
|
||||
data=[
|
||||
("received", [u["received_count"] for u in data.values()]),
|
||||
],
|
||||
activity=[
|
||||
("sent", [u["activity-by-hour"] for u in data.values()]),
|
||||
],
|
||||
earliest=[u["earliest"] for u in data.values()],
|
||||
latest=[u["latest"] for u in data.values()],
|
||||
)
|
||||
|
||||
accum = defaultdict(int)
|
||||
for h in range(24):
|
||||
accum[h] = sum(d["activity-by-hour"][h] for d in data.values())
|
||||
|
||||
print_time_table(
|
||||
["received"],
|
||||
[accum]
|
||||
)
|
||||
|
||||
# Print login report
|
||||
|
||||
if collector["logins"]:
|
||||
msg = "User logins per hour"
|
||||
print_header(msg)
|
||||
|
||||
data = OrderedDict(sorted(collector["logins"].items(), key=email_sort))
|
||||
|
||||
# Get a list of all of the protocols seen in the logs in reverse count order.
|
||||
all_protocols = defaultdict(int)
|
||||
for u in data.values():
|
||||
for protocol_name, count in u["totals_by_protocol"].items():
|
||||
all_protocols[protocol_name] += count
|
||||
all_protocols = [k for k, v in sorted(all_protocols.items(), key=lambda kv : -kv[1])]
|
||||
|
||||
print_user_table(
|
||||
data.keys(),
|
||||
data=[
|
||||
(protocol_name, [
|
||||
round(u["totals_by_protocol"][protocol_name] / (u["latest"]-u["earliest"]).total_seconds() * 60*60, 1)
|
||||
if (u["latest"]-u["earliest"]).total_seconds() > 0
|
||||
else 0 # prevent division by zero
|
||||
for u in data.values()])
|
||||
for protocol_name in all_protocols
|
||||
],
|
||||
sub_data=[
|
||||
("Protocol and Source", [[
|
||||
"{} {}: {} times".format(protocol_name, host, count)
|
||||
for (protocol_name, host), count
|
||||
in sorted(u["totals_by_protocol_and_host"].items(), key=lambda kv:-kv[1])
|
||||
] for u in data.values()])
|
||||
],
|
||||
activity=[
|
||||
(protocol_name, [u["activity-by-hour"][protocol_name] for u in data.values()])
|
||||
for protocol_name in all_protocols
|
||||
],
|
||||
earliest=[u["earliest"] for u in data.values()],
|
||||
latest=[u["latest"] for u in data.values()],
|
||||
numstr=lambda n : str(round(n, 1)),
|
||||
)
|
||||
|
||||
accum = { protocol_name: defaultdict(int) for protocol_name in all_protocols }
|
||||
for h in range(24):
|
||||
for protocol_name in all_protocols:
|
||||
accum[protocol_name][h] = sum(d["activity-by-hour"][protocol_name][h] for d in data.values())
|
||||
|
||||
print_time_table(
|
||||
all_protocols,
|
||||
[accum[protocol_name] for protocol_name in all_protocols]
|
||||
)
|
||||
|
||||
if collector["postgrey"]:
|
||||
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(textwrap.fill(
|
||||
"The following mail was greylisted, meaning the emails were temporarily rejected. "
|
||||
"Legitimate senders must try again after three minutes.",
|
||||
width=80, initial_indent=" ", subsequent_indent=" "
|
||||
), end='\n\n')
|
||||
|
||||
data = OrderedDict(sorted(collector["postgrey"].items(), key=email_sort))
|
||||
users = []
|
||||
received = []
|
||||
senders = []
|
||||
sender_clients = []
|
||||
delivered_dates = []
|
||||
|
||||
for recipient in data:
|
||||
sorted_recipients = sorted(data[recipient].items(), key=lambda kv: kv[1][0] or kv[1][1])
|
||||
for (client_address, sender), (first_date, delivered_date) in sorted_recipients:
|
||||
if first_date:
|
||||
users.append(recipient)
|
||||
received.append(first_date)
|
||||
senders.append(sender)
|
||||
delivered_dates.append(delivered_date)
|
||||
sender_clients.append(client_address)
|
||||
|
||||
print_user_table(
|
||||
users,
|
||||
data=[
|
||||
("received", received),
|
||||
("sender", senders),
|
||||
("delivered", [str(d) or "no retry yet" for d in delivered_dates]),
|
||||
("sending host", sender_clients)
|
||||
],
|
||||
delimit=True,
|
||||
)
|
||||
|
||||
if collector["rejected"]:
|
||||
msg = "Blocked Email {:%Y-%m-%d %H:%M:%S} and {:%Y-%m-%d %H:%M:%S}"
|
||||
print_header(msg.format(END_DATE, START_DATE))
|
||||
|
||||
data = OrderedDict(sorted(collector["rejected"].items(), key=email_sort))
|
||||
|
||||
rejects = []
|
||||
|
||||
if VERBOSE:
|
||||
for user_data in data.values():
|
||||
user_rejects = []
|
||||
for date, sender, message in user_data["blocked"]:
|
||||
if len(sender) > 64:
|
||||
sender = sender[:32] + "…" + sender[-32:]
|
||||
user_rejects.append("%s - %s " % (date, sender))
|
||||
user_rejects.append(" %s" % message)
|
||||
rejects.append(user_rejects)
|
||||
|
||||
print_user_table(
|
||||
data.keys(),
|
||||
data=[
|
||||
("blocked", [len(u["blocked"]) for u in data.values()]),
|
||||
],
|
||||
sub_data=[
|
||||
("blocked emails", rejects),
|
||||
],
|
||||
earliest=[u["earliest"] for u in data.values()],
|
||||
latest=[u["latest"] for u in data.values()],
|
||||
)
|
||||
|
||||
if collector["other-services"] and VERBOSE and False:
|
||||
print_header("Other services")
|
||||
print("The following unkown services were found in the log file.")
|
||||
print(" ", *sorted(list(collector["other-services"])), sep='\n│ ')
|
||||
|
||||
|
||||
def scan_mail_log_line(line, collector):
|
||||
""" Scan a log line and extract interesting data """
|
||||
|
||||
m = re.match(r"(\w+[\s]+\d+ \d+:\d+:\d+) ([\w]+ )?([\w\-/]+)[^:]*: (.*)", line)
|
||||
|
||||
if not m:
|
||||
return True
|
||||
|
||||
date, system, service, log = m.groups()
|
||||
collector["scan_count"] += 1
|
||||
|
||||
# print()
|
||||
# print("date:", date)
|
||||
# print("host:", system)
|
||||
# print("service:", service)
|
||||
# print("log:", log)
|
||||
|
||||
# Replaced the dateutil parser for a less clever way of parser that is roughly 4 times faster.
|
||||
# date = dateutil.parser.parse(date)
|
||||
date = datetime.datetime.strptime(date, '%b %d %H:%M:%S')
|
||||
date = date.replace(START_DATE.year)
|
||||
|
||||
# Check if the found date is within the time span we are scanning
|
||||
if date > START_DATE:
|
||||
# Don't process, but continue
|
||||
return True
|
||||
elif date < END_DATE:
|
||||
# Don't process, and halt
|
||||
return False
|
||||
|
||||
if service == "postfix/submission/smtpd":
|
||||
if SCAN_OUT:
|
||||
scan_postfix_submission_line(date, log, collector)
|
||||
elif service == "postfix/lmtp":
|
||||
if SCAN_IN:
|
||||
scan_postfix_lmtp_line(date, log, collector)
|
||||
elif service.endswith("-login"):
|
||||
if SCAN_DOVECOT_LOGIN:
|
||||
scan_dovecot_login_line(date, log, collector, service[:4])
|
||||
elif service == "postgrey":
|
||||
if SCAN_GREY:
|
||||
scan_postgrey_line(date, log, collector)
|
||||
elif service == "postfix/smtpd":
|
||||
if SCAN_BLOCKED:
|
||||
scan_postfix_smtpd_line(date, log, collector)
|
||||
elif service in ("postfix/qmgr", "postfix/pickup", "postfix/cleanup", "postfix/scache",
|
||||
"spampd", "postfix/anvil", "postfix/master", "opendkim", "postfix/lmtp",
|
||||
"postfix/tlsmgr", "anvil"):
|
||||
# nothing to look at
|
||||
return True
|
||||
else:
|
||||
collector["other-services"].add(service)
|
||||
return True
|
||||
|
||||
collector["parse_count"] += 1
|
||||
return True
|
||||
|
||||
def scan_dovecot_line(date, log, collector):
|
||||
m = re.match("imap-login: Login: user=<(.*?)>, method=PLAIN, rip=(.*?),", log)
|
||||
if m:
|
||||
login, ip = m.group(1), m.group(2)
|
||||
if ip != "127.0.0.1": # local login from webmail/zpush
|
||||
collector["imap-logins"].setdefault(login, {})[ip] = date
|
||||
|
||||
def scan_postgrey_line(date, log, collector):
|
||||
m = re.match("action=(greylist|pass), reason=(.*?), (?:delay=\d+, )?client_name=(.*), client_address=(.*), sender=(.*), recipient=(.*)", log)
|
||||
""" Scan a postgrey log line and extract interesting data """
|
||||
|
||||
m = re.match("action=(greylist|pass), reason=(.*?), (?:delay=\d+, )?client_name=(.*), "
|
||||
"client_address=(.*), sender=(.*), recipient=(.*)",
|
||||
log)
|
||||
|
||||
if m:
|
||||
action, reason, client_name, client_address, sender, recipient = m.groups()
|
||||
key = (client_address, sender)
|
||||
|
||||
action, reason, client_name, client_address, sender, user = m.groups()
|
||||
|
||||
if user_match(user):
|
||||
|
||||
# Might be useful to group services that use a lot of mail different servers on sub
|
||||
# domains like <sub>1.domein.com
|
||||
|
||||
# if '.' in client_name:
|
||||
# addr = client_name.split('.')
|
||||
# if len(addr) > 2:
|
||||
# client_name = '.'.join(addr[1:])
|
||||
|
||||
key = (client_address if client_name == 'unknown' else client_name, sender)
|
||||
|
||||
rep = collector["postgrey"].setdefault(user, {})
|
||||
|
||||
if action == "greylist" and reason == "new":
|
||||
collector["postgrey"].setdefault(recipient, {})[key] = (date, None)
|
||||
elif action == "pass" and reason == "triplet found" and key in collector["postgrey"].get(recipient, {}):
|
||||
collector["postgrey"][recipient][key] = (collector["postgrey"][recipient][key][0], date)
|
||||
rep[key] = (date, rep[key][1] if key in rep else None)
|
||||
elif action == "pass":
|
||||
rep[key] = (rep[key][0] if key in rep else None, date)
|
||||
|
||||
|
||||
def scan_postfix_smtpd_line(date, log, collector):
|
||||
m = re.match("NOQUEUE: reject: RCPT from .*?: (.*?); from=<(.*?)> to=<(.*?)>", log)
|
||||
if m:
|
||||
message, sender, recipient = m.groups()
|
||||
if recipient in collector["real_mail_addresses"]:
|
||||
# only log mail to real recipients
|
||||
""" Scan a postfix smtpd log line and extract interesting data """
|
||||
|
||||
# skip this, is reported in the greylisting report
|
||||
# Check if the incoming mail was rejected
|
||||
|
||||
m = re.match("NOQUEUE: reject: RCPT from .*?: (.*?); from=<(.*?)> to=<(.*?)>", log)
|
||||
|
||||
if m:
|
||||
message, sender, user = m.groups()
|
||||
|
||||
# skip this, if reported in the greylisting report
|
||||
if "Recipient address rejected: Greylisted" in message:
|
||||
return
|
||||
|
||||
# only log mail to known recipients
|
||||
if user_match(user):
|
||||
if collector["known_addresses"] is None or user in collector["known_addresses"]:
|
||||
data = collector["rejected"].get(
|
||||
user,
|
||||
{
|
||||
"blocked": [],
|
||||
"earliest": None,
|
||||
"latest": None,
|
||||
}
|
||||
)
|
||||
# simplify this one
|
||||
m = re.search(r"Client host \[(.*?)\] blocked using zen.spamhaus.org; (.*)", message)
|
||||
m = re.search(
|
||||
r"Client host \[(.*?)\] blocked using zen.spamhaus.org; (.*)", message
|
||||
)
|
||||
if m:
|
||||
message = "ip blocked: " + m.group(2)
|
||||
|
||||
else:
|
||||
# simplify this one too
|
||||
m = re.search(r"Sender address \[.*@(.*)\] blocked using dbl.spamhaus.org; (.*)", message)
|
||||
m = re.search(
|
||||
r"Sender address \[.*@(.*)\] blocked using dbl.spamhaus.org; (.*)", message
|
||||
)
|
||||
if m:
|
||||
message = "domain blocked: " + m.group(2)
|
||||
|
||||
collector["rejected-mail"].setdefault(recipient, []).append( (date, sender, message) )
|
||||
if data["latest"] is None:
|
||||
data["latest"] = date
|
||||
data["earliest"] = date
|
||||
data["blocked"].append((date, sender, message))
|
||||
|
||||
collector["rejected"][user] = data
|
||||
|
||||
|
||||
def scan_dovecot_login_line(date, log, collector, protocol_name):
|
||||
""" Scan a dovecot login log line and extract interesting data """
|
||||
|
||||
m = re.match("Info: Login: user=<(.*?)>, method=PLAIN, rip=(.*?),", log)
|
||||
|
||||
if m:
|
||||
# TODO: CHECK DIT
|
||||
user, host = m.groups()
|
||||
|
||||
if user_match(user):
|
||||
add_login(user, date, protocol_name, host, collector)
|
||||
|
||||
|
||||
def add_login(user, date, protocol_name, host, collector):
|
||||
# Get the user data, or create it if the user is new
|
||||
data = collector["logins"].get(
|
||||
user,
|
||||
{
|
||||
"earliest": None,
|
||||
"latest": None,
|
||||
"totals_by_protocol": defaultdict(int),
|
||||
"totals_by_protocol_and_host": defaultdict(int),
|
||||
"activity-by-hour": defaultdict(lambda : defaultdict(int)),
|
||||
}
|
||||
)
|
||||
|
||||
if data["latest"] is None:
|
||||
data["latest"] = date
|
||||
data["earliest"] = date
|
||||
|
||||
data["totals_by_protocol"][protocol_name] += 1
|
||||
data["totals_by_protocol_and_host"][(protocol_name, host)] += 1
|
||||
|
||||
if host not in ("127.0.0.1", "::1") or True:
|
||||
data["activity-by-hour"][protocol_name][date.hour] += 1
|
||||
|
||||
collector["logins"][user] = data
|
||||
|
||||
|
||||
def scan_postfix_lmtp_line(date, log, collector):
|
||||
""" Scan a postfix lmtp log line and extract interesting data
|
||||
|
||||
It is assumed that every log of postfix/lmtp indicates an email that was successfully
|
||||
received by Postfix.
|
||||
|
||||
"""
|
||||
|
||||
m = re.match("([A-Z0-9]+): to=<(\S+)>, .* Saved", log)
|
||||
|
||||
if m:
|
||||
_, user = m.groups()
|
||||
|
||||
if user_match(user):
|
||||
# Get the user data, or create it if the user is new
|
||||
data = collector["received_mail"].get(
|
||||
user,
|
||||
{
|
||||
"received_count": 0,
|
||||
"earliest": None,
|
||||
"latest": None,
|
||||
"activity-by-hour": defaultdict(int),
|
||||
}
|
||||
)
|
||||
|
||||
data["received_count"] += 1
|
||||
data["activity-by-hour"][date.hour] += 1
|
||||
|
||||
if data["latest"] is None:
|
||||
data["latest"] = date
|
||||
data["earliest"] = date
|
||||
|
||||
collector["received_mail"][user] = data
|
||||
|
||||
|
||||
def scan_postfix_submission_line(date, log, collector):
|
||||
""" Scan a postfix submission log line and extract interesting data
|
||||
|
||||
Lines containing a sasl_method with the values PLAIN or LOGIN are assumed to indicate a sent
|
||||
email.
|
||||
|
||||
"""
|
||||
|
||||
# Match both the 'plain' and 'login' sasl methods, since both authentication methods are
|
||||
# allowed by Dovecot
|
||||
m = re.match("([A-Z0-9]+): client=(\S+), sasl_method=(PLAIN|LOGIN), sasl_username=(\S+)", log)
|
||||
|
||||
if m:
|
||||
_, client, method, user = m.groups()
|
||||
|
||||
if user_match(user):
|
||||
# Get the user data, or create it if the user is new
|
||||
data = collector["sent_mail"].get(
|
||||
user,
|
||||
{
|
||||
"sent_count": 0,
|
||||
"hosts": set(),
|
||||
"earliest": None,
|
||||
"latest": None,
|
||||
"activity-by-hour": defaultdict(int),
|
||||
}
|
||||
)
|
||||
|
||||
data["sent_count"] += 1
|
||||
data["hosts"].add(client)
|
||||
data["activity-by-hour"][date.hour] += 1
|
||||
|
||||
if data["latest"] is None:
|
||||
data["latest"] = date
|
||||
data["earliest"] = date
|
||||
|
||||
collector["sent_mail"][user] = data
|
||||
|
||||
# Also log this as a login.
|
||||
add_login(user, date, "smtp", client, collector)
|
||||
|
||||
# Utility functions
|
||||
|
||||
def reverse_readline(filename, buf_size=8192):
|
||||
""" A generator that returns the lines of a file in reverse order
|
||||
|
||||
http://stackoverflow.com/a/23646049/801870
|
||||
|
||||
"""
|
||||
|
||||
with open(filename) as fh:
|
||||
segment = None
|
||||
offset = 0
|
||||
fh.seek(0, os.SEEK_END)
|
||||
file_size = remaining_size = fh.tell()
|
||||
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):
|
||||
""" Check if the given user matches any of the filters """
|
||||
return FILTERS is None or any(u in user for u in FILTERS)
|
||||
|
||||
|
||||
def email_sort(email):
|
||||
""" Split the given email address into a reverse order tuple, for sorting i.e (domain, name) """
|
||||
return tuple(reversed(email[0].split('@')))
|
||||
|
||||
|
||||
def valid_date(string):
|
||||
""" Validate the given date string fetched from the --startdate argument """
|
||||
try:
|
||||
date = dateutil.parser.parse(string)
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError("Unrecognized date and/or time '%s'" % string)
|
||||
return date
|
||||
|
||||
|
||||
# Print functions
|
||||
|
||||
def print_time_table(labels, data, do_print=True):
|
||||
labels.insert(0, "hour")
|
||||
data.insert(0, [str(h) for h in range(24)])
|
||||
|
||||
temp = "│ {:<%d} " % max(len(l) for l in labels)
|
||||
lines = []
|
||||
|
||||
for label in labels:
|
||||
lines.append(temp.format(label))
|
||||
|
||||
for h in range(24):
|
||||
max_len = max(len(str(d[h])) for d in data)
|
||||
base = "{:>%d} " % max(2, max_len)
|
||||
|
||||
for i, d in enumerate(data):
|
||||
lines[i] += base.format(d[h])
|
||||
|
||||
lines.insert(0, "┬ totals by time of day:")
|
||||
lines.append("└" + (len(lines[-1]) - 2) * "─")
|
||||
|
||||
if do_print:
|
||||
print("\n".join(lines))
|
||||
else:
|
||||
return lines
|
||||
|
||||
|
||||
def print_user_table(users, data=None, sub_data=None, activity=None, latest=None, earliest=None,
|
||||
delimit=False, numstr=str):
|
||||
str_temp = "{:<32} "
|
||||
lines = []
|
||||
data = data or []
|
||||
|
||||
col_widths = len(data) * [0]
|
||||
col_left = len(data) * [False]
|
||||
vert_pos = 0
|
||||
|
||||
do_accum = all(isinstance(n, (int, float)) for _, d in data for n in d)
|
||||
data_accum = len(data) * ([0] if do_accum else [" "])
|
||||
|
||||
last_user = None
|
||||
|
||||
for row, user in enumerate(users):
|
||||
|
||||
if delimit:
|
||||
if last_user and last_user != user:
|
||||
lines.append(len(lines[-1]) * "…")
|
||||
last_user = user
|
||||
|
||||
line = "{:<32} ".format(user[:31] + "…" if len(user) > 32 else user)
|
||||
|
||||
for col, (l, d) in enumerate(data):
|
||||
if isinstance(d[row], str):
|
||||
col_str = str_temp.format(d[row][:31] + "…" if len(d[row]) > 32 else d[row])
|
||||
col_left[col] = True
|
||||
elif isinstance(d[row], datetime.datetime):
|
||||
col_str = "{:<20}".format(str(d[row]))
|
||||
col_left[col] = True
|
||||
else:
|
||||
temp = "{:>%s}" % max(5, len(l) + 1, len(str(d[row])) + 1)
|
||||
col_str = temp.format(str(d[row]))
|
||||
col_widths[col] = max(col_widths[col], len(col_str))
|
||||
line += col_str
|
||||
|
||||
if do_accum:
|
||||
data_accum[col] += d[row]
|
||||
|
||||
try:
|
||||
if None not in [latest, earliest]:
|
||||
vert_pos = len(line)
|
||||
e = earliest[row]
|
||||
l = latest[row]
|
||||
timespan = relativedelta(l, e)
|
||||
if timespan.months:
|
||||
temp = " │ {:0.1f} months"
|
||||
line += temp.format(timespan.months + timespan.days / 30.0)
|
||||
elif timespan.days:
|
||||
temp = " │ {:0.1f} days"
|
||||
line += temp.format(timespan.days + timespan.hours / 24.0)
|
||||
elif (e.hour, e.minute) == (l.hour, l.minute):
|
||||
temp = " │ {:%H:%M}"
|
||||
line += temp.format(e)
|
||||
else:
|
||||
temp = " │ {:%H:%M} - {:%H:%M}"
|
||||
line += temp.format(e, l)
|
||||
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
lines.append(line.rstrip())
|
||||
|
||||
try:
|
||||
if VERBOSE:
|
||||
if sub_data is not None:
|
||||
for l, d in sub_data:
|
||||
if d[row]:
|
||||
lines.append("┬")
|
||||
lines.append("│ %s" % l)
|
||||
lines.append("├─%s─" % (len(l) * "─"))
|
||||
lines.append("│")
|
||||
max_len = 0
|
||||
for v in list(d[row]):
|
||||
lines.append("│ %s" % v)
|
||||
max_len = max(max_len, len(v))
|
||||
lines.append("└" + (max_len + 1) * "─")
|
||||
|
||||
if activity is not None:
|
||||
lines.extend(print_time_table(
|
||||
[label for label, _ in activity],
|
||||
[data[row] for _, data in activity],
|
||||
do_print=False
|
||||
))
|
||||
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
header = str_temp.format("")
|
||||
|
||||
for col, (l, _) in enumerate(data):
|
||||
if col_left[col]:
|
||||
header += l.ljust(max(5, len(l) + 1, col_widths[col]))
|
||||
else:
|
||||
header += l.rjust(max(5, len(l) + 1, col_widths[col]))
|
||||
|
||||
if None not in (latest, earliest):
|
||||
header += " │ timespan "
|
||||
|
||||
lines.insert(0, header.rstrip())
|
||||
|
||||
table_width = max(len(l) for l in lines)
|
||||
t_line = table_width * "─"
|
||||
b_line = table_width * "─"
|
||||
|
||||
if vert_pos:
|
||||
t_line = t_line[:vert_pos + 1] + "┼" + t_line[vert_pos + 2:]
|
||||
b_line = b_line[:vert_pos + 1] + ("┬" if VERBOSE else "┼") + b_line[vert_pos + 2:]
|
||||
|
||||
lines.insert(1, t_line)
|
||||
lines.append(b_line)
|
||||
|
||||
# Print totals
|
||||
|
||||
data_accum = [numstr(a) for a in data_accum]
|
||||
footer = str_temp.format("Totals:" if do_accum else " ")
|
||||
for row, (l, _) in enumerate(data):
|
||||
temp = "{:>%d}" % max(5, len(l) + 1)
|
||||
footer += temp.format(data_accum[row])
|
||||
|
||||
try:
|
||||
if None not in [latest, earliest]:
|
||||
max_l = max(latest)
|
||||
min_e = min(earliest)
|
||||
timespan = relativedelta(max_l, min_e)
|
||||
if timespan.days:
|
||||
temp = " │ {:0.2f} days"
|
||||
footer += temp.format(timespan.days + timespan.hours / 24.0)
|
||||
elif (min_e.hour, min_e.minute) == (max_l.hour, max_l.minute):
|
||||
temp = " │ {:%H:%M}"
|
||||
footer += temp.format(min_e)
|
||||
else:
|
||||
temp = " │ {:%H:%M} - {:%H:%M}"
|
||||
footer += temp.format(min_e, max_l)
|
||||
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
lines.append(footer)
|
||||
|
||||
print("\n".join(lines))
|
||||
|
||||
|
||||
def print_header(msg):
|
||||
print('\n' + msg)
|
||||
print("═" * len(msg), '\n')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from status_checks import ConsoleOutput
|
||||
env = utils.load_environment()
|
||||
scan_mail_log(ConsoleOutput(), env)
|
||||
try:
|
||||
env_vars = utils.load_environment()
|
||||
except FileNotFoundError:
|
||||
env_vars = {}
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Scan the mail log files for interesting data. By default, this script "
|
||||
"shows today's incoming and outgoing mail statistics. This script was ("
|
||||
"re)written for the Mail-in-a-box email server."
|
||||
"https://github.com/mail-in-a-box/mailinabox",
|
||||
add_help=False
|
||||
)
|
||||
|
||||
# Switches to determine what to parse and what to ignore
|
||||
|
||||
parser.add_argument("-r", "--received", help="Scan for received emails.",
|
||||
action="store_true")
|
||||
parser.add_argument("-s", "--sent", help="Scan for sent emails.",
|
||||
action="store_true")
|
||||
parser.add_argument("-l", "--logins", help="Scan for user logins to IMAP/POP3.",
|
||||
action="store_true")
|
||||
parser.add_argument("-g", "--grey", help="Scan for greylisted emails.",
|
||||
action="store_true")
|
||||
parser.add_argument("-b", "--blocked", help="Scan for blocked emails.",
|
||||
action="store_true")
|
||||
|
||||
parser.add_argument("-t", "--timespan", choices=TIME_DELTAS.keys(), default='today',
|
||||
metavar='<time span>',
|
||||
help="Time span to scan, going back from the start date. Possible values: "
|
||||
"{}. Defaults to 'today'.".format(", ".join(list(TIME_DELTAS.keys()))))
|
||||
parser.add_argument("-d", "--startdate", action="store", dest="startdate",
|
||||
type=valid_date, metavar='<start date>',
|
||||
help="Date and time to start scanning the log file from. If no date is "
|
||||
"provided, scanning will start from the current date and time.")
|
||||
parser.add_argument("-u", "--users", action="store", dest="users",
|
||||
metavar='<email1,email2,email...>',
|
||||
help="Comma separated list of (partial) email addresses to filter the "
|
||||
"output with.")
|
||||
|
||||
parser.add_argument('-h', '--help', action='help', help="Print this message and exit.")
|
||||
parser.add_argument("-v", "--verbose", help="Output extra data where available.",
|
||||
action="store_true")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.startdate is not None:
|
||||
START_DATE = args.startdate
|
||||
if args.timespan == 'today':
|
||||
args.timespan = 'day'
|
||||
print("Setting start date to {}".format(START_DATE))
|
||||
|
||||
END_DATE = START_DATE - TIME_DELTAS[args.timespan]
|
||||
|
||||
VERBOSE = args.verbose
|
||||
|
||||
if args.received or args.sent or args.logins or args.grey or args.blocked:
|
||||
SCAN_IN = args.received
|
||||
if not SCAN_IN:
|
||||
print("Ignoring received emails")
|
||||
|
||||
SCAN_OUT = args.sent
|
||||
if not SCAN_OUT:
|
||||
print("Ignoring sent emails")
|
||||
|
||||
SCAN_DOVECOT_LOGIN = args.logins
|
||||
if not SCAN_DOVECOT_LOGIN:
|
||||
print("Ignoring logins")
|
||||
|
||||
SCAN_GREY = args.grey
|
||||
if SCAN_GREY:
|
||||
print("Showing greylisted emails")
|
||||
|
||||
SCAN_BLOCKED = args.blocked
|
||||
if SCAN_BLOCKED:
|
||||
print("Showing blocked emails")
|
||||
|
||||
if args.users is not None:
|
||||
FILTERS = args.users.strip().split(',')
|
||||
|
||||
scan_mail_log(env_vars)
|
||||
|
||||
@@ -1,44 +1,95 @@
|
||||
#!/usr/bin/python3
|
||||
#!/usr/local/lib/mailinabox/env/bin/python
|
||||
|
||||
# NOTE:
|
||||
# This script is run both using the system-wide Python 3
|
||||
# interpreter (/usr/bin/python3) as well as through the
|
||||
# virtualenv (/usr/local/lib/mailinabox/env). So only
|
||||
# import packages at the top level of this script that
|
||||
# are installed in *both* contexts. We use the system-wide
|
||||
# Python 3 in setup/questions.sh to validate the email
|
||||
# address entered by the user.
|
||||
|
||||
import subprocess, shutil, os, sqlite3, re
|
||||
import utils
|
||||
from email_validator import validate_email as validate_email_, EmailNotValidError
|
||||
import idna
|
||||
|
||||
def validate_email(email, mode=None):
|
||||
# Checks that an email address is syntactically valid. Returns True/False.
|
||||
# Until Postfix supports SMTPUTF8, an email address may contain ASCII
|
||||
# characters only; IDNs must be IDNA-encoded.
|
||||
#
|
||||
# When mode=="user", we're checking that this can be a user account name.
|
||||
# Dovecot has tighter restrictions - letters, numbers, underscore, and
|
||||
# dash only!
|
||||
#
|
||||
# When mode=="alias", we're allowing anything that can be in a Postfix
|
||||
# alias table, i.e. omitting the local part ("@domain.tld") is OK.
|
||||
|
||||
# Check the syntax of the address.
|
||||
try:
|
||||
validate_email_(email,
|
||||
allow_smtputf8=False,
|
||||
check_deliverability=False,
|
||||
allow_empty_local=(mode=="alias")
|
||||
)
|
||||
except EmailNotValidError:
|
||||
return False
|
||||
|
||||
if mode == 'user':
|
||||
# There are a lot of characters permitted in email addresses, but
|
||||
# Dovecot's sqlite driver seems to get confused if there are any
|
||||
# Dovecot's sqlite auth driver seems to get confused if there are any
|
||||
# unusual characters in the address. Bah. Also note that since
|
||||
# the mailbox path name is based on the email address, the address
|
||||
# shouldn't be absurdly long and must not have a forward slash.
|
||||
|
||||
# Our database is case sensitive (oops), which affects mail delivery
|
||||
# (Postfix always queries in lowercase?), so also only permit lowercase
|
||||
# letters.
|
||||
if len(email) > 255: return False
|
||||
if re.search(r'[^\@\.a-z0-9_\-]+', email):
|
||||
return False
|
||||
|
||||
if mode == 'user':
|
||||
# For Dovecot's benefit, only allow basic characters.
|
||||
ATEXT = r'[\w\-]'
|
||||
elif mode in (None, 'alias'):
|
||||
# For aliases, we can allow any valid email address.
|
||||
# Based on RFC 2822 and https://github.com/SyrusAkbary/validate_email/blob/master/validate_email.py,
|
||||
# these characters are permitted in email addresses.
|
||||
ATEXT = r'[\w!#$%&\'\*\+\-/=\?\^`\{\|\}~]' # see 3.2.4
|
||||
else:
|
||||
raise ValueError(mode)
|
||||
# Everything looks good.
|
||||
return True
|
||||
|
||||
# per RFC 2822 3.2.4
|
||||
DOT_ATOM_TEXT_LOCAL = ATEXT + r'+(?:\.' + ATEXT + r'+)*'
|
||||
if mode == 'alias':
|
||||
# For aliases, Postfix accepts '@domain.tld' format for
|
||||
# catch-all addresses on the source side and domain aliases
|
||||
# on the destination side. Make the local part optional.
|
||||
DOT_ATOM_TEXT_LOCAL = '(?:' + DOT_ATOM_TEXT_LOCAL + ')?'
|
||||
def sanitize_idn_email_address(email):
|
||||
# The user may enter Unicode in an email address. Convert the domain part
|
||||
# to IDNA before going into our database. Leave the local part alone ---
|
||||
# although validate_email will reject non-ASCII characters.
|
||||
#
|
||||
# The domain name system only exists in ASCII, so it doesn't make sense
|
||||
# to store domain names in Unicode. We want to store what is meaningful
|
||||
# to the underlying protocols.
|
||||
try:
|
||||
localpart, domainpart = email.split("@")
|
||||
domainpart = idna.encode(domainpart).decode('ascii')
|
||||
return localpart + "@" + domainpart
|
||||
except (ValueError, idna.IDNAError):
|
||||
# ValueError: String does not have a single @-sign, so it is not
|
||||
# a valid email address. IDNAError: Domain part is not IDNA-valid.
|
||||
# Validation is not this function's job, so return value unchanged.
|
||||
# If there are non-ASCII characters it will be filtered out by
|
||||
# validate_email.
|
||||
return email
|
||||
|
||||
# as above, but we can require that the host part have at least
|
||||
# one period in it, so use a "+" rather than a "*" at the end
|
||||
DOT_ATOM_TEXT_HOST = ATEXT + r'+(?:\.' + ATEXT + r'+)+'
|
||||
def prettify_idn_email_address(email):
|
||||
# This is the opposite of sanitize_idn_email_address. We store domain
|
||||
# names in IDNA in the database, but we want to show Unicode to the user.
|
||||
try:
|
||||
localpart, domainpart = email.split("@")
|
||||
domainpart = idna.decode(domainpart.encode("ascii"))
|
||||
return localpart + "@" + domainpart
|
||||
except (ValueError, UnicodeError, idna.IDNAError):
|
||||
# Failed to decode IDNA, or the email address does not have a
|
||||
# single @-sign. Should never happen.
|
||||
return email
|
||||
|
||||
# per RFC 2822 3.4.1
|
||||
ADDR_SPEC = '^%s@%s$' % (DOT_ATOM_TEXT_LOCAL, DOT_ATOM_TEXT_HOST)
|
||||
|
||||
return re.match(ADDR_SPEC, email)
|
||||
def is_dcv_address(email):
|
||||
email = email.lower()
|
||||
for localpart in ("admin", "administrator", "postmaster", "hostmaster", "webmaster", "abuse"):
|
||||
if email.startswith(localpart+"@") or email.startswith(localpart+"+"):
|
||||
return True
|
||||
return False
|
||||
|
||||
def open_database(env, with_connection=False):
|
||||
conn = sqlite3.connect(env["STORAGE_ROOT"] + "/mail/users.sqlite")
|
||||
@@ -54,7 +105,7 @@ def get_mail_users(env):
|
||||
users = [ row[0] for row in c.fetchall() ]
|
||||
return utils.sort_email_addresses(users, env)
|
||||
|
||||
def get_mail_users_ex(env, with_archived=False, with_slow_info=False):
|
||||
def get_mail_users_ex(env, with_archived=False):
|
||||
# Returns a complex data structure of all user accounts, optionally
|
||||
# including archived (status="inactive") accounts.
|
||||
#
|
||||
@@ -65,11 +116,7 @@ def get_mail_users_ex(env, with_archived=False, with_slow_info=False):
|
||||
# {
|
||||
# email: "name@domain.tld",
|
||||
# privileges: [ "priv1", "priv2", ... ],
|
||||
# status: "active",
|
||||
# aliases: [
|
||||
# ("alias@domain.tld", ["indirect.alias@domain.tld", ...]),
|
||||
# ...
|
||||
# ]
|
||||
# status: "active" | "inactive",
|
||||
# },
|
||||
# ...
|
||||
# ]
|
||||
@@ -77,9 +124,6 @@ def get_mail_users_ex(env, with_archived=False, with_slow_info=False):
|
||||
# ...
|
||||
# ]
|
||||
|
||||
# Pre-load all aliases.
|
||||
aliases = get_mail_alias_map(env)
|
||||
|
||||
# Get users and their privileges.
|
||||
users = []
|
||||
active_accounts = set()
|
||||
@@ -95,30 +139,22 @@ def get_mail_users_ex(env, with_archived=False, with_slow_info=False):
|
||||
}
|
||||
users.append(user)
|
||||
|
||||
if with_slow_info:
|
||||
user["aliases"] = [
|
||||
(alias, sorted(evaluate_mail_alias_map(alias, aliases, env)))
|
||||
for alias in aliases.get(email.lower(), [])
|
||||
]
|
||||
user["mailbox_size"] = utils.du(os.path.join(env['STORAGE_ROOT'], 'mail/mailboxes', *reversed(email.split("@"))))
|
||||
|
||||
# Add in archived accounts.
|
||||
if with_archived:
|
||||
root = os.path.join(env['STORAGE_ROOT'], 'mail/mailboxes')
|
||||
for domain in os.listdir(root):
|
||||
if os.path.isdir(os.path.join(root, domain)):
|
||||
for user in os.listdir(os.path.join(root, domain)):
|
||||
email = user + "@" + domain
|
||||
mbox = os.path.join(root, domain, user)
|
||||
if email in active_accounts: continue
|
||||
user = {
|
||||
"email": email,
|
||||
"privileges": "",
|
||||
"privileges": [],
|
||||
"status": "inactive",
|
||||
"mailbox": mbox,
|
||||
}
|
||||
users.append(user)
|
||||
if with_slow_info:
|
||||
user["mailbox_size"] = utils.du(mbox)
|
||||
|
||||
# Group by domain.
|
||||
domains = { }
|
||||
@@ -150,13 +186,13 @@ def get_admins(env):
|
||||
return users
|
||||
|
||||
def get_mail_aliases(env):
|
||||
# Returns a sorted list of tuples of (alias, forward-to string).
|
||||
# Returns a sorted list of tuples of (address, forward-tos, permitted-senders).
|
||||
c = open_database(env)
|
||||
c.execute('SELECT source, destination FROM aliases')
|
||||
aliases = { row[0]: row[1] for row in c.fetchall() } # make dict
|
||||
c.execute('SELECT source, destination, permitted_senders FROM aliases')
|
||||
aliases = { row[0]: row for row in c.fetchall() } # make dict
|
||||
|
||||
# put in a canonical order: sort by domain, then by email address lexicographically
|
||||
aliases = [ (source, aliases[source]) for source in utils.sort_email_addresses(aliases.keys(), env) ]
|
||||
aliases = [ aliases[address] for address in utils.sort_email_addresses(aliases.keys(), env) ]
|
||||
return aliases
|
||||
|
||||
def get_mail_aliases_ex(env):
|
||||
@@ -168,8 +204,10 @@ def get_mail_aliases_ex(env):
|
||||
# domain: "domain.tld",
|
||||
# alias: [
|
||||
# {
|
||||
# source: "name@domain.tld",
|
||||
# destination: ["target1@domain.com", "target2@domain.com", ...],
|
||||
# address: "name@domain.tld", # IDNA-encoded
|
||||
# address_display: "name@domain.tld", # full Unicode
|
||||
# forwards_to: ["user1@domain.com", "receiver-only1@domain.com", ...],
|
||||
# permitted_senders: ["user1@domain.com", "sender-only1@domain.com", ...] OR null,
|
||||
# required: True|False
|
||||
# },
|
||||
# ...
|
||||
@@ -180,10 +218,10 @@ def get_mail_aliases_ex(env):
|
||||
|
||||
required_aliases = get_required_aliases(env)
|
||||
domains = {}
|
||||
for source, destination in get_mail_aliases(env):
|
||||
for address, forwards_to, permitted_senders in get_mail_aliases(env):
|
||||
# get alias info
|
||||
domain = get_domain(source)
|
||||
required = ((source in required_aliases) or (source == get_system_administrator(env)))
|
||||
domain = get_domain(address)
|
||||
required = (address in required_aliases)
|
||||
|
||||
# add to list
|
||||
if not domain in domains:
|
||||
@@ -192,50 +230,57 @@ def get_mail_aliases_ex(env):
|
||||
"aliases": [],
|
||||
}
|
||||
domains[domain]["aliases"].append({
|
||||
"source": source,
|
||||
"destination": [d.strip() for d in destination.split(",")],
|
||||
"address": address,
|
||||
"address_display": prettify_idn_email_address(address),
|
||||
"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,
|
||||
"required": required,
|
||||
})
|
||||
|
||||
# Sort domains.
|
||||
domains = [domains[domain] for domain in utils.sort_domains(domains.keys(), env)]
|
||||
|
||||
# Sort aliases within each domain first by required-ness then lexicographically by source address.
|
||||
# Sort aliases within each domain first by required-ness then lexicographically by address.
|
||||
for domain in domains:
|
||||
domain["aliases"].sort(key = lambda alias : (alias["required"], alias["source"]))
|
||||
domain["aliases"].sort(key = lambda alias : (alias["required"], alias["address"]))
|
||||
return domains
|
||||
|
||||
def get_mail_alias_map(env):
|
||||
aliases = { }
|
||||
for alias, targets in get_mail_aliases(env):
|
||||
for em in targets.split(","):
|
||||
em = em.strip().lower()
|
||||
aliases.setdefault(em, []).append(alias)
|
||||
return aliases
|
||||
|
||||
def evaluate_mail_alias_map(email, aliases, env):
|
||||
ret = set()
|
||||
for alias in aliases.get(email.lower(), []):
|
||||
ret.add(alias)
|
||||
ret |= evaluate_mail_alias_map(alias, aliases, env)
|
||||
def get_domain(emailaddr, as_unicode=True):
|
||||
# Gets the domain part of an email address. Turns IDNA
|
||||
# back to Unicode for display.
|
||||
ret = emailaddr.split('@', 1)[1]
|
||||
if as_unicode:
|
||||
try:
|
||||
ret = idna.decode(ret.encode('ascii'))
|
||||
except (ValueError, UnicodeError, idna.IDNAError):
|
||||
# Looks like we have an invalid email address in
|
||||
# the database. Now is not the time to complain.
|
||||
pass
|
||||
return ret
|
||||
|
||||
def get_domain(emailaddr):
|
||||
return emailaddr.split('@', 1)[1]
|
||||
|
||||
def get_mail_domains(env, filter_aliases=lambda alias : True):
|
||||
# Returns the domain names (IDNA-encoded) of all of the email addresses
|
||||
# configured on the system.
|
||||
return set(
|
||||
[get_domain(addr) for addr in get_mail_users(env)]
|
||||
+ [get_domain(source) for source, target in get_mail_aliases(env) if filter_aliases((source, target)) ]
|
||||
[get_domain(login, as_unicode=False) for login in get_mail_users(env)]
|
||||
+ [get_domain(address, as_unicode=False) for address, *_ in get_mail_aliases(env) if filter_aliases(address) ]
|
||||
)
|
||||
|
||||
def add_mail_user(email, pw, privs, env):
|
||||
# validate email
|
||||
if email.strip() == "":
|
||||
return ("No email address provided.", 400)
|
||||
if not validate_email(email, mode='user'):
|
||||
elif not validate_email(email):
|
||||
return ("Invalid email address.", 400)
|
||||
elif not validate_email(email, mode='user'):
|
||||
return ("User account email addresses may only use the lowercase ASCII letters a-z, the digits 0-9, underscore (_), hyphen (-), and period (.).", 400)
|
||||
elif is_dcv_address(email) and len(get_mail_users(env)) > 0:
|
||||
# Make domain control validation hijacking a little harder to mess up by preventing the usual
|
||||
# addresses used for DCV from being user accounts. Except let it be the first account because
|
||||
# during box setup the user won't know the rules.
|
||||
return ("You may not make a user account for that address because it is frequently used for domain control validation. Use an alias instead if necessary.", 400)
|
||||
|
||||
# validate password
|
||||
validate_password(pw)
|
||||
|
||||
# validate privileges
|
||||
@@ -251,7 +296,7 @@ def add_mail_user(email, pw, privs, env):
|
||||
conn, c = open_database(env, with_connection=True)
|
||||
|
||||
# hash the password
|
||||
pw = utils.shell('check_output', ["/usr/bin/doveadm", "pw", "-s", "SHA512-CRYPT", "-p", pw]).strip()
|
||||
pw = hash_password(pw)
|
||||
|
||||
# add the user to the database
|
||||
try:
|
||||
@@ -263,31 +308,15 @@ def add_mail_user(email, pw, privs, env):
|
||||
# write databasebefore next step
|
||||
conn.commit()
|
||||
|
||||
# Create the user's INBOX, Spam, and Drafts folders, and subscribe them.
|
||||
# K-9 mail will poll every 90 seconds if a Drafts folder does not exist, so create it
|
||||
# to avoid unnecessary polling.
|
||||
|
||||
# Check if the mailboxes exist before creating them. When creating a user that had previously
|
||||
# been deleted, the mailboxes will still exist because they are still on disk.
|
||||
try:
|
||||
existing_mboxes = utils.shell('check_output', ["doveadm", "mailbox", "list", "-u", email, "-8"], capture_stderr=True).split("\n")
|
||||
except subprocess.CalledProcessError as e:
|
||||
c.execute("DELETE FROM users WHERE email=?", (email,))
|
||||
conn.commit()
|
||||
return ("Failed to initialize the user: " + e.output.decode("utf8"), 400)
|
||||
|
||||
for folder in ("INBOX", "Spam", "Drafts"):
|
||||
if folder not in existing_mboxes:
|
||||
utils.shell('check_call', ["doveadm", "mailbox", "create", "-u", email, "-s", folder])
|
||||
|
||||
# Update things in case any new domains are added.
|
||||
return kick(env, "mail user added")
|
||||
|
||||
def set_mail_password(email, pw, env):
|
||||
# validate that password is acceptable
|
||||
validate_password(pw)
|
||||
|
||||
# hash the password
|
||||
pw = utils.shell('check_output', ["/usr/bin/doveadm", "pw", "-s", "SHA512-CRYPT", "-p", pw]).strip()
|
||||
pw = hash_password(pw)
|
||||
|
||||
# update the database
|
||||
conn, c = open_database(env, with_connection=True)
|
||||
@@ -297,7 +326,26 @@ def set_mail_password(email, pw, env):
|
||||
conn.commit()
|
||||
return "OK"
|
||||
|
||||
def hash_password(pw):
|
||||
# Turn the plain password into a Dovecot-format hashed password, meaning
|
||||
# something like "{SCHEME}hashedpassworddata".
|
||||
# http://wiki2.dovecot.org/Authentication/PasswordSchemes
|
||||
return utils.shell('check_output', ["/usr/bin/doveadm", "pw", "-s", "SHA512-CRYPT", "-p", pw]).strip()
|
||||
|
||||
def get_mail_password(email, env):
|
||||
# Gets the hashed password for a user. Passwords are stored in Dovecot's
|
||||
# password format, with a prefixed scheme.
|
||||
# http://wiki2.dovecot.org/Authentication/PasswordSchemes
|
||||
# update the database
|
||||
c = open_database(env)
|
||||
c.execute('SELECT password FROM users WHERE email=?', (email,))
|
||||
rows = c.fetchall()
|
||||
if len(rows) != 1:
|
||||
raise ValueError("That's not a user (%s)." % email)
|
||||
return rows[0][0]
|
||||
|
||||
def remove_mail_user(email, env):
|
||||
# remove
|
||||
conn, c = open_database(env, with_connection=True)
|
||||
c.execute("DELETE FROM users WHERE email=?", (email,))
|
||||
if c.rowcount != 1:
|
||||
@@ -310,11 +358,13 @@ def remove_mail_user(email, env):
|
||||
def parse_privs(value):
|
||||
return [p for p in value.split("\n") if p.strip() != ""]
|
||||
|
||||
def get_mail_user_privileges(email, env):
|
||||
def get_mail_user_privileges(email, env, empty_on_error=False):
|
||||
# get privs
|
||||
c = open_database(env)
|
||||
c.execute('SELECT privileges FROM users WHERE email=?', (email,))
|
||||
rows = c.fetchall()
|
||||
if len(rows) != 1:
|
||||
if empty_on_error: return []
|
||||
return ("That's not a user (%s)." % email, 400)
|
||||
return parse_privs(rows[0][0])
|
||||
|
||||
@@ -350,44 +400,93 @@ def add_remove_mail_user_privilege(email, priv, action, env):
|
||||
|
||||
return "OK"
|
||||
|
||||
def add_mail_alias(source, destination, env, update_if_exists=False, do_kick=True):
|
||||
# validate source
|
||||
if source.strip() == "":
|
||||
return ("No incoming email address provided.", 400)
|
||||
if not validate_email(source, mode='alias'):
|
||||
return ("Invalid incoming email address (%s)." % source, 400)
|
||||
def add_mail_alias(address, forwards_to, permitted_senders, env, update_if_exists=False, do_kick=True):
|
||||
# convert Unicode domain to IDNA
|
||||
address = sanitize_idn_email_address(address)
|
||||
|
||||
# Our database is case sensitive (oops), which affects mail delivery
|
||||
# (Postfix always queries in lowercase?), so force lowercase.
|
||||
address = address.lower()
|
||||
|
||||
# validate address
|
||||
address = address.strip()
|
||||
if address == "":
|
||||
return ("No email address provided.", 400)
|
||||
if not validate_email(address, mode='alias'):
|
||||
return ("Invalid email address (%s)." % address, 400)
|
||||
|
||||
# validate forwards_to
|
||||
validated_forwards_to = []
|
||||
forwards_to = forwards_to.strip()
|
||||
|
||||
# extra checks for email addresses used in domain control validation
|
||||
is_dcv_source = is_dcv_address(address)
|
||||
|
||||
# Postfix allows a single @domain.tld as the destination, which means
|
||||
# the local part on the address is preserved in the rewrite. We must
|
||||
# try to convert Unicode to IDNA first before validating that it's a
|
||||
# legitimate alias address. Don't allow this sort of rewriting for
|
||||
# DCV source addresses.
|
||||
r1 = sanitize_idn_email_address(forwards_to)
|
||||
if validate_email(r1, mode='alias') and not is_dcv_source:
|
||||
validated_forwards_to.append(r1)
|
||||
|
||||
# validate destination
|
||||
dests = []
|
||||
destination = destination.strip()
|
||||
if validate_email(destination, mode='alias'):
|
||||
# Oostfix allows a single @domain.tld as the destination, which means
|
||||
# the local part on the address is preserved in the rewrite.
|
||||
dests.append(destination)
|
||||
else:
|
||||
# Parse comma and \n-separated destination emails & validate. In this
|
||||
# case, the recipients must be complete email addresses.
|
||||
for line in destination.split("\n"):
|
||||
# case, the forwards_to must be complete email addresses.
|
||||
for line in forwards_to.split("\n"):
|
||||
for email in line.split(","):
|
||||
email = email.strip()
|
||||
if email == "": continue
|
||||
email = sanitize_idn_email_address(email) # Unicode => IDNA
|
||||
# Strip any +tag from email alias and check privileges
|
||||
privileged_email = re.sub(r"(?=\+)[^@]*(?=@)",'',email)
|
||||
if not validate_email(email):
|
||||
return ("Invalid destination email address (%s)." % email, 400)
|
||||
dests.append(email)
|
||||
if len(destination) == 0:
|
||||
return ("No destination email address(es) provided.", 400)
|
||||
destination = ",".join(dests)
|
||||
return ("Invalid receiver email address (%s)." % email, 400)
|
||||
if is_dcv_source and not is_dcv_address(email) and "admin" not in get_mail_user_privileges(privileged_email, env, empty_on_error=True):
|
||||
# Make domain control validation hijacking a little harder to mess up by
|
||||
# requiring aliases for email addresses typically used in DCV to forward
|
||||
# only to accounts that are administrators on this system.
|
||||
return ("This alias can only have administrators of this system as destinations because the address is frequently used for domain control validation.", 400)
|
||||
validated_forwards_to.append(email)
|
||||
|
||||
# validate permitted_senders
|
||||
valid_logins = get_mail_users(env)
|
||||
validated_permitted_senders = []
|
||||
permitted_senders = permitted_senders.strip()
|
||||
|
||||
# Parse comma and \n-separated sender logins & validate. The permitted_senders must be
|
||||
# valid usernames.
|
||||
for line in permitted_senders.split("\n"):
|
||||
for login in line.split(","):
|
||||
login = login.strip()
|
||||
if login == "": continue
|
||||
if login not in valid_logins:
|
||||
return ("Invalid permitted sender: %s is not a user on this system." % login, 400)
|
||||
validated_permitted_senders.append(login)
|
||||
|
||||
# Make sure the alias has either a forwards_to or a permitted_sender.
|
||||
if len(validated_forwards_to) + len(validated_permitted_senders) == 0:
|
||||
return ("The alias must either forward to an address or have a permitted sender.", 400)
|
||||
|
||||
# save to db
|
||||
|
||||
forwards_to = ",".join(validated_forwards_to)
|
||||
|
||||
if len(validated_permitted_senders) == 0:
|
||||
permitted_senders = None
|
||||
else:
|
||||
permitted_senders = ",".join(validated_permitted_senders)
|
||||
|
||||
conn, c = open_database(env, with_connection=True)
|
||||
try:
|
||||
c.execute("INSERT INTO aliases (source, destination) VALUES (?, ?)", (source, destination))
|
||||
c.execute("INSERT INTO aliases (source, destination, permitted_senders) VALUES (?, ?, ?)", (address, forwards_to, permitted_senders))
|
||||
return_status = "alias added"
|
||||
except sqlite3.IntegrityError:
|
||||
if not update_if_exists:
|
||||
return ("Alias already exists (%s)." % source, 400)
|
||||
return ("Alias already exists (%s)." % address, 400)
|
||||
else:
|
||||
c.execute("UPDATE aliases SET destination = ? WHERE source = ?", (destination, source))
|
||||
c.execute("UPDATE aliases SET destination = ?, permitted_senders = ? WHERE source = ?", (forwards_to, permitted_senders, address))
|
||||
return_status = "alias updated"
|
||||
|
||||
conn.commit()
|
||||
@@ -396,11 +495,15 @@ def add_mail_alias(source, destination, env, update_if_exists=False, do_kick=Tru
|
||||
# Update things in case any new domains are added.
|
||||
return kick(env, return_status)
|
||||
|
||||
def remove_mail_alias(source, env, do_kick=True):
|
||||
def remove_mail_alias(address, env, do_kick=True):
|
||||
# convert Unicode domain to IDNA
|
||||
address = sanitize_idn_email_address(address)
|
||||
|
||||
# remove
|
||||
conn, c = open_database(env, with_connection=True)
|
||||
c.execute("DELETE FROM aliases WHERE source=?", (source,))
|
||||
c.execute("DELETE FROM aliases WHERE source=?", (address,))
|
||||
if c.rowcount != 1:
|
||||
return ("That's not an alias (%s)." % source, 400)
|
||||
return ("That's not an alias (%s)." % address, 400)
|
||||
conn.commit()
|
||||
|
||||
if do_kick:
|
||||
@@ -414,32 +517,38 @@ def get_required_aliases(env):
|
||||
# These are the aliases that must exist.
|
||||
aliases = set()
|
||||
|
||||
# The system administrator alias is required.
|
||||
aliases.add(get_system_administrator(env))
|
||||
|
||||
# The hostmaster alias is exposed in the DNS SOA for each zone.
|
||||
aliases.add("hostmaster@" + env['PRIMARY_HOSTNAME'])
|
||||
|
||||
# Get a list of domains we serve mail for, except ones for which the only
|
||||
# email on that domain is a postmaster/admin alias to the administrator.
|
||||
# email on that domain are the required aliases or a catch-all/domain-forwarder.
|
||||
real_mail_domains = get_mail_domains(env,
|
||||
filter_aliases = lambda alias : \
|
||||
(not alias[0].startswith("postmaster@") \
|
||||
and not alias[0].startswith("admin@")) \
|
||||
or alias[1] != get_system_administrator(env) \
|
||||
filter_aliases = lambda alias :
|
||||
not alias.startswith("postmaster@")
|
||||
and not alias.startswith("admin@")
|
||||
and not alias.startswith("abuse@")
|
||||
and not alias.startswith("@")
|
||||
)
|
||||
|
||||
# Create postmaster@ and admin@ for all domains we serve mail on.
|
||||
# postmaster@ is assumed to exist by our Postfix configuration. admin@
|
||||
# isn't anything, but it might save the user some trouble e.g. when
|
||||
# Create postmaster@, admin@ and abuse@ for all domains we serve
|
||||
# mail on. postmaster@ is assumed to exist by our Postfix configuration.
|
||||
# admin@isn't anything, but it might save the user some trouble e.g. when
|
||||
# buying an SSL certificate.
|
||||
# abuse@ is part of RFC2142: https://www.ietf.org/rfc/rfc2142.txt
|
||||
for domain in real_mail_domains:
|
||||
aliases.add("postmaster@" + domain)
|
||||
aliases.add("admin@" + domain)
|
||||
aliases.add("abuse@" + domain)
|
||||
|
||||
return aliases
|
||||
|
||||
def kick(env, mail_result=None):
|
||||
results = []
|
||||
|
||||
# Inclde the current operation's result in output.
|
||||
# Include the current operation's result in output.
|
||||
|
||||
if mail_result is not None:
|
||||
results.append(mail_result + "\n")
|
||||
@@ -447,36 +556,38 @@ def kick(env, mail_result=None):
|
||||
# Ensure every required alias exists.
|
||||
|
||||
existing_users = get_mail_users(env)
|
||||
existing_aliases = get_mail_aliases(env)
|
||||
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(source):
|
||||
def ensure_admin_alias_exists(address):
|
||||
# If a user account exists with that address, we're good.
|
||||
if source in existing_users:
|
||||
if address in existing_users:
|
||||
return
|
||||
|
||||
# Does this alias exists?
|
||||
for s, t in existing_aliases:
|
||||
if s == source:
|
||||
# If the alias already exists, we're good.
|
||||
if address in existing_aliases:
|
||||
return
|
||||
|
||||
# Doesn't exist.
|
||||
administrator = get_system_administrator(env)
|
||||
add_mail_alias(source, administrator, env, do_kick=False)
|
||||
results.append("added alias %s (=> %s)\n" % (source, administrator))
|
||||
if address == administrator: return # don't make an alias from the administrator to itself --- this alias must be created manually
|
||||
add_mail_alias(address, administrator, "", env, do_kick=False)
|
||||
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
|
||||
results.append("added alias %s (=> %s)\n" % (address, administrator))
|
||||
|
||||
|
||||
for alias in required_aliases:
|
||||
ensure_admin_alias_exists(alias)
|
||||
for address in required_aliases:
|
||||
ensure_admin_alias_exists(address)
|
||||
|
||||
# Remove auto-generated postmaster/admin on domains we no
|
||||
# longer have any other email addresses for.
|
||||
for source, target in existing_aliases:
|
||||
user, domain = source.split("@")
|
||||
if user in ("postmaster", "admin") \
|
||||
and source not in required_aliases \
|
||||
and target == get_system_administrator(env):
|
||||
remove_mail_alias(source, env, do_kick=False)
|
||||
results.append("removed alias %s (was to %s; domain no longer used for email)\n" % (source, target))
|
||||
for address, forwards_to, *_ in existing_alias_records:
|
||||
user, domain = address.split("@")
|
||||
if user in ("postmaster", "admin", "abuse") \
|
||||
and address not in required_aliases \
|
||||
and forwards_to == get_system_administrator(env):
|
||||
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))
|
||||
|
||||
# Update DNS and nginx in case any domains are added/removed.
|
||||
|
||||
@@ -494,8 +605,8 @@ def validate_password(pw):
|
||||
raise ValueError("No password provided.")
|
||||
if re.search(r"[\s]", pw):
|
||||
raise ValueError("Passwords cannot contain spaces.")
|
||||
if len(pw) < 4:
|
||||
raise ValueError("Passwords must be at least four characters.")
|
||||
if len(pw) < 8:
|
||||
raise ValueError("Passwords must be at least eight characters.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
2
management/munin_start.sh
Executable file
2
management/munin_start.sh
Executable file
@@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
mkdir -p /var/run/munin && chown munin /var/run/munin
|
||||
660
management/ssl_certificates.py
Executable file
660
management/ssl_certificates.py
Executable file
@@ -0,0 +1,660 @@
|
||||
#!/usr/local/lib/mailinabox/env/bin/python
|
||||
# Utilities for installing and selecting SSL certificates.
|
||||
|
||||
import os, os.path, re, shutil, subprocess, tempfile
|
||||
|
||||
from utils import shell, safe_domain_name, sort_domains
|
||||
import idna
|
||||
|
||||
# SELECTING SSL CERTIFICATES FOR USE IN WEB
|
||||
|
||||
def get_ssl_certificates(env):
|
||||
# Scan all of the installed SSL certificates and map every domain
|
||||
# that the certificates are good for to the best certificate for
|
||||
# the domain.
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
|
||||
from cryptography.x509 import Certificate
|
||||
|
||||
# The certificates are all stored here:
|
||||
ssl_root = os.path.join(env["STORAGE_ROOT"], 'ssl')
|
||||
|
||||
# List all of the files in the SSL directory and one level deep.
|
||||
def get_file_list():
|
||||
if not os.path.exists(ssl_root):
|
||||
return
|
||||
for fn in os.listdir(ssl_root):
|
||||
if fn == 'ssl_certificate.pem':
|
||||
# This is always a symbolic link
|
||||
# to the certificate to use for
|
||||
# PRIMARY_HOSTNAME. Don't let it
|
||||
# be eligible for use because we
|
||||
# could end up creating a symlink
|
||||
# to itself --- we want to find
|
||||
# the cert that it should be a
|
||||
# symlink to.
|
||||
continue
|
||||
fn = os.path.join(ssl_root, fn)
|
||||
if os.path.isfile(fn):
|
||||
yield fn
|
||||
elif os.path.isdir(fn):
|
||||
for fn1 in os.listdir(fn):
|
||||
fn1 = os.path.join(fn, fn1)
|
||||
if os.path.isfile(fn1):
|
||||
yield fn1
|
||||
|
||||
# Remember stuff.
|
||||
private_keys = { }
|
||||
certificates = [ ]
|
||||
|
||||
# Scan each of the files to find private keys and certificates.
|
||||
# We must load all of the private keys first before processing
|
||||
# certificates so that we can check that we have a private key
|
||||
# available before using a certificate.
|
||||
for fn in get_file_list():
|
||||
try:
|
||||
pem = load_pem(load_cert_chain(fn)[0])
|
||||
except ValueError:
|
||||
# Not a valid PEM format for a PEM type we care about.
|
||||
continue
|
||||
|
||||
# Remember where we got this object.
|
||||
pem._filename = fn
|
||||
|
||||
# Is it a private key?
|
||||
if isinstance(pem, RSAPrivateKey):
|
||||
private_keys[pem.public_key().public_numbers()] = pem
|
||||
|
||||
# Is it a certificate?
|
||||
if isinstance(pem, Certificate):
|
||||
certificates.append(pem)
|
||||
|
||||
# Process the certificates.
|
||||
domains = { }
|
||||
for cert in certificates:
|
||||
# What domains is this certificate good for?
|
||||
cert_domains, primary_domain = get_certificate_domains(cert)
|
||||
cert._primary_domain = primary_domain
|
||||
|
||||
# Is there a private key file for this certificate?
|
||||
private_key = private_keys.get(cert.public_key().public_numbers())
|
||||
if not private_key:
|
||||
continue
|
||||
cert._private_key = private_key
|
||||
|
||||
# Add this cert to the list of certs usable for the domains.
|
||||
for domain in cert_domains:
|
||||
# The primary hostname can only use a certificate mapped
|
||||
# to the system private key.
|
||||
if domain == env['PRIMARY_HOSTNAME']:
|
||||
if cert._private_key._filename != os.path.join(env['STORAGE_ROOT'], 'ssl', 'ssl_private_key.pem'):
|
||||
continue
|
||||
|
||||
domains.setdefault(domain, []).append(cert)
|
||||
|
||||
# Sort the certificates to prefer good ones.
|
||||
import datetime
|
||||
now = datetime.datetime.utcnow()
|
||||
ret = { }
|
||||
for domain, cert_list in domains.items():
|
||||
#for c in cert_list: print(domain, c.not_valid_before, c.not_valid_after, "("+str(now)+")", c.issuer, c.subject, c._filename)
|
||||
cert_list.sort(key = lambda cert : (
|
||||
# must be valid NOW
|
||||
cert.not_valid_before <= now <= cert.not_valid_after,
|
||||
|
||||
# prefer one that is not self-signed
|
||||
cert.issuer != cert.subject,
|
||||
|
||||
###########################################################
|
||||
# The above lines ensure that valid certificates are chosen
|
||||
# over invalid certificates. The lines below choose between
|
||||
# multiple valid certificates available for this domain.
|
||||
###########################################################
|
||||
|
||||
# prefer one with the expiration furthest into the future so
|
||||
# that we can easily rotate to new certs as we get them
|
||||
cert.not_valid_after,
|
||||
|
||||
###########################################################
|
||||
# We always choose the certificate that is good for the
|
||||
# longest period of time. This is important for how we
|
||||
# provision certificates for Let's Encrypt. To ensure that
|
||||
# we don't re-provision every night, we have to ensure that
|
||||
# if we choose to provison a certificate that it will
|
||||
# *actually* be used so the provisioning logic knows it
|
||||
# doesn't still need to provision a certificate for the
|
||||
# domain.
|
||||
###########################################################
|
||||
|
||||
# in case a certificate is installed in multiple paths,
|
||||
# prefer the... lexicographically last one?
|
||||
cert._filename,
|
||||
|
||||
), reverse=True)
|
||||
cert = cert_list.pop(0)
|
||||
ret[domain] = {
|
||||
"private-key": cert._private_key._filename,
|
||||
"certificate": cert._filename,
|
||||
"primary-domain": cert._primary_domain,
|
||||
"certificate_object": cert,
|
||||
}
|
||||
|
||||
return ret
|
||||
|
||||
def get_domain_ssl_files(domain, ssl_certificates, env, allow_missing_cert=False, use_main_cert=True):
|
||||
if use_main_cert or not allow_missing_cert:
|
||||
# Get the system certificate info.
|
||||
ssl_private_key = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_private_key.pem'))
|
||||
ssl_certificate = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_certificate.pem'))
|
||||
system_certificate = {
|
||||
"private-key": ssl_private_key,
|
||||
"certificate": ssl_certificate,
|
||||
"primary-domain": env['PRIMARY_HOSTNAME'],
|
||||
"certificate_object": load_pem(load_cert_chain(ssl_certificate)[0]),
|
||||
}
|
||||
|
||||
if use_main_cert:
|
||||
if domain == env['PRIMARY_HOSTNAME']:
|
||||
# The primary domain must use the server certificate because
|
||||
# it is hard-coded in some service configuration files.
|
||||
return system_certificate
|
||||
|
||||
wildcard_domain = re.sub("^[^\.]+", "*", domain)
|
||||
if domain in ssl_certificates:
|
||||
return ssl_certificates[domain]
|
||||
elif wildcard_domain in ssl_certificates:
|
||||
return ssl_certificates[wildcard_domain]
|
||||
elif not allow_missing_cert:
|
||||
# No valid certificate is available for this domain! Return default files.
|
||||
return system_certificate
|
||||
else:
|
||||
# No valid certificate is available for this domain.
|
||||
return None
|
||||
|
||||
|
||||
# PROVISIONING CERTIFICATES FROM LETSENCRYPT
|
||||
|
||||
def get_certificates_to_provision(env, limit_domains=None, show_valid_certs=True):
|
||||
# Get a set of domain names that we can provision certificates for
|
||||
# using certbot. We start with domains that the box is serving web
|
||||
# for and subtract:
|
||||
# * domains not in limit_domains if limit_domains is not empty
|
||||
# * domains with custom "A" records, i.e. they are hosted elsewhere
|
||||
# * domains with actual "A" records that point elsewhere
|
||||
# * domains that already have certificates that will be valid for a while
|
||||
|
||||
from web_update import get_web_domains
|
||||
from status_checks import query_dns, normalize_ip
|
||||
|
||||
existing_certs = get_ssl_certificates(env)
|
||||
|
||||
plausible_web_domains = get_web_domains(env, exclude_dns_elsewhere=False)
|
||||
actual_web_domains = get_web_domains(env)
|
||||
|
||||
domains_to_provision = set()
|
||||
domains_cant_provision = { }
|
||||
|
||||
for domain in plausible_web_domains:
|
||||
# Skip domains that the user doesn't want to provision now.
|
||||
if limit_domains and domain not in limit_domains:
|
||||
continue
|
||||
|
||||
# Check that there isn't an explicit A/AAAA record.
|
||||
if domain not in actual_web_domains:
|
||||
domains_cant_provision[domain] = "The domain has a custom DNS A/AAAA record that points the domain elsewhere, so there is no point to installing a TLS certificate here and we could not automatically provision one anyway because provisioning requires access to the website (which isn't here)."
|
||||
|
||||
# Check that the DNS resolves to here.
|
||||
else:
|
||||
|
||||
# Does the domain resolve to this machine in public DNS? If not,
|
||||
# we can't do domain control validation. For IPv6 is configured,
|
||||
# make sure both IPv4 and IPv6 are correct because we don't know
|
||||
# how Let's Encrypt will connect.
|
||||
bad_dns = []
|
||||
for rtype, value in [("A", env["PUBLIC_IP"]), ("AAAA", env.get("PUBLIC_IPV6"))]:
|
||||
if not value: continue # IPv6 is not configured
|
||||
response = query_dns(domain, rtype)
|
||||
if response != normalize_ip(value):
|
||||
bad_dns.append("%s (%s)" % (response, rtype))
|
||||
|
||||
if bad_dns:
|
||||
domains_cant_provision[domain] = "The domain name does not resolve to this machine: " \
|
||||
+ (", ".join(bad_dns)) \
|
||||
+ "."
|
||||
|
||||
else:
|
||||
# DNS is all good.
|
||||
|
||||
# Check for a good existing cert.
|
||||
existing_cert = get_domain_ssl_files(domain, existing_certs, env, use_main_cert=False, allow_missing_cert=True)
|
||||
if existing_cert:
|
||||
existing_cert_check = check_certificate(domain, existing_cert['certificate'], existing_cert['private-key'],
|
||||
warn_if_expiring_soon=14)
|
||||
if existing_cert_check[0] == "OK":
|
||||
if show_valid_certs:
|
||||
domains_cant_provision[domain] = "The domain has a valid certificate already. ({} Certificate: {}, private key {})".format(
|
||||
existing_cert_check[1],
|
||||
existing_cert['certificate'],
|
||||
existing_cert['private-key'])
|
||||
continue
|
||||
|
||||
domains_to_provision.add(domain)
|
||||
|
||||
return (domains_to_provision, domains_cant_provision)
|
||||
|
||||
def provision_certificates(env, limit_domains):
|
||||
# What domains should we provision certificates for? And what
|
||||
# errors prevent provisioning for other domains.
|
||||
domains, domains_cant_provision = get_certificates_to_provision(env, limit_domains=limit_domains)
|
||||
|
||||
# Build a list of what happened on each domain or domain-set.
|
||||
ret = []
|
||||
for domain, error in domains_cant_provision.items():
|
||||
ret.append({
|
||||
"domains": [domain],
|
||||
"log": [error],
|
||||
"result": "skipped",
|
||||
})
|
||||
|
||||
|
||||
# Break into groups of up to 100 certificates at a time, which is Let's Encrypt's
|
||||
# limit for a single certificate. We'll sort to put related domains together.
|
||||
max_domains_per_group = 100
|
||||
domains = sort_domains(domains, env)
|
||||
certs = []
|
||||
while len(domains) > 0:
|
||||
certs.append( domains[:max_domains_per_group] )
|
||||
domains = domains[max_domains_per_group:]
|
||||
|
||||
# Prepare to provision.
|
||||
|
||||
# Where should we put our Let's Encrypt account info and state cache.
|
||||
account_path = os.path.join(env['STORAGE_ROOT'], 'ssl/lets_encrypt')
|
||||
if not os.path.exists(account_path):
|
||||
os.mkdir(account_path)
|
||||
|
||||
# Provision certificates.
|
||||
for domain_list in certs:
|
||||
ret.append({
|
||||
"domains": domain_list,
|
||||
"log": [],
|
||||
})
|
||||
try:
|
||||
# Create a CSR file for our master private key so that certbot
|
||||
# uses our private key.
|
||||
key_file = os.path.join(env['STORAGE_ROOT'], 'ssl', 'ssl_private_key.pem')
|
||||
with tempfile.NamedTemporaryFile() as csr_file:
|
||||
# We could use openssl, but certbot requires
|
||||
# that the CN domain and SAN domains match
|
||||
# the domain list passed to certbot, and adding
|
||||
# SAN domains openssl req is ridiculously complicated.
|
||||
# subprocess.check_output([
|
||||
# "openssl", "req", "-new",
|
||||
# "-key", key_file,
|
||||
# "-out", csr_file.name,
|
||||
# "-subj", "/CN=" + domain_list[0],
|
||||
# "-sha256" ])
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.serialization import Encoding
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.x509.oid import NameOID
|
||||
builder = x509.CertificateSigningRequestBuilder()
|
||||
builder = builder.subject_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, domain_list[0]) ]))
|
||||
builder = builder.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
||||
builder = builder.add_extension(x509.SubjectAlternativeName(
|
||||
[x509.DNSName(d) for d in domain_list]
|
||||
), critical=False)
|
||||
request = builder.sign(load_pem(load_cert_chain(key_file)[0]), hashes.SHA256(), default_backend())
|
||||
with open(csr_file.name, "wb") as f:
|
||||
f.write(request.public_bytes(Encoding.PEM))
|
||||
|
||||
# Provision, writing to a temporary file.
|
||||
webroot = os.path.join(account_path, 'webroot')
|
||||
os.makedirs(webroot, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
cert_file = os.path.join(d, 'cert_and_chain.pem')
|
||||
print("Provisioning TLS certificates for " + ", ".join(domain_list) + ".")
|
||||
certbotret = subprocess.check_output([
|
||||
"certbot",
|
||||
"certonly",
|
||||
#"-v", # just enough to see ACME errors
|
||||
"--non-interactive", # will fail if user hasn't registered during Mail-in-a-Box setup
|
||||
|
||||
"-d", ",".join(domain_list), # first will be main domain
|
||||
|
||||
"--csr", csr_file.name, # use our private key; unfortunately this doesn't work with auto-renew so we need to save cert manually
|
||||
"--cert-path", os.path.join(d, 'cert'), # we only use the full chain
|
||||
"--chain-path", os.path.join(d, 'chain'), # we only use the full chain
|
||||
"--fullchain-path", cert_file,
|
||||
|
||||
"--webroot", "--webroot-path", webroot,
|
||||
|
||||
"--config-dir", account_path,
|
||||
#"--staging",
|
||||
], stderr=subprocess.STDOUT).decode("utf8")
|
||||
install_cert_copy_file(cert_file, env)
|
||||
|
||||
ret[-1]["log"].append(certbotret)
|
||||
ret[-1]["result"] = "installed"
|
||||
except subprocess.CalledProcessError as e:
|
||||
ret[-1]["log"].append(e.output.decode("utf8"))
|
||||
ret[-1]["result"] = "error"
|
||||
except Exception as e:
|
||||
ret[-1]["log"].append(str(e))
|
||||
ret[-1]["result"] = "error"
|
||||
|
||||
# Run post-install steps.
|
||||
ret.extend(post_install_func(env))
|
||||
|
||||
# Return what happened with each certificate request.
|
||||
return ret
|
||||
|
||||
def provision_certificates_cmdline():
|
||||
import sys
|
||||
from exclusiveprocess import Lock
|
||||
|
||||
from utils import load_environment
|
||||
|
||||
Lock(die=True).forever()
|
||||
env = load_environment()
|
||||
|
||||
quiet = False
|
||||
domains = []
|
||||
|
||||
for arg in sys.argv[1:]:
|
||||
if arg == "-q":
|
||||
quiet = True
|
||||
else:
|
||||
domains.append(arg)
|
||||
|
||||
# Go.
|
||||
status = provision_certificates(env, limit_domains=domains)
|
||||
|
||||
# Show what happened.
|
||||
for request in status:
|
||||
if isinstance(request, str):
|
||||
print(request)
|
||||
else:
|
||||
if quiet and request['result'] == 'skipped':
|
||||
continue
|
||||
print(request['result'] + ":", ", ".join(request['domains']) + ":")
|
||||
for line in request["log"]:
|
||||
print(line)
|
||||
print()
|
||||
|
||||
|
||||
# INSTALLING A NEW CERTIFICATE FROM THE CONTROL PANEL
|
||||
|
||||
def create_csr(domain, ssl_key, country_code, env):
|
||||
return shell("check_output", [
|
||||
"openssl", "req", "-new",
|
||||
"-key", ssl_key,
|
||||
"-sha256",
|
||||
"-subj", "/C=%s/CN=%s" % (country_code, domain)])
|
||||
|
||||
def install_cert(domain, ssl_cert, ssl_chain, env, raw=False):
|
||||
# Write the combined cert+chain to a temporary path and validate that it is OK.
|
||||
# The certificate always goes above the chain.
|
||||
import tempfile
|
||||
fd, fn = tempfile.mkstemp('.pem')
|
||||
os.write(fd, (ssl_cert + '\n' + ssl_chain).encode("ascii"))
|
||||
os.close(fd)
|
||||
|
||||
# Do validation on the certificate before installing it.
|
||||
ssl_private_key = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_private_key.pem'))
|
||||
cert_status, cert_status_details = check_certificate(domain, fn, ssl_private_key)
|
||||
if cert_status != "OK":
|
||||
if cert_status == "SELF-SIGNED":
|
||||
cert_status = "This is a self-signed certificate. I can't install that."
|
||||
os.unlink(fn)
|
||||
if cert_status_details is not None:
|
||||
cert_status += " " + cert_status_details
|
||||
return cert_status
|
||||
|
||||
# Copy certifiate into ssl directory.
|
||||
install_cert_copy_file(fn, env)
|
||||
|
||||
# Run post-install steps.
|
||||
ret = post_install_func(env)
|
||||
if raw: return ret
|
||||
return "\n".join(ret)
|
||||
|
||||
|
||||
def install_cert_copy_file(fn, env):
|
||||
# Where to put it?
|
||||
# Make a unique path for the certificate.
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from binascii import hexlify
|
||||
cert = load_pem(load_cert_chain(fn)[0])
|
||||
all_domains, cn = get_certificate_domains(cert)
|
||||
path = "%s-%s-%s.pem" % (
|
||||
safe_domain_name(cn), # common name, which should be filename safe because it is IDNA-encoded, but in case of a malformed cert make sure it's ok to use as a filename
|
||||
cert.not_valid_after.date().isoformat().replace("-", ""), # expiration date
|
||||
hexlify(cert.fingerprint(hashes.SHA256())).decode("ascii")[0:8], # fingerprint prefix
|
||||
)
|
||||
ssl_certificate = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', path))
|
||||
|
||||
# Install the certificate.
|
||||
os.makedirs(os.path.dirname(ssl_certificate), exist_ok=True)
|
||||
shutil.move(fn, ssl_certificate)
|
||||
|
||||
|
||||
def post_install_func(env):
|
||||
ret = []
|
||||
|
||||
# Get the certificate to use for PRIMARY_HOSTNAME.
|
||||
ssl_certificates = get_ssl_certificates(env)
|
||||
cert = get_domain_ssl_files(env['PRIMARY_HOSTNAME'], ssl_certificates, env, use_main_cert=False)
|
||||
if not cert:
|
||||
# Ruh-row, we don't have any certificate usable
|
||||
# for the primary hostname.
|
||||
ret.append("there is no valid certificate for " + env['PRIMARY_HOSTNAME'])
|
||||
|
||||
# Symlink the best cert for PRIMARY_HOSTNAME to the system
|
||||
# certificate path, which is hard-coded for various purposes, and then
|
||||
# restart postfix and dovecot.
|
||||
system_ssl_certificate = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_certificate.pem'))
|
||||
if cert and os.readlink(system_ssl_certificate) != cert['certificate']:
|
||||
# Update symlink.
|
||||
ret.append("updating primary certificate")
|
||||
ssl_certificate = cert['certificate']
|
||||
os.unlink(system_ssl_certificate)
|
||||
os.symlink(ssl_certificate, system_ssl_certificate)
|
||||
|
||||
# Restart postfix and dovecot so they pick up the new file.
|
||||
shell('check_call', ["/usr/sbin/service", "postfix", "restart"])
|
||||
shell('check_call', ["/usr/sbin/service", "dovecot", "restart"])
|
||||
ret.append("mail services restarted")
|
||||
|
||||
# The DANE TLSA record will remain valid so long as the private key
|
||||
# hasn't changed. We don't ever change the private key automatically.
|
||||
# If the user does it, they must manually update DNS.
|
||||
|
||||
# Update the web configuration so nginx picks up the new certificate file.
|
||||
from web_update import do_web_update
|
||||
ret.append( do_web_update(env) )
|
||||
|
||||
return ret
|
||||
|
||||
# VALIDATION OF CERTIFICATES
|
||||
|
||||
def check_certificate(domain, ssl_certificate, ssl_private_key, warn_if_expiring_soon=10, rounded_time=False, just_check_domain=False):
|
||||
# Check that the ssl_certificate & ssl_private_key files are good
|
||||
# for the provided domain.
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
|
||||
from cryptography.x509 import Certificate
|
||||
|
||||
# The ssl_certificate file may contain a chain of certificates. We'll
|
||||
# need to split that up before we can pass anything to openssl or
|
||||
# parse them in Python. Parse it with the cryptography library.
|
||||
try:
|
||||
ssl_cert_chain = load_cert_chain(ssl_certificate)
|
||||
cert = load_pem(ssl_cert_chain[0])
|
||||
if not isinstance(cert, Certificate): raise ValueError("This is not a certificate file.")
|
||||
except ValueError as e:
|
||||
return ("There is a problem with the certificate file: %s" % str(e), None)
|
||||
|
||||
# First check that the domain name is one of the names allowed by
|
||||
# the certificate.
|
||||
if domain is not None:
|
||||
certificate_names, cert_primary_name = get_certificate_domains(cert)
|
||||
|
||||
# Check that the domain appears among the acceptable names, or a wildcard
|
||||
# form of the domain name (which is a stricter check than the specs but
|
||||
# should work in normal cases).
|
||||
wildcard_domain = re.sub("^[^\.]+", "*", domain)
|
||||
if domain not in certificate_names and wildcard_domain not in certificate_names:
|
||||
return ("The certificate is for the wrong domain name. It is for %s."
|
||||
% ", ".join(sorted(certificate_names)), None)
|
||||
|
||||
# Second, check that the certificate matches the private key.
|
||||
if ssl_private_key is not None:
|
||||
try:
|
||||
priv_key = load_pem(open(ssl_private_key, 'rb').read())
|
||||
except ValueError as e:
|
||||
return ("The private key file %s is not a private key file: %s" % (ssl_private_key, str(e)), None)
|
||||
|
||||
if not isinstance(priv_key, RSAPrivateKey):
|
||||
return ("The private key file %s is not a private key file." % ssl_private_key, None)
|
||||
|
||||
if priv_key.public_key().public_numbers() != cert.public_key().public_numbers():
|
||||
return ("The certificate does not correspond to the private key at %s." % ssl_private_key, None)
|
||||
|
||||
# We could also use the openssl command line tool to get the modulus
|
||||
# listed in each file. The output of each command below looks like "Modulus=XXXXX".
|
||||
# $ openssl rsa -inform PEM -noout -modulus -in ssl_private_key
|
||||
# $ openssl x509 -in ssl_certificate -noout -modulus
|
||||
|
||||
# Third, check if the certificate is self-signed. Return a special flag string.
|
||||
if cert.issuer == cert.subject:
|
||||
return ("SELF-SIGNED", None)
|
||||
|
||||
# When selecting which certificate to use for non-primary domains, we check if the primary
|
||||
# certificate or a www-parent-domain certificate is good for the domain. There's no need
|
||||
# to run extra checks beyond this point.
|
||||
if just_check_domain:
|
||||
return ("OK", None)
|
||||
|
||||
# Check that the certificate hasn't expired. The datetimes returned by the
|
||||
# certificate are 'naive' and in UTC. We need to get the current time in UTC.
|
||||
import datetime
|
||||
now = datetime.datetime.utcnow()
|
||||
if not(cert.not_valid_before <= now <= cert.not_valid_after):
|
||||
return ("The certificate has expired or is not yet valid. It is valid from %s to %s." % (cert.not_valid_before, cert.not_valid_after), None)
|
||||
|
||||
# Next validate that the certificate is valid. This checks whether the certificate
|
||||
# is self-signed, that the chain of trust makes sense, that it is signed by a CA
|
||||
# that Ubuntu has installed on this machine's list of CAs, and I think that it hasn't
|
||||
# expired.
|
||||
|
||||
# The certificate chain has to be passed separately and is given via STDIN.
|
||||
# This command returns a non-zero exit status in most cases, so trap errors.
|
||||
retcode, verifyoutput = shell('check_output', [
|
||||
"openssl",
|
||||
"verify", "-verbose",
|
||||
"-purpose", "sslserver", "-policy_check",]
|
||||
+ ([] if len(ssl_cert_chain) == 1 else ["-untrusted", "/proc/self/fd/0"])
|
||||
+ [ssl_certificate],
|
||||
input=b"\n\n".join(ssl_cert_chain[1:]),
|
||||
trap=True)
|
||||
|
||||
if "self signed" in verifyoutput:
|
||||
# Certificate is self-signed. Probably we detected this above.
|
||||
return ("SELF-SIGNED", None)
|
||||
|
||||
elif retcode != 0:
|
||||
if "unable to get local issuer certificate" in verifyoutput:
|
||||
return ("The certificate is missing an intermediate chain or the intermediate chain is incorrect or incomplete. (%s)" % verifyoutput, None)
|
||||
|
||||
# There is some unknown problem. Return the `openssl verify` raw output.
|
||||
return ("There is a problem with the certificate.", verifyoutput.strip())
|
||||
|
||||
else:
|
||||
# `openssl verify` returned a zero exit status so the cert is currently
|
||||
# good.
|
||||
|
||||
# But is it expiring soon?
|
||||
cert_expiration_date = cert.not_valid_after
|
||||
ndays = (cert_expiration_date-now).days
|
||||
if not rounded_time or ndays <= 10:
|
||||
# Yikes better renew soon!
|
||||
expiry_info = "The certificate expires in %d days on %s." % (ndays, cert_expiration_date.strftime("%x"))
|
||||
else:
|
||||
# We'll renew it with Lets Encrypt.
|
||||
expiry_info = "The certificate expires on %s." % cert_expiration_date.strftime("%x")
|
||||
|
||||
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
|
||||
# certificate, which occurs on day 14.
|
||||
return ("The certificate is expiring soon: " + expiry_info, None)
|
||||
|
||||
# Return the special OK code.
|
||||
return ("OK", expiry_info)
|
||||
|
||||
def load_cert_chain(pemfile):
|
||||
# A certificate .pem file may contain a chain of certificates.
|
||||
# Load the file and split them apart.
|
||||
re_pem = rb"(-+BEGIN (?:.+)-+[\r\n]+(?:[A-Za-z0-9+/=]{1,64}[\r\n]+)+-+END (?:.+)-+[\r\n]+)"
|
||||
with open(pemfile, "rb") as f:
|
||||
pem = f.read() + b"\n" # ensure trailing newline
|
||||
pemblocks = re.findall(re_pem, pem)
|
||||
if len(pemblocks) == 0:
|
||||
raise ValueError("File does not contain valid PEM data.")
|
||||
return pemblocks
|
||||
|
||||
def load_pem(pem):
|
||||
# Parse a "---BEGIN .... END---" PEM string and return a Python object for it
|
||||
# using classes from the cryptography package.
|
||||
from cryptography.x509 import load_pem_x509_certificate
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
pem_type = re.match(b"-+BEGIN (.*?)-+[\r\n]", pem)
|
||||
if pem_type is None:
|
||||
raise ValueError("File is not a valid PEM-formatted file.")
|
||||
pem_type = pem_type.group(1)
|
||||
if pem_type in (b"RSA PRIVATE KEY", b"PRIVATE KEY"):
|
||||
return serialization.load_pem_private_key(pem, password=None, backend=default_backend())
|
||||
if pem_type == b"CERTIFICATE":
|
||||
return load_pem_x509_certificate(pem, default_backend())
|
||||
raise ValueError("Unsupported PEM object type: " + pem_type.decode("ascii", "replace"))
|
||||
|
||||
def get_certificate_domains(cert):
|
||||
from cryptography.x509 import DNSName, ExtensionNotFound, OID_COMMON_NAME, OID_SUBJECT_ALTERNATIVE_NAME
|
||||
import idna
|
||||
|
||||
names = set()
|
||||
cn = None
|
||||
|
||||
# The domain may be found in the Subject Common Name (CN). This comes back as an IDNA (ASCII)
|
||||
# string, which is the format we store domains in - so good.
|
||||
try:
|
||||
cn = cert.subject.get_attributes_for_oid(OID_COMMON_NAME)[0].value
|
||||
names.add(cn)
|
||||
except IndexError:
|
||||
# No common name? Certificate is probably generated incorrectly.
|
||||
# But we'll let it error-out when it doesn't find the domain.
|
||||
pass
|
||||
|
||||
# ... or be one of the Subject Alternative Names. The cryptography library handily IDNA-decodes
|
||||
# the names for us. We must encode back to ASCII, but wildcard certificates can't pass through
|
||||
# IDNA encoding/decoding so we must special-case. See https://github.com/pyca/cryptography/pull/2071.
|
||||
def idna_decode_dns_name(dns_name):
|
||||
if dns_name.startswith("*."):
|
||||
return "*." + idna.encode(dns_name[2:]).decode('ascii')
|
||||
else:
|
||||
return idna.encode(dns_name).decode('ascii')
|
||||
|
||||
try:
|
||||
sans = cert.extensions.get_extension_for_oid(OID_SUBJECT_ALTERNATIVE_NAME).value.get_values_for_type(DNSName)
|
||||
for san in sans:
|
||||
names.add(idna_decode_dns_name(san))
|
||||
except ExtensionNotFound:
|
||||
pass
|
||||
|
||||
return names, cn
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Provision certificates.
|
||||
provision_certificates_cmdline()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,32 +7,62 @@
|
||||
|
||||
<h3>Add a mail alias</h3>
|
||||
|
||||
<p>Aliases are email forwarders. An alias can forward email to a <a href="javascript:show_panel('users')">mail user</a> or to any email address.</p>
|
||||
<p>Aliases are email forwarders. An alias can forward email to a <a href="#" onclick="return show_panel('users')">mail user</a> or to any email address.</p>
|
||||
|
||||
<form class="form-horizontal" role="form" onsubmit="do_add_alias(); return false;">
|
||||
<p>To use an alias or any address besides your own login username in outbound mail, the sending user must be included as a permitted sender for the alias.</p>
|
||||
|
||||
<form id="addalias-form" class="form-horizontal" role="form" onsubmit="do_add_alias(); return false;">
|
||||
<div class="form-group">
|
||||
<div class="col-sm-offset-1 col-sm-11">
|
||||
<div id="alias_type_buttons" class="btn-group btn-group-xs">
|
||||
<button type="button" class="btn btn-default active" data-mode="regular">Regular</button>
|
||||
<button type="button" class="btn btn-default" data-mode="regular">Regular</button>
|
||||
<button type="button" class="btn btn-default" data-mode="catchall">Catch-All</button>
|
||||
<button type="button" class="btn btn-default" data-mode="domainalias">Domain Alias</button>
|
||||
</div>
|
||||
<div id="alias_mode_info" class="text-info small" style="display: none; margin: .5em 0 0 0;">
|
||||
<span class="catchall hidden">A catch-all alias captures all otherwise unmatched email to a domain. Enter just a part of an email address starting with the @-sign.</span>
|
||||
<span class="domainalias hidden">A domain alias forwards all otherwise unmatched mail from one domain to another domain, preserving the part before the @-sign.</span>
|
||||
<span class="catchall hidden">A catch-all alias captures all otherwise unmatched email to a domain.</span>
|
||||
<span class="domainalias hidden">A domain alias forwards all otherwise unmatched email from one domain to another domain, preserving the part before the @-sign.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="addaliasEmail" class="col-sm-1 control-label">Alias</label>
|
||||
<label for="addaliasAddress" class="col-sm-1 control-label">Alias</label>
|
||||
<div class="col-sm-10">
|
||||
<input type="email" class="form-control" id="addaliasEmail">
|
||||
<input type="email" class="form-control" id="addaliasAddress">
|
||||
<div style="margin-top: 3px; padding-left: 3px; font-size: 90%" class="text-muted">
|
||||
<span class="catchall domainalias">Enter just the part of an email address starting with the @-sign.</span>
|
||||
You may use international (non-ASCII) characters for the domain part of the email address only.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="addaliasTargets" class="col-sm-1 control-label">Forward To</label>
|
||||
<label for="addaliasForwardsTo" class="col-sm-1 control-label">Forwards To</label>
|
||||
<div class="col-sm-10">
|
||||
<textarea class="form-control" rows="3" id="addaliasTargets"></textarea>
|
||||
<textarea class="form-control" rows="3" id="addaliasForwardsTo"></textarea>
|
||||
<div style="margin-top: 3px; padding-left: 3px; font-size: 90%">
|
||||
<span class="domainalias text-muted">Enter just the part of an email address starting with the @-sign.</span>
|
||||
<span class="text-danger">Only forward mail to addresses handled by this Mail-in-a-Box, since mail forwarded by aliases to other domains may be rejected or filtered by the receiver. To forward mail to other domains, create a mail user and then log into webmail for the user and create a filter rule to forward mail.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="addaliasSenders" class="col-sm-1 control-label">Permitted Senders</label>
|
||||
<div class="col-sm-10">
|
||||
<div class="radio">
|
||||
<label>
|
||||
<input id="addaliasForwardsToNotAdvanced" name="addaliasForwardsToDivToggle" type="radio" checked onclick="$('#addaliasForwardsToDiv').toggle(false)">
|
||||
Any mail user listed in the Forwards To box can send mail claiming to be from <span class="regularalias">the alias address</span><span class="catchall domainalias">any address on the alias domain</span>.
|
||||
</label>
|
||||
</div>
|
||||
<div class="radio">
|
||||
<label>
|
||||
<input id="addaliasForwardsToAdvanced" name="addaliasForwardsToDivToggle" type="radio" id="addaliasForwardsToDivShower" onclick="$('#addaliasForwardsToDiv').toggle(true)">
|
||||
I’ll enter the mail users that can send mail claiming to be from <span class="regularalias">the alias address</span><span class="catchall domainalias">any address on the alias domain</span>.
|
||||
</label>
|
||||
</div>
|
||||
<div id="addaliasForwardsToDiv" style="margin-top: .5em; margin-left: 1.4em; display: none;">
|
||||
<textarea class="form-control" rows="3" id="addaliasSenders" placeholder="one user per line or separated by commas"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
@@ -50,13 +80,14 @@
|
||||
<th></th>
|
||||
<th>Alias<br></th>
|
||||
<th>Forwards To</th>
|
||||
<th>Permitted Senders</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p style="margin-top: 1.5em"><small>Hostmaster@, postmaster@, and admin@ email addresses are required on some domains.</small></p>
|
||||
<p style="margin-top: 1.5em"><small>hostmaster@, postmaster@, admin@ and abuse@ email addresses are required on some domains.</small></p>
|
||||
|
||||
<div style="display: none">
|
||||
<table>
|
||||
@@ -69,12 +100,48 @@
|
||||
<span class="glyphicon glyphicon-trash"></span>
|
||||
</a>
|
||||
</td>
|
||||
<td class='email'> </td>
|
||||
<td class='target'> </td>
|
||||
<td class='address'> </td>
|
||||
<td class='forwardsTo'> </td>
|
||||
<td class='senders'> </td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<h3>Mail aliases API (advanced)</h3>
|
||||
|
||||
<p>Use your box’s mail aliases API to add and remove mail aliases from the command-line or custom services you build.</p>
|
||||
|
||||
<p>Usage:</p>
|
||||
|
||||
<pre>curl -X <b>VERB</b> [-d "<b>parameters</b>"] --user {email}:{password} https://{{hostname}}/admin/mail/aliases[<b>action</b>]</pre>
|
||||
|
||||
<p>Brackets denote an optional argument. Please note that the POST body <code>parameters</code> must be URL-encoded.</p>
|
||||
|
||||
<p>The email and password given to the <code>--user</code> option must be an administrative user on this system.</p>
|
||||
|
||||
<h4 style="margin-bottom: 0">Verbs</h4>
|
||||
|
||||
<table class="table" style="margin-top: .5em">
|
||||
<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 aliases. 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 alias. Required POST-body parameters are <code>address</code> and <code>forwards_to</code>.</td></tr>
|
||||
<tr><td>POST</td><td>/remove</td> <td>Removes a mail alias. Required POST-body parameter is <code>address</code>.</td></tr>
|
||||
</table>
|
||||
|
||||
<h4>Examples:</h4>
|
||||
|
||||
<p>Try these examples. For simplicity the examples omit the <code>--user me@mydomain.com:yourpassword</code> command line argument which you must fill in with your email address and password.</p>
|
||||
|
||||
<pre># Gives a JSON-encoded list of all mail aliases
|
||||
curl -X GET https://{{hostname}}/admin/mail/aliases?format=json
|
||||
|
||||
# Adds a new alias
|
||||
curl -X POST -d "address=new_alias@mydomail.com" -d "forwards_to=my_email@mydomain.com" https://{{hostname}}/admin/mail/aliases/add
|
||||
|
||||
# Removes an alias
|
||||
curl -X POST -d "address=new_alias@mydomail.com" https://{{hostname}}/admin/mail/aliases/remove
|
||||
</pre>
|
||||
|
||||
|
||||
<script>
|
||||
function show_aliases() {
|
||||
@@ -97,10 +164,12 @@ function show_aliases() {
|
||||
n.attr('id', '');
|
||||
|
||||
if (alias.required) n.addClass('alias-required');
|
||||
n.attr('data-email', alias.source);
|
||||
n.find('td.email').text(alias.source)
|
||||
for (var j = 0; j < alias.destination.length; j++)
|
||||
n.find('td.target').append($("<div></div>").text(alias.destination[j]))
|
||||
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)
|
||||
for (var j = 0; j < alias.forwards_to.length; j++)
|
||||
n.find('td.forwardsTo').append($("<div></div>").text(alias.forwards_to[j]))
|
||||
for (var j = 0; j < (alias.permitted_senders ? alias.permitted_senders.length : 0); j++)
|
||||
n.find('td.senders').append($("<div></div>").text(alias.permitted_senders[j]))
|
||||
$('#alias_table tbody').append(n);
|
||||
}
|
||||
}
|
||||
@@ -110,25 +179,25 @@ function show_aliases() {
|
||||
$('#alias_type_buttons button').off('click').click(function() {
|
||||
$('#alias_type_buttons button').removeClass('active');
|
||||
$(this).addClass('active');
|
||||
$('#addalias-form .regularalias, #addalias-form .catchall, #addalias-form .domainalias').addClass('hidden');
|
||||
if ($(this).attr('data-mode') == "regular") {
|
||||
$('#addaliasEmail').attr('type', 'email');
|
||||
$('#addaliasEmail').attr('placeholder', 'incoming email address (e.g. you@yourdomain.com)');
|
||||
$('#addaliasTargets').attr('placeholder', 'forward to these email addresses (one per line or separated by commas)');
|
||||
$('#addaliasAddress').attr('type', 'email');
|
||||
$('#addaliasAddress').attr('placeholder', 'you@yourdomain.com (incoming email address)');
|
||||
$('#addaliasForwardsTo').attr('placeholder', 'one address per line or separated by commas');
|
||||
$('#alias_mode_info').slideUp();
|
||||
$('#addalias-form .regularalias').removeClass('hidden');
|
||||
} else if ($(this).attr('data-mode') == "catchall") {
|
||||
$('#addaliasEmail').attr('type', 'text');
|
||||
$('#addaliasEmail').attr('placeholder', 'incoming catch-all address (e.g. @yourdomain.com)');
|
||||
$('#addaliasTargets').attr('placeholder', 'forward to these email addresses (one per line or separated by commas)');
|
||||
$('#addaliasAddress').attr('type', 'text');
|
||||
$('#addaliasAddress').attr('placeholder', '@yourdomain.com (incoming catch-all domain)');
|
||||
$('#addaliasForwardsTo').attr('placeholder', 'one address per line or separated by commas');
|
||||
$('#alias_mode_info').slideDown();
|
||||
$('#alias_mode_info span').addClass('hidden');
|
||||
$('#alias_mode_info span.catchall').removeClass('hidden');
|
||||
$('#addalias-form .catchall').removeClass('hidden');
|
||||
} else if ($(this).attr('data-mode') == "domainalias") {
|
||||
$('#addaliasEmail').attr('type', 'text');
|
||||
$('#addaliasEmail').attr('placeholder', 'incoming domain (@yourdomain.com)');
|
||||
$('#addaliasTargets').attr('placeholder', 'forward to domain (@yourdomain.com)');
|
||||
$('#addaliasAddress').attr('type', 'text');
|
||||
$('#addaliasAddress').attr('placeholder', '@yourdomain.com (incoming catch-all domain)');
|
||||
$('#addaliasForwardsTo').attr('placeholder', '@otherdomain.com (forward to other domain)');
|
||||
$('#alias_mode_info').slideDown();
|
||||
$('#alias_mode_info span').addClass('hidden');
|
||||
$('#alias_mode_info span.domainalias').removeClass('hidden');
|
||||
$('#addalias-form .domainalias').removeClass('hidden');
|
||||
}
|
||||
})
|
||||
$('#alias_type_buttons button[data-mode="regular"]').click(); // init
|
||||
@@ -138,15 +207,21 @@ function show_aliases() {
|
||||
var is_alias_add_update = false;
|
||||
function do_add_alias() {
|
||||
var title = (!is_alias_add_update) ? "Add Alias" : "Update Alias";
|
||||
var email = $("#addaliasEmail").val();
|
||||
var targets = $("#addaliasTargets").val();
|
||||
var form_address = $("#addaliasAddress").val();
|
||||
var form_forwardsto = $("#addaliasForwardsTo").val();
|
||||
var form_senders = ($('#addaliasForwardsToAdvanced').prop('checked') ? $("#addaliasSenders").val() : '');
|
||||
if ($('#addaliasForwardsToAdvanced').prop('checked') && !/\S/.exec($("#addaliasSenders").val())) {
|
||||
show_modal_error(title, "You did not enter any permitted senders.");
|
||||
return false;
|
||||
}
|
||||
api(
|
||||
"/mail/aliases/add",
|
||||
"POST",
|
||||
{
|
||||
update_if_exists: is_alias_add_update ? '1' : '0',
|
||||
source: email,
|
||||
destination: targets
|
||||
address: form_address,
|
||||
forwards_to: form_forwardsto,
|
||||
permitted_senders: form_senders
|
||||
},
|
||||
function(r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
@@ -161,48 +236,55 @@ function do_add_alias() {
|
||||
}
|
||||
|
||||
function aliases_reset_form() {
|
||||
$("#addaliasEmail").prop('disabled', false);
|
||||
$("#addaliasEmail").val('')
|
||||
$("#addaliasTargets").val('')
|
||||
$("#addaliasAddress").prop('disabled', false);
|
||||
$("#addaliasAddress").val('')
|
||||
$("#addaliasForwardsTo").val('')
|
||||
$("#addaliasSenders").val('')
|
||||
$('#alias-cancel').addClass('hidden');
|
||||
$('#add-alias-button').text('Add Alias');
|
||||
is_alias_add_update = false;
|
||||
}
|
||||
|
||||
function aliases_edit(elem) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
var targetdivs = $(elem).parents('tr').find('.target div');
|
||||
var targets = "";
|
||||
for (var i = 0; i < targetdivs.length; i++)
|
||||
targets += $(targetdivs[i]).text() + "\n";
|
||||
|
||||
is_alias_add_update = true;
|
||||
$('#alias-cancel').removeClass('hidden');
|
||||
$("#addaliasEmail").prop('disabled', true);
|
||||
$("#addaliasEmail").val(email);
|
||||
$("#addaliasTargets").val(targets);
|
||||
$('#add-alias-button').text('Update');
|
||||
if (email.charAt(0) == '@' && targets.charAt(0) == '@')
|
||||
var address = $(elem).parents('tr').attr('data-address');
|
||||
var receiverdivs = $(elem).parents('tr').find('.forwardsTo div');
|
||||
var senderdivs = $(elem).parents('tr').find('.senders div');
|
||||
var forwardsTo = "";
|
||||
for (var i = 0; i < receiverdivs.length; i++)
|
||||
forwardsTo += $(receiverdivs[i]).text() + "\n";
|
||||
var senders = "";
|
||||
for (var i = 0; i < senderdivs.length; i++)
|
||||
senders += $(senderdivs[i]).text() + "\n";
|
||||
if (address.charAt(0) == '@' && forwardsTo.charAt(0) == '@')
|
||||
$('#alias_type_buttons button[data-mode="domainalias"]').click();
|
||||
else if (email.charAt(0) == '@')
|
||||
else if (address.charAt(0) == '@')
|
||||
$('#alias_type_buttons button[data-mode="catchall"]').click();
|
||||
else
|
||||
$('#alias_type_buttons button[data-mode="regular"]').click();
|
||||
$('#alias-cancel').removeClass('hidden');
|
||||
$("#addaliasAddress").prop('disabled', true);
|
||||
$("#addaliasAddress").val(address);
|
||||
$("#addaliasForwardsTo").val(forwardsTo);
|
||||
$('#addaliasForwardsToAdvanced').prop('checked', senders != "");
|
||||
$('#addaliasForwardsToNotAdvanced').prop('checked', senders == "");
|
||||
$("#addaliasSenders").val(senders);
|
||||
$('#add-alias-button').text('Update');
|
||||
$('body').animate({ scrollTop: 0 })
|
||||
is_alias_add_update = true;
|
||||
}
|
||||
|
||||
function aliases_remove(elem) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
var row_address = $(elem).parents('tr').attr('data-address');
|
||||
show_modal_confirm(
|
||||
"Remove Alias",
|
||||
"Remove " + email + "?",
|
||||
"Remove " + row_address + "?",
|
||||
"Remove",
|
||||
function() {
|
||||
api(
|
||||
"/mail/aliases/remove",
|
||||
"POST",
|
||||
{
|
||||
source: email
|
||||
address: row_address
|
||||
},
|
||||
function(r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
<p>It is possible to set custom DNS records on domains hosted here.</p>
|
||||
|
||||
<h3>Set Custom DNS Records</h3>
|
||||
<h3>Set custom DNS records</h3>
|
||||
|
||||
<p>You can set additional DNS records, such as if you have a website running on another server, to add DKIM records for external mail providers, or for various confirmation-of-ownership tests.</p>
|
||||
|
||||
@@ -31,10 +31,15 @@
|
||||
<label for="customdnsType" class="col-sm-1 control-label">Type</label>
|
||||
<div class="col-sm-10">
|
||||
<select id="customdnsType" class="form-control" style="max-width: 400px" onchange="show_customdns_rtype_hint()">
|
||||
<option value="A" data-hint="Enter an IPv4 address (i.e. a dotted quad, such as 123.456.789.012).">A (IPv4 address)</option>
|
||||
<option value="AAAA" data-hint="Enter an IPv6 address.">AAAA (IPv6 address)</option>
|
||||
<option value="A" data-hint="Enter an IPv4 address (i.e. a dotted quad, such as 123.456.789.012). The 'local' alias sets the record to this box's public IPv4 address.">A (IPv4 address)</option>
|
||||
<option value="AAAA" data-hint="Enter an IPv6 address. The 'local' alias sets the record to this box's public IPv6 address.">AAAA (IPv6 address)</option>
|
||||
<option value="CAA" data-hint="Enter a CA that can issue certificates for this domain in the form of FLAG TAG VALUE. (0 issuewild "letsencrypt.org")">CAA (Certificate Authority Authorization)</option>
|
||||
<option value="CNAME" data-hint="Enter another domain name followed by a period at the end (e.g. mypage.github.io.).">CNAME (DNS forwarding)</option>
|
||||
<option value="TXT" data-hint="Enter arbitrary text.">TXT (text record)</option>
|
||||
<option value="MX" data-hint="Enter record in the form of PRIORITY DOMAIN., including trailing period (e.g. 20 mx.example.com.).">MX (mail exchanger)</option>
|
||||
<option value="SRV" data-hint="Enter record in the form of PRIORITY WEIGHT PORT TARGET., including trailing period (e.g. 10 10 5060 sip.example.com.).">SRV (service record)</option>
|
||||
<option value="SSHFP" data-hint="Enter record in the form of ALGORITHM TYPE FINGERPRINT.">SSHFP (SSH fingerprint record)</option>
|
||||
<option value="NS" data-hint="Enter a hostname to which this subdomain should be delegated to">NS (DNS subdomain delegation)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
@@ -64,9 +69,10 @@
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<h3>Using a Secondary Nameserver</h3>
|
||||
<h3>Using a secondary nameserver</h3>
|
||||
|
||||
<p>If your TLD requires you to have two separate nameservers, you can either set up a secondary (aka “slave”) nameserver or, alternatively, set up <a href="#" onclick="return show_panel('external_dns')">external DNS</a> and ignore the DNS server on this box. If you choose to use a seconday/slave nameserver, you must find a seconday/slave nameserver service provider. Your domain name registrar or virtual cloud provider may provide this service for you. Once you set up the seconday/slave nameserver service, enter the hostname of <em>their</em> secondary nameserver:</p>
|
||||
<p>If your TLD requires you to have two separate nameservers, you can either set up <a href="#" onclick="return show_panel('external_dns')">external DNS</a> and ignore the DNS server on this box entirely, or use the DNS server on this box but add a secondary (aka “slave”) nameserver.</p>
|
||||
<p>If you choose to use a secondary nameserver, you must find a secondary nameserver service provider. Your domain name registrar or virtual cloud provider may provide this service for you. Once you set up the secondary nameserver service, enter the hostname (not the IP address) of <em>their</em> secondary nameserver in the box below.</p>
|
||||
|
||||
<form class="form-horizontal" role="form" onsubmit="do_set_secondary_dns(); return false;">
|
||||
<div class="form-group">
|
||||
@@ -80,9 +86,15 @@
|
||||
<button type="submit" class="btn btn-primary">Update</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="secondarydns-clear-instructions" class="form-group" style="display: none">
|
||||
<div class="form-group">
|
||||
<div class="col-sm-offset-1 col-sm-11">
|
||||
<p class="small">Clear the input field above and click Update to use this machine itself as secondary DNS, which is the default/normal setup.</p>
|
||||
<p class="small">
|
||||
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>.
|
||||
</p>
|
||||
<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.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -92,44 +104,56 @@
|
||||
|
||||
<p>Use your box’s DNS API to set custom DNS records on domains hosted here. For instance, you can create your own dynamic DNS service.</p>
|
||||
|
||||
<p>Send a POST request like this:</p>
|
||||
<p>Usage:</p>
|
||||
|
||||
<pre>curl -d "" --user {email}:{password} https://{{hostname}}/admin/dns/set/<b>qname</b>[/<b>rtype</b>[/<b>value</b>]]</pre>
|
||||
<pre>curl -X <b>VERB</b> [-d "<b>value</b>"] --user {email}:{password} https://{{hostname}}/admin/dns/custom[/<b>qname</b>[/<b>rtype</b>]]</pre>
|
||||
|
||||
<h4>HTTP POST parameters</h4>
|
||||
<p>(Brackets denote an optional argument.)</p>
|
||||
|
||||
<h4>Verbs</h4>
|
||||
|
||||
<table class="table">
|
||||
<thead><th>Verb</th> <th>Usage</th></thead>
|
||||
<tr><td>GET</td> <td>Returns matching custom DNS records as a JSON array of objects. Each object has the keys <code>qname</code>, <code>rtype</code>, and <code>value</code>. The optional <code>qname</code> and <code>rtype</code> parameters in the request URL filter the records returned in the response. The request body (<code>-d "..."</code>) must be omitted.</td></tr>
|
||||
<tr><td>PUT</td> <td>Sets a custom DNS record replacing any existing records with the same <code>qname</code> and <code>rtype</code>. Use PUT (instead of POST) when you only have one value for a <code>qname</code> and <code>rtype</code>, such as typical <code>A</code> records (without round-robin).</td></tr>
|
||||
<tr><td>POST</td> <td>Adds a new custom DNS record. Use POST when you have multiple <code>TXT</code> records or round-robin <code>A</code> records. (PUT would delete previously added records.)</td></tr>
|
||||
<tr><td>DELETE</td> <td>Deletes custom DNS records. If the request body (<code>-d "..."</code>) is empty or omitted, deletes all records matching the <code>qname</code> and <code>rtype</code>. If the request body is present, deletes only the record matching the <code>qname</code>, <code>rtype</code> and value.</td></tr>
|
||||
</table>
|
||||
|
||||
<h4>Parameters</h4>
|
||||
|
||||
<table class="table">
|
||||
<thead><th>Parameter</th> <th>Value</th></thead>
|
||||
<tr><td>email</td> <td>The email address of any administrative user here.</td></tr>
|
||||
<tr><td>password</td> <td>That user’s password.</td></tr>
|
||||
<tr><td>qname</td> <td>The fully qualified domain name for the record you are trying to set.</td></tr>
|
||||
<tr><td>rtype</td> <td>The resource type. <code>A</code> if omitted. Possible values: <code>A</code> (an IPv4 address), <code>AAAA</code> (an IPv6 address), <code>TXT</code> (a text string), or <code>CNAME</code> (an alias, which is a fully qualified domain name).</td></tr>
|
||||
<tr><td>value</td> <td>The new record’s value. If omitted, the IPv4 address of the remote host is used. This is handy for dynamic DNS! To delete a record, use “__delete__”.</td></tr>
|
||||
<tr><td>qname</td> <td>The fully qualified domain name for the record you are trying to set. It must be one of the domain names or a subdomain of one of the domain names hosted on this box. (Add mail users or aliases to add new domains.)</td></tr>
|
||||
<tr><td>rtype</td> <td>The resource type. Defaults to <code>A</code> if omitted. Possible values: <code>A</code> (an IPv4 address), <code>AAAA</code> (an IPv6 address), <code>TXT</code> (a text string), <code>CNAME</code> (an alias, which is a fully qualified domain name — don’t forget the final period), <code>MX</code>, <code>SRV</code>, <code>SSHFP</code>, <code>CAA</code> or <code>NS</code>.</td></tr>
|
||||
<tr><td>value</td> <td>For PUT, POST, and DELETE, the record’s value. If the <code>rtype</code> is <code>A</code> or <code>AAAA</code> and <code>value</code> is empty or omitted, the IPv4 or IPv6 address of the remote host is used (be sure to use the <code>-4</code> or <code>-6</code> options to curl). This is handy for dynamic DNS!</td></tr>
|
||||
</table>
|
||||
|
||||
<p style="margin-top: 1em">Note that <code>-d ""</code> is merely to ensure curl sends a POST request. You do not need to put anything inside the quotes. You can also pass the value using typical form encoding in the POST body.</p>
|
||||
|
||||
<p>Strict <a href="http://tools.ietf.org/html/rfc4408">SPF</a> and <a href="https://datatracker.ietf.org/doc/draft-kucherawy-dmarc-base/?include_text=1">DMARC</a> records will be added to all custom domains unless you override them.</p>
|
||||
|
||||
<h4>Examples:</h4>
|
||||
|
||||
<p>Try these examples. For simplicity the examples omit the <code>--user me@mydomain.com:yourpassword</code> command line argument which you must fill in with your email address and password.</p>
|
||||
|
||||
<pre># sets laptop.mydomain.com to point to the IP address of the machine you are executing curl on
|
||||
curl -d "" --user me@mydomain.com:###### https://{{hostname}}/admin/dns/set/laptop.mydomain.com
|
||||
curl -X PUT https://{{hostname}}/admin/dns/custom/laptop.mydomain.com
|
||||
|
||||
# sets an alias
|
||||
curl -d "" --user me@mydomain.com:###### https://{{hostname}}/admin/dns/set/foo.mydomain.com/cname/bar.mydomain.com
|
||||
# deletes that record and all A records for that domain name
|
||||
curl -X DELETE https://{{hostname}}/admin/dns/custom/laptop.mydomain.com
|
||||
|
||||
# clears the alias
|
||||
curl -d "" --user me@mydomain.com:###### https://{{hostname}}/admin/dns/set/bar.mydomain.com/cname/__delete__
|
||||
# sets a CNAME alias
|
||||
curl -X PUT -d "bar.mydomain.com." https://{{hostname}}/admin/dns/custom/foo.mydomain.com/cname
|
||||
|
||||
# sets a TXT record using the alternate value syntax
|
||||
curl -d "value=something%20here" --user me@mydomain.com:###### https://{{hostname}}/admin/dns/set/foo.mydomain.com/txt
|
||||
# deletes that CNAME and all CNAME records for that domain name
|
||||
curl -X DELETE https://{{hostname}}/admin/dns/custom/foo.mydomain.com/cname
|
||||
|
||||
# sets a <a href="http://en.wikipedia.org/wiki/SRV_record">SRV record</a> for the "service" and "protocol" hosted on "target" server
|
||||
curl -d "" --user me@mydomain.com:###### https://{{hostname}}/admin/dns/set/_service._protocol.{{hostname}}/srv/"priority weight port target"
|
||||
# adds a TXT record using POST to preserve any previous TXT records
|
||||
curl -X POST -d "some text here" https://{{hostname}}/admin/dns/custom/foo.mydomain.com/txt
|
||||
|
||||
# sets a SRV record using the value syntax
|
||||
curl -d "value=priority weight port target" --user me@mydomain.com:###### https://{{hostname}}/admin/dns/set/_service._protocol.host/srv
|
||||
# deletes that one TXT record while preserving other TXT records
|
||||
curl -X DELETE -d "some text here" https://{{hostname}}/admin/dns/custom/foo.mydomain.com/txt
|
||||
</pre>
|
||||
|
||||
<script>
|
||||
@@ -139,8 +163,8 @@ function show_custom_dns() {
|
||||
"GET",
|
||||
{ },
|
||||
function(data) {
|
||||
$('#secondarydnsHostname').val(data.hostname ? data.hostname : '');
|
||||
$('#secondarydns-clear-instructions').toggle(data.hostname != null);
|
||||
$('#secondarydnsHostname').val(data.hostnames.join(' '));
|
||||
$('#secondarydns-clear-instructions').toggle(data.hostnames.length > 0);
|
||||
});
|
||||
|
||||
api(
|
||||
@@ -160,7 +184,7 @@ function show_custom_dns() {
|
||||
|
||||
function show_current_custom_dns() {
|
||||
api(
|
||||
"/dns/set",
|
||||
"/dns/custom",
|
||||
"GET",
|
||||
{ },
|
||||
function(data) {
|
||||
@@ -175,6 +199,7 @@ function show_current_custom_dns() {
|
||||
$('#custom-dns-current').find("tbody").append(tr);
|
||||
tr.attr('data-qname', data[i].qname);
|
||||
tr.attr('data-rtype', data[i].rtype);
|
||||
tr.attr('data-value', data[i].value);
|
||||
tr.append($('<td class="long"/>').text(data[i].qname));
|
||||
tr.append($('<td/>').text(data[i].rtype));
|
||||
tr.append($('<td class="long"/>').text(data[i].value));
|
||||
@@ -186,7 +211,8 @@ function show_current_custom_dns() {
|
||||
function delete_custom_dns_record(elem) {
|
||||
var qname = $(elem).parents('tr').attr('data-qname');
|
||||
var rtype = $(elem).parents('tr').attr('data-rtype');
|
||||
do_set_custom_dns(qname, rtype, "__delete__");
|
||||
var value = $(elem).parents('tr').attr('data-value');
|
||||
do_set_custom_dns(qname, rtype, value, "DELETE");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -195,7 +221,7 @@ function do_set_secondary_dns() {
|
||||
"/dns/secondary-nameserver",
|
||||
"POST",
|
||||
{
|
||||
hostname: $('#secondarydnsHostname').val()
|
||||
hostnames: $('#secondarydnsHostname').val()
|
||||
},
|
||||
function(data) {
|
||||
if (data == "") return; // nothing updated
|
||||
@@ -207,7 +233,7 @@ function do_set_secondary_dns() {
|
||||
});
|
||||
}
|
||||
|
||||
function do_set_custom_dns(qname, rtype, value) {
|
||||
function do_set_custom_dns(qname, rtype, value, method) {
|
||||
if (!qname) {
|
||||
if ($('#customdnsQname').val() != '')
|
||||
qname = $('#customdnsQname').val() + '.' + $('#customdnsZone').val();
|
||||
@@ -215,21 +241,20 @@ function do_set_custom_dns(qname, rtype, value) {
|
||||
qname = $('#customdnsZone').val();
|
||||
rtype = $('#customdnsType').val();
|
||||
value = $('#customdnsValue').val();
|
||||
method = 'POST';
|
||||
}
|
||||
|
||||
api(
|
||||
"/dns/set/" + qname + "/" + rtype,
|
||||
"POST",
|
||||
{
|
||||
value: value
|
||||
},
|
||||
"/dns/custom/" + qname + "/" + rtype,
|
||||
method,
|
||||
value,
|
||||
function(data) {
|
||||
if (data == "") return; // nothing updated
|
||||
show_modal_error("Custom DNS", $("<pre/>").text(data));
|
||||
show_current_custom_dns();
|
||||
},
|
||||
function(err) {
|
||||
show_modal_error("Custom DNS", $("<pre/>").text(err));
|
||||
show_modal_error("Custom DNS (Error)", $("<pre/>").text(err));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -34,6 +34,15 @@
|
||||
|
||||
<p>If you do so, you are responsible for keeping your DNS entries up to date! If you previously enabled DNSSEC on your domain name by setting a DS record at your registrar, you will likely have to turn it off before changing nameservers.</p>
|
||||
|
||||
|
||||
<p class="alert" role="alert">
|
||||
<span class="glyphicon glyphicon-info-sign"></span>
|
||||
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.
|
||||
You may need to adopt this technique when adding DomainKeys. Use a tool like <code>named-checkzone</code> to validate your zone file.
|
||||
</p>
|
||||
|
||||
|
||||
<table id="external_dns_settings" class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
|
||||
@@ -1,28 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
|
||||
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
|
||||
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
|
||||
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
|
||||
<meta name="viewport" content="width=device-width">
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
|
||||
<title>{{hostname}} - Mail-in-a-Box Control Panel</title>
|
||||
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
|
||||
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="/admin/assets/bootstrap/css/bootstrap.min.css">
|
||||
<style>
|
||||
@import url(https://fonts.googleapis.com/css?family=Raleway:400,700);
|
||||
@import url(https://fonts.googleapis.com/css?family=Ubuntu:300);
|
||||
|
||||
html {
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
body {
|
||||
padding-top: 50px;
|
||||
overflow-y: scroll;
|
||||
padding-bottom: 20px;
|
||||
}
|
||||
|
||||
@@ -31,7 +21,7 @@
|
||||
}
|
||||
|
||||
h1, h2, h3, h4 {
|
||||
font-family: Raleway, sans-serif;
|
||||
font-family: sans-serif;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@@ -73,18 +63,18 @@
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
|
||||
<style>
|
||||
</style>
|
||||
<link rel="stylesheet" href="/admin/assets/bootstrap/css/bootstrap-theme.min.css">
|
||||
</head>
|
||||
<body>
|
||||
<!--[if lt IE 7]>
|
||||
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
|
||||
<![endif]-->
|
||||
<div class="navbar navbar-inverse navbar-fixed-top">
|
||||
|
||||
<!--[if lt IE 8]><p>Internet Explorer version 8 or any modern web browser is required to use this website, sorry.<![endif]-->
|
||||
<!--[if gt IE 7]><!-->
|
||||
|
||||
<div class="navbar navbar-inverse navbar-static-top" role="navigation">
|
||||
<div class="container">
|
||||
<div class="navbar-header">
|
||||
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
|
||||
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
|
||||
<span class="sr-only">Toggle navigation</span>
|
||||
<span class="icon-bar"></span>
|
||||
<span class="icon-bar"></span>
|
||||
<span class="icon-bar"></span>
|
||||
@@ -97,12 +87,13 @@
|
||||
<a href="#" class="dropdown-toggle" data-toggle="dropdown">System <b class="caret"></b></a>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="#system_status" onclick="return show_panel(this);">Status Checks</a></li>
|
||||
<li><a href="#ssl" onclick="return show_panel(this);">SSL Certificates</a></li>
|
||||
<li><a href="#tls" onclick="return show_panel(this);">TLS (SSL) Certificates</a></li>
|
||||
<li><a href="#system_backup" onclick="return show_panel(this);">Backup Status</a></li>
|
||||
<li class="divider"></li>
|
||||
<li class="dropdown-header">Advanced Options</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="#external_dns" onclick="return show_panel(this);">External DNS</a></li>
|
||||
<li><a href="/admin/munin" target="_blank">Munin Monitoring</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="dropdown">
|
||||
@@ -117,7 +108,7 @@
|
||||
<li><a href="#web" onclick="return show_panel(this);">Web</a></li>
|
||||
</ul>
|
||||
<ul class="nav navbar-nav navbar-right">
|
||||
<li><a href="#" onclick="do_logout(); return false;" style="color: white">Log out?</a></li>
|
||||
<li><a href="#" onclick="do_logout(); return false;" style="color: white">Log out</a></li>
|
||||
</ul>
|
||||
</div><!--/.navbar-collapse -->
|
||||
</div>
|
||||
@@ -164,7 +155,7 @@
|
||||
{% include "web.html" %}
|
||||
</div>
|
||||
|
||||
<div id="panel_ssl" class="admin_panel">
|
||||
<div id="panel_tls" class="admin_panel">
|
||||
{% include "ssl.html" %}
|
||||
</div>
|
||||
|
||||
@@ -175,9 +166,9 @@
|
||||
</footer>
|
||||
</div> <!-- /container -->
|
||||
|
||||
<div id="ajax_loading_indicator" style="display: none; position: fixed; left: 0; top: 0; width: 100%; height: 100%; text-align: center; background-color: rgba(255,255,255,.75)">
|
||||
<div id="ajax_loading_indicator" style="display: none; position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: 100000; text-align: center; background-color: rgba(255,255,255,.75)">
|
||||
<div style="margin: 20% auto">
|
||||
<div><span class="glyphicon glyphicon-time"></span></div>
|
||||
<div><span class="fa fa-spinner fa-pulse"></span></div>
|
||||
<div>Loading...</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -200,8 +191,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
|
||||
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
|
||||
<script src="/admin/assets/jquery.min.js"></script>
|
||||
<script src="/admin/assets/bootstrap/js/bootstrap.min.js"></script>
|
||||
|
||||
<script>
|
||||
var global_modal_state = null;
|
||||
@@ -233,7 +224,7 @@ $(function() {
|
||||
function show_modal_error(title, message, callback) {
|
||||
$('#global_modal h4').text(title);
|
||||
$('#global_modal .modal-body').html("<p/>");
|
||||
if (typeof question == String) {
|
||||
if (typeof question == 'string') {
|
||||
$('#global_modal p').text(message);
|
||||
$('#global_modal .modal-dialog').addClass("modal-sm");
|
||||
} else {
|
||||
@@ -245,11 +236,12 @@ function show_modal_error(title, message, callback) {
|
||||
global_modal_funcs = [callback, callback];
|
||||
global_modal_state = null;
|
||||
$('#global_modal').modal({});
|
||||
return false; // handy when called from onclick
|
||||
}
|
||||
|
||||
function show_modal_confirm(title, question, verb, yes_callback, cancel_callback) {
|
||||
$('#global_modal h4').text(title);
|
||||
if (typeof question == String) {
|
||||
if (typeof question == 'string') {
|
||||
$('#global_modal .modal-dialog').addClass("modal-sm");
|
||||
$('#global_modal .modal-body').html("<p/>");
|
||||
$('#global_modal p').text(question);
|
||||
@@ -257,20 +249,26 @@ function show_modal_confirm(title, question, verb, yes_callback, cancel_callback
|
||||
$('#global_modal .modal-dialog').removeClass("modal-sm");
|
||||
$('#global_modal .modal-body').html("").append(question);
|
||||
}
|
||||
if (typeof verb == 'string') {
|
||||
$('#global_modal .btn-default').show().text("Cancel");
|
||||
$('#global_modal .btn-danger').show().text(verb);
|
||||
} else {
|
||||
$('#global_modal .btn-default').show().text(verb[1]);
|
||||
$('#global_modal .btn-danger').show().text(verb[0]);
|
||||
}
|
||||
global_modal_funcs = [yes_callback, cancel_callback];
|
||||
global_modal_state = null;
|
||||
$('#global_modal').modal({});
|
||||
return false; // handy when called from onclick
|
||||
}
|
||||
|
||||
var ajax_num_executing_requests = 0;
|
||||
function ajax(options) {
|
||||
function ajax_with_indicator(options) {
|
||||
setTimeout("if (ajax_num_executing_requests > 0) $('#ajax_loading_indicator').fadeIn()", 100);
|
||||
function hide_loading_indicator() {
|
||||
ajax_num_executing_requests--;
|
||||
if (ajax_num_executing_requests == 0)
|
||||
$('#ajax_loading_indicator').stop().hide(); // stop() prevents an ongoing fade from causing the thing to be shown again after this call
|
||||
$('#ajax_loading_indicator').stop(true).hide(); // stop() prevents an ongoing fade from causing the thing to be shown again after this call
|
||||
}
|
||||
var old_success = options.success;
|
||||
var old_error = options.error;
|
||||
@@ -290,6 +288,7 @@ function ajax(options) {
|
||||
};
|
||||
ajax_num_executing_requests++;
|
||||
$.ajax(options);
|
||||
return false; // handy when called from onclick
|
||||
}
|
||||
|
||||
var api_credentials = ["", ""];
|
||||
@@ -326,10 +325,16 @@ function api(url, method, data, callback, callback_error) {
|
||||
show_modal_error("Error", "Something went wrong, sorry.")
|
||||
}
|
||||
|
||||
ajax({
|
||||
ajax_with_indicator({
|
||||
url: "/admin" + url,
|
||||
method: method,
|
||||
cache: false,
|
||||
data: data,
|
||||
|
||||
// the custom DNS api sends raw POST/PUT bodies --- prevent URL-encoding
|
||||
processData: typeof data != "string",
|
||||
mimeType: typeof data == "string" ? "text/plain; charset=ascii" : null,
|
||||
|
||||
beforeSend: function(xhr) {
|
||||
// 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
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
<h1 style="margin: 1em; text-align: center">{{hostname}}</h1>
|
||||
|
||||
{% if no_admins_exist %}
|
||||
{% if no_users_exist or no_admins_exist %}
|
||||
<div class="row">
|
||||
<div class="col-md-offset-2 col-md-8">
|
||||
{% if no_users_exist %}
|
||||
<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>
|
||||
<pre>cd mailinabox
|
||||
sudo tools/mail.py user add me@{{hostname}}
|
||||
sudo tools/mail.py user make-admin me@{{hostname}}</pre>
|
||||
{% else %}
|
||||
<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>
|
||||
<pre>cd mailinabox
|
||||
sudo tools/mail.py user make-admin your@emailaddress.com</pre>
|
||||
sudo tools/mail.py user make-admin me@{{hostname}}</pre>
|
||||
{% endif %}
|
||||
<hr>
|
||||
</div>
|
||||
</div>
|
||||
@@ -15,7 +23,7 @@ sudo tools/mail.py user make-admin your@emailaddress.com</pre>
|
||||
<p style="margin: 2em; text-align: center;">Log in here for your Mail-in-a-Box control panel.</p>
|
||||
|
||||
<div style="margin: 0 auto; max-width: 32em;">
|
||||
<form class="form-horizontal" role="form" onsubmit="do_login(); return false;">
|
||||
<form class="form-horizontal" role="form" onsubmit="do_login(); return false;" method="get">
|
||||
<div class="form-group">
|
||||
<label for="inputEmail3" class="col-sm-3 control-label">Email</label>
|
||||
<div class="col-sm-9">
|
||||
@@ -49,11 +57,15 @@ sudo tools/mail.py user make-admin your@emailaddress.com</pre>
|
||||
<script>
|
||||
function do_login() {
|
||||
if ($('#loginEmail').val() == "") {
|
||||
show_modal_error("Login Failed", "Enter your email address.")
|
||||
show_modal_error("Login Failed", "Enter your email address.", function() {
|
||||
$('#loginEmail').focus();
|
||||
});
|
||||
return false;
|
||||
}
|
||||
if ($('#loginPassword').val() == "") {
|
||||
show_modal_error("Login Failed", "Enter your email password.")
|
||||
show_modal_error("Login Failed", "Enter your email password.", function() {
|
||||
$('#loginPassword').focus();
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -67,18 +79,25 @@ function do_login() {
|
||||
function(response){
|
||||
// This API call always succeeds. It returns a JSON object indicating
|
||||
// whether the request was authenticated or not.
|
||||
if (response.status != "authorized") {
|
||||
if (response.status != "ok") {
|
||||
// Show why the login failed.
|
||||
show_modal_error("Login Failed", response.reason)
|
||||
|
||||
// Reset any saved credentials.
|
||||
do_logout();
|
||||
|
||||
} else if (!("api_key" in response)) {
|
||||
// Login succeeded but user might not be authorized!
|
||||
show_modal_error("Login Failed", "You are not an administrator on this system.")
|
||||
|
||||
// Reset any saved credentials.
|
||||
do_logout();
|
||||
|
||||
} else {
|
||||
// Login succeeded.
|
||||
|
||||
// Save the new credentials.
|
||||
api_credentials = [response.api_key, ""];
|
||||
api_credentials = [response.email, response.api_key];
|
||||
|
||||
// Try to wipe the username/password information.
|
||||
$('#loginEmail').val('');
|
||||
@@ -98,7 +117,7 @@ function do_login() {
|
||||
// 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,
|
||||
// which confuses the loading indicator.
|
||||
setTimeout(function() { show_panel(!switch_back_to_panel ? 'system_status' : switch_back_to_panel) }, 300);
|
||||
setTimeout(function() { show_panel(!switch_back_to_panel || switch_back_to_panel == "login" ? 'system_status' : switch_back_to_panel) }, 300);
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -111,4 +130,14 @@ function do_logout() {
|
||||
sessionStorage.removeItem("miab-cp-credentials");
|
||||
show_panel('login');
|
||||
}
|
||||
|
||||
function show_login() {
|
||||
$('#loginEmail,#loginPassword').each(function() {
|
||||
var input = $(this);
|
||||
if (!$.trim(input.val())) {
|
||||
input.focus();
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
<tr><th>Protocol/Method</th> <td>IMAP</td></tr>
|
||||
<tr><th>Mail server</th> <td>{{hostname}}</td>
|
||||
<tr><th>IMAP Port</th> <td>993</td></tr>
|
||||
<tr><th>IMAP Sercurity</th> <td>SSL</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 Security</td> <td>STARTTLS <small>(“always” or “required”, if prompted)</small></td></tr>
|
||||
<tr><th>Username:</th> <td>Your whole email address.</td></tr>
|
||||
@@ -38,9 +38,11 @@
|
||||
|
||||
<p>In addition to setting up your email, you’ll also need to set up <a href="#sync_guide" onclick="return show_panel(this);">contacts and calendar synchronization</a> separately.</p>
|
||||
|
||||
<p>As an alternative to IMAP you can also use the POP protocol: choose POP as the protocol, port 995, and SSL or TLS security in your mail client. The SMTP settings and usernames and passwords remain the same. However, we recommend you use IMAP instead.</p>
|
||||
|
||||
<h4>Exchange/ActiveSync settings</h4>
|
||||
|
||||
<p>On iOS devices and devices on this <a href="http://z-push.org/compatibility/">compatibility list</a>, you may set up your mail as an Exchange or ActiveSync server. However, we’ve found this to be more buggy than using IMAP. If you encounter any problems, please use the manual settings above.</p>
|
||||
<p>On iOS devices, devices on this <a href="https://wiki.z-hub.io/display/ZP/Compatibility">compatibility list</a>, or using Outlook 2007 or later on Windows 7 and later, you may set up your mail as an Exchange or ActiveSync server. However, we’ve found this to be more buggy than using IMAP as described above. If you encounter any problems, please use the manual settings above.</p>
|
||||
|
||||
<table class="table">
|
||||
<tr><th>Server</th> <td>{{hostname}}</td></tr>
|
||||
@@ -57,10 +59,10 @@
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<h4>Greylisting</h4>
|
||||
<p>Your box using a technique called greylisting to cut down on spam. Greylisting works by delaying mail from people you haven’t received mail from before for up to about 10 minutes. The vast majority of spam gets tricked by this. If you are waiting for an email from someone new, such as if you are registering on a new website and are waiting for an email confirmation, please give it up to 10-15 minutes to arrive.</p>
|
||||
<p>Your box uses a technique called greylisting to cut down on spam. Greylisting works by initially rejecting mail from people you haven’t received mail from before. Legitimate mail servers will attempt redelivery shortly afterwards, but the vast majority of spam gets tricked by this. If you are waiting for an email from someone new, such as if you are registering on a new website and are waiting for an email confirmation, please be aware there will be a minimum of 3 minutes delay, depending how soon the remote server attempts redelivery.</p>
|
||||
|
||||
<h4>+tag addresses</h4>
|
||||
<p>Every incoming email address also receives mail for <code>+tag</code> addresses. If your email address is <code>you@yourdomain.com</code>, you can also accept mail at <code>you+anythinghere@yourdomain.com</code>. Use this as a fast way to create aliases or to segment incoming mail for your own filtering rules.</p>
|
||||
<p>Every incoming email address also receives mail for <code>+tag</code> addresses. If your email address is <code>you@yourdomain.com</code>, you’ll also automatically get mail sent to <code>you+anythinghere@yourdomain.com</code>. Use this as a fast way to segment incoming mail for your own filtering rules without having to create aliases in this control panel.</p>
|
||||
|
||||
<h4>Use only this box to send as you</h4>
|
||||
<p>Your box sets strict email sending policies for your domain names to make it harder for spam and other fraudulent mail to claim to be you. Only this machine is authorized to send email on behalf of your domain names. If you use any other service to send email as you, it will likely get spam filtered by recipients.</p>
|
||||
|
||||
@@ -1,12 +1,31 @@
|
||||
<style>
|
||||
</style>
|
||||
|
||||
<h2>SSL Certificates</h2>
|
||||
<h2>TLS (SSL) Certificates</h2>
|
||||
|
||||
<h3>Certificate Status</h3>
|
||||
<p>A TLS (formerly called SSL) certificate is a cryptographic file that proves to anyone connecting to a web address that the connection is secure between you and the owner of that address.</p>
|
||||
|
||||
<p>You need a TLS certificate for this box’s hostname ({{hostname}}) and every other domain name and subdomain that this box is hosting a website for (see the list below).</p>
|
||||
|
||||
<table id="ssl_domains" class="table" style="margin-bottom: 2em; width: auto;">
|
||||
<div id="ssl_provision">
|
||||
<h3>Provision certificates</h3>
|
||||
|
||||
<div id="ssl_provision_p" style="display: none; margin-top: 1.5em">
|
||||
<button onclick='return provision_tls_cert();' class='btn btn-primary' style="float: left; margin: 0 1.5em 1em 0;">Provision</button>
|
||||
<p>A TLS certificate can be automatically provisioned from <a href="https://letsencrypt.org/" target="_blank">Let’s Encrypt</a>, a free TLS certificate provider, for:<br>
|
||||
<span class="text-primary"></span></p>
|
||||
</div>
|
||||
|
||||
<div class="clearfix"> </div>
|
||||
|
||||
<div id="ssl_provision_result"></div>
|
||||
</div>
|
||||
|
||||
<h3>Certificate status</h3>
|
||||
|
||||
<p style="margin-top: 1.5em">Certificates expire after a period of time. All certificates will be automatically renewed through <a href="https://letsencrypt.org/" target="_blank">Let’s Encrypt</a> 14 days prior to expiration.</p>
|
||||
|
||||
<table id="ssl_domains" class="table" style="margin-bottom: 2em; width: auto; display: none">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Domain</th>
|
||||
@@ -18,29 +37,39 @@
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p>Advanced:<br>Install a multi-domain or wildcard certificate for the <code>{{hostname}}</code> domain to have it automatically applied to any domains it is valid for.</p>
|
||||
|
||||
<h3 id="ssl_install_header">Install SSL Certificate</h3>
|
||||
<h3 id="ssl_install_header">Install certificate</h3>
|
||||
|
||||
<p>There are many places where you can get a free or cheap SSL certificate. We recommend <a href="https://www.namecheap.com/security/ssl-certificates/domain-validation.aspx">Namecheap’s $9 certificate</a> or <a href="https://www.startssl.com/">StartSSL’s free express lane</a>.</p>
|
||||
<p>If you don't want to use our automatic Let's Encrypt integration, you can give any other certificate provider a try. You can generate the needed CSR below.</p>
|
||||
|
||||
<p>Which domain are you getting an SSL certificate for?</p>
|
||||
<p>Which domain are you getting a certificate for?</p>
|
||||
|
||||
<p><select id="ssldomain" onchange="show_csr()" class="form-control" style="width: auto"></select></p>
|
||||
|
||||
<p>(A multi-domain or wildcard certificate will be automatically applied to any domains it is valid for besides the one you choose above.)</p>
|
||||
|
||||
<p>What country are you in? This is required by some TLS certificate providers. You may leave this blank if you know your TLS certificate provider doesn't require it.</p>
|
||||
|
||||
<p><select id="sslcc" onchange="show_csr()" class="form-control" style="width: auto">
|
||||
<option value="">(Select)</option>
|
||||
{% for code, name in csr_country_codes %}
|
||||
<option value="{{code}}">{{name}}</option>
|
||||
{% endfor %}
|
||||
</select></p>
|
||||
|
||||
<div id="csr_info" style="display: none">
|
||||
<p>You will need to provide the SSL certificate provider this Certificate Signing Request (CSR):</p>
|
||||
<p>You will need to provide the certificate provider this Certificate Signing Request (CSR):</p>
|
||||
|
||||
<pre id="ssl_csr"></pre>
|
||||
|
||||
<p><small>The CSR is safe to share. It can only be used in combination with a secret key stored on this machine.</small></p>
|
||||
|
||||
<p>The SSL certificate provider will then provide you with an SSL certificate. They may also provide you with an intermediate chain. Paste each separately into the boxes below:</p>
|
||||
<p>The certificate provider will then provide you with a TLS/SSL certificate. They may also provide you with an intermediate chain. Paste each separately into the boxes below:</p>
|
||||
|
||||
<p style="margin-bottom: .5em">SSL certificate:</p>
|
||||
<p style="margin-bottom: .5em">TLS/SSL certificate:</p>
|
||||
<p><textarea id="ssl_paste_cert" class="form-control" style="max-width: 40em; height: 8em" placeholder="-----BEGIN CERTIFICATE-----
stuff here
-----END CERTIFICATE-----"></textarea></p>
|
||||
|
||||
<p style="margin-bottom: .5em">SSL intermediate chain (if provided):</p>
|
||||
<p style="margin-bottom: .5em">TLS/SSL intermediate chain (if provided):</p>
|
||||
<p><textarea id="ssl_paste_chain" class="form-control" style="max-width: 40em; height: 8em" placeholder="-----BEGIN CERTIFICATE-----
stuff here
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
more stuff here
-----END CERTIFICATE-----"></textarea></p>
|
||||
|
||||
<p>After you paste in the information, click the install button.</p>
|
||||
@@ -49,26 +78,41 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function show_ssl() {
|
||||
function show_tls(keep_provisioning_shown) {
|
||||
api(
|
||||
"/web/domains",
|
||||
"/ssl/status",
|
||||
"GET",
|
||||
{
|
||||
},
|
||||
function(domains) {
|
||||
function(res) {
|
||||
// provisioning status
|
||||
|
||||
if (!keep_provisioning_shown)
|
||||
$('#ssl_provision').toggle(res.can_provision.length > 0)
|
||||
|
||||
$('#ssl_provision_p').toggle(res.can_provision.length > 0);
|
||||
if (res.can_provision.length > 0)
|
||||
$('#ssl_provision_p span').text(res.can_provision.join(", "));
|
||||
|
||||
// certificate status
|
||||
var domains = res.status;
|
||||
var tb = $('#ssl_domains tbody');
|
||||
tb.text('');
|
||||
$('#ssldomain').html('<option value="">(select)</option>');
|
||||
|
||||
$('#ssl_domains').show();
|
||||
for (var i = 0; i < domains.length; i++) {
|
||||
var row = $("<tr><th class='domain'><a href=''></a></th><td class='status'></td> <td class='actions'><a href='#' onclick='return ssl_install(this);' class='btn btn-xs'>Install Certificate</a></td></tr>");
|
||||
tb.append(row);
|
||||
row.attr('data-domain', domains[i].domain);
|
||||
row.find('.domain a').text(domains[i].domain);
|
||||
row.find('.domain a').attr('href', 'https://' + domains[i].domain);
|
||||
row.addClass("text-" + domains[i].ssl_certificate[0]);
|
||||
row.find('.status').text(domains[i].ssl_certificate[1]);
|
||||
if (domains[i].ssl_certificate[0] == "success") {
|
||||
if (domains[i].status == "not-applicable") {
|
||||
domains[i].status = "muted"; // text-muted css class
|
||||
row.find('.actions a').remove(); // no actions applicable
|
||||
}
|
||||
row.addClass("text-" + domains[i].status);
|
||||
row.find('.status').text(domains[i].text);
|
||||
if (domains[i].status == "success") {
|
||||
row.find('.actions a').addClass('btn-default').text('Replace Certificate');
|
||||
} else {
|
||||
row.find('.actions a').addClass('btn-primary').text('Install Certificate');
|
||||
@@ -82,18 +126,24 @@ function show_ssl() {
|
||||
function ssl_install(elem) {
|
||||
var domain = $(elem).parents('tr').attr('data-domain');
|
||||
$('#ssldomain').val(domain);
|
||||
$('#csr_info').slideDown();
|
||||
$('#ssl_csr').text('Loading...');
|
||||
show_csr();
|
||||
$('html, body').animate({ scrollTop: $('#ssl_install_header').offset().top - $('.navbar-fixed-top').height() - 20 })
|
||||
return false;
|
||||
}
|
||||
|
||||
function show_csr() {
|
||||
// Can't show a CSR until both inputs are entered.
|
||||
if ($('#ssldomain').val() == "") return;
|
||||
if ($('#sslcc').val() == "") return;
|
||||
|
||||
// Scroll to it and fetch.
|
||||
$('#csr_info').slideDown();
|
||||
$('#ssl_csr').text('Loading...');
|
||||
api(
|
||||
"/ssl/csr/" + $('#ssldomain').val(),
|
||||
"POST",
|
||||
{
|
||||
countrycode: $('#sslcc').val()
|
||||
},
|
||||
function(data) {
|
||||
$('#ssl_csr').text(data);
|
||||
@@ -110,11 +160,77 @@ function install_cert() {
|
||||
chain: $('#ssl_paste_chain').val()
|
||||
},
|
||||
function(status) {
|
||||
if (status == "") {
|
||||
show_modal_error("SSL Certificate Installation", "Certificate has been installed. Check that you have no connection problems to the domain.", function() { show_ssl(); $('#csr_info').slideUp(); });
|
||||
if (/^OK($|\n)/.test(status)) {
|
||||
console.log(status)
|
||||
show_modal_error("TLS Certificate Installation", "Certificate has been installed. Check that you have no connection problems to the domain.", function() { show_ssl(); $('#csr_info').slideUp(); });
|
||||
} else {
|
||||
show_modal_error("SSL Certificate Installation", status);
|
||||
show_modal_error("TLS Certificate Installation", status);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function provision_tls_cert() {
|
||||
// Automatically provision any certs.
|
||||
$('#ssl_provision_p .btn').attr('disabled', '1'); // prevent double-clicks
|
||||
api(
|
||||
"/ssl/provision",
|
||||
"POST",
|
||||
{ },
|
||||
function(status) {
|
||||
// Clear last attempt.
|
||||
$('#ssl_provision_result').text("");
|
||||
may_reenable_provision_button = true;
|
||||
|
||||
// Nothing was done. There might also be problem domains, but we've already displayed those.
|
||||
if (status.requests.length == 0) {
|
||||
show_modal_error("TLS Certificate Provisioning", "There were no domain names to provision certificates for.");
|
||||
// don't return - haven't re-enabled the provision button
|
||||
}
|
||||
|
||||
// Each provisioning API call returns zero or more "requests" which represent
|
||||
// a request to Let's Encrypt for a single certificate. Normally there is just
|
||||
// one request (for a single multi-domain certificate).
|
||||
for (var i = 0; i < status.requests.length; i++) {
|
||||
var r = status.requests[i];
|
||||
|
||||
if (r.result == "skipped") {
|
||||
// not interested --- this domain wasn't in the table
|
||||
// to begin with
|
||||
continue;
|
||||
}
|
||||
|
||||
// create an HTML block to display the results of this request
|
||||
var n = $("<div><h4/><p/></div>");
|
||||
$('#ssl_provision_result').append(n);
|
||||
|
||||
// plain log line
|
||||
if (typeof r === "string") {
|
||||
n.find("p").text(r);
|
||||
continue;
|
||||
}
|
||||
|
||||
// show a header only to disambiguate request blocks
|
||||
if (status.requests.length > 0)
|
||||
n.find("h4").text(r.domains.join(", "));
|
||||
|
||||
if (r.result == "error") {
|
||||
n.find("p").addClass("text-danger").text(r.message);
|
||||
|
||||
} else if (r.result == "installed") {
|
||||
n.find("p").addClass("text-success").text("The TLS certificate was provisioned and installed.");
|
||||
setTimeout("show_tls(true)", 1); // update main table of certificate statuses, call with arg keep_provisioning_shown true so that we don't clear what we just outputted
|
||||
|
||||
}
|
||||
|
||||
// display the detailed log info in case of problems
|
||||
var trace = $("<div class='small text-muted' style='margin-top: 1.5em'>Log:</div>");
|
||||
n.append(trace);
|
||||
for (var j = 0; j < r.log.length; j++)
|
||||
trace.append($("<div/>").text(r.log[j]));
|
||||
}
|
||||
|
||||
if (may_reenable_provision_button)
|
||||
$('#ssl_provision_p .btn').removeAttr("disabled");
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
|
||||
<table class="table">
|
||||
<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/repository/browse/?fdfilter=dav&fdid=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">DAVdroid</a> ($3.69; 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 Calendar</td> <td><a href="https://play.google.com/store/apps/details?id=org.dmfs.caldav.lib">CalDAV-Sync</a> ($2.89)</td></tr>
|
||||
</table>
|
||||
|
||||
@@ -5,17 +5,130 @@
|
||||
|
||||
<h2>Backup Status</h2>
|
||||
|
||||
<h3>Copying Backup Files</h3>
|
||||
<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. The backup is stored on the machine itself. You are responsible for copying the backup files off of the machine.</p>
|
||||
<h3>Configuration</h3>
|
||||
|
||||
<p>Many cloud providers make this easy by allowing you to take snapshots of the machine's disk.</p>
|
||||
<form class="form-horizontal" role="form" onsubmit="set_custom_backup(); return false;">
|
||||
<div class="form-group">
|
||||
<label for="backup-target-type" class="col-sm-2 control-label">Backup to:</label>
|
||||
<div class="col-sm-2">
|
||||
<select class="form-control" rows="1" id="backup-target-type" onchange="toggle_form()">
|
||||
<option value="off">Nowhere (Disable Backups)</option>
|
||||
<option value="local">{{hostname}}</option>
|
||||
<option value="rsync">rsync</option>
|
||||
<option value="s3">Amazon S3</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<!-- LOCAL BACKUP -->
|
||||
<div class="form-group backup-target-local">
|
||||
<div class="col-sm-10 col-sm-offset-2">
|
||||
<p>Backups are stored on this machine’s own hard disk. You are responsible for periodically using SFTP (FTP over SSH) to copy the backup files from <tt class="backup-location"></tt> to a safe location. These files are encrypted, so they are safe to store anywhere.</p>
|
||||
<p>Separately 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.</p>
|
||||
</div>
|
||||
</div>
|
||||
<!-- RSYNC BACKUP -->
|
||||
<div class="form-group backup-target-rsync">
|
||||
<div class="col-sm-10 col-sm-offset-2">
|
||||
|
||||
<p>You can also use SFTP (FTP over SSH) to copy files from <tt id="backup-location"></tt>. These files are encrpyted, so they are safe to store anywhere. Copy the encryption password from <tt id="backup-encpassword-file"></tt> also but keep it in a safe location.</p>
|
||||
<p>Backups synced to a remote machine using rsync over SSH, with local
|
||||
copies in <tt class="backup-location"></tt>. These files are encrypted, so
|
||||
they are safe to store anywhere.</p> <p>Separately 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.</p>
|
||||
|
||||
<h3>Current Backups</h3>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group backup-target-rsync">
|
||||
<label for="backup-target-rsync-host" class="col-sm-2 control-label">Hostname</label>
|
||||
<div class="col-sm-8">
|
||||
<input type="text" placeholder="hostname.local" class="form-control" rows="1" id="backup-target-rsync-host">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group backup-target-rsync">
|
||||
<label for="backup-target-rsync-path" class="col-sm-2 control-label">Path</label>
|
||||
<div class="col-sm-8">
|
||||
<input type="text" placeholder="/backups/{{hostname}}" class="form-control" rows="1" id="backup-target-rsync-path">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group backup-target-rsync">
|
||||
<label for="backup-target-rsync-user" class="col-sm-2 control-label">Username</label>
|
||||
<div class="col-sm-8">
|
||||
<input type="text" class="form-control" rows="1" id="backup-target-rsync-user">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group backup-target-rsync">
|
||||
<label for="ssh-pub-key" class="col-sm-2 control-label">Public SSH Key</label>
|
||||
<div class="col-sm-8">
|
||||
<input type="text" class="form-control" rows="1" id="ssh-pub-key" readonly>
|
||||
<div class="small" style="margin-top: 2px">
|
||||
Copy the Public SSH Key above, and paste it within the <tt>~/.ssh/authorized_keys</tt>
|
||||
of target user on the backup server specified above. That way you'll enable secure and
|
||||
passwordless authentication from your mail-in-a-box server and your backup server.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- S3 BACKUP -->
|
||||
<div class="form-group backup-target-s3">
|
||||
<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>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>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group backup-target-s3">
|
||||
<label for="backup-target-s3-host-select" class="col-sm-2 control-label">S3 Region</label>
|
||||
<div class="col-sm-8">
|
||||
<select class="form-control" rows="1" id="backup-target-s3-host-select">
|
||||
{% for name, host in backup_s3_hosts %}
|
||||
<option value="{{host}}">{{name}}</option>
|
||||
{% endfor %}
|
||||
<option value="other">Other</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group backup-target-s3">
|
||||
<label for="backup-target-s3-host" class="col-sm-2 control-label">S3 Host / Endpoint</label>
|
||||
<div class="col-sm-8">
|
||||
<input type="text" placeholder="Endpoint" class="form-control" rows="1" id="backup-target-s3-host">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group backup-target-s3">
|
||||
<label for="backup-target-s3-path" class="col-sm-2 control-label">S3 Path</label>
|
||||
<div class="col-sm-8">
|
||||
<input type="text" placeholder="your-bucket-name/backup-directory" class="form-control" rows="1" id="backup-target-s3-path">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group backup-target-s3">
|
||||
<label for="backup-target-user" class="col-sm-2 control-label">S3 Access Key</label>
|
||||
<div class="col-sm-8">
|
||||
<input type="text" class="form-control" rows="1" id="backup-target-user">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group backup-target-s3">
|
||||
<label for="backup-target-pass" class="col-sm-2 control-label">S3 Secret Access Key</label>
|
||||
<div class="col-sm-8">
|
||||
<input type="text" class="form-control" rows="1" id="backup-target-pass">
|
||||
</div>
|
||||
</div>
|
||||
<!-- Common -->
|
||||
<div class="form-group backup-target-local backup-target-rsync backup-target-s3">
|
||||
<label for="min-age" class="col-sm-2 control-label">Days:</label>
|
||||
<div class="col-sm-8">
|
||||
<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>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<div class="col-sm-offset-2 col-sm-10">
|
||||
<button id="set-s3-backup-button" type="submit" class="btn btn-primary">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<p>The backup directory currently contains the backups listed below. The total size on disk of the backups is <span id="backup-total-size"></span>.</p>
|
||||
<h3>Available backups</h3>
|
||||
|
||||
<p>The backup location currently contains the backups listed below. The total size of the backups is currently <span id="backup-total-size"></span>.</p>
|
||||
|
||||
<table id="backup-status" class="table" style="width: auto">
|
||||
<thead>
|
||||
@@ -27,10 +140,16 @@
|
||||
<tbody>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p style="margin-top: 2em"><small>The size column in the table indicates the size of the encrpyted backup, but the total size on disk shown above includes storage for unencrpyted intermediate files.</small></p>
|
||||
|
||||
<script>
|
||||
|
||||
function toggle_form() {
|
||||
var target_type = $("#backup-target-type").val();
|
||||
$(".backup-target-local, .backup-target-rsync, .backup-target-s3").hide();
|
||||
$(".backup-target-" + target_type).show();
|
||||
|
||||
init_inputs(target_type);
|
||||
}
|
||||
|
||||
function nice_size(bytes) {
|
||||
var powers = ['bytes', 'KB', 'MB', 'GB', 'TB'];
|
||||
while (true) {
|
||||
@@ -48,19 +167,27 @@ function nice_size(bytes) {
|
||||
}
|
||||
|
||||
function show_system_backup() {
|
||||
show_custom_backup()
|
||||
|
||||
$('#backup-status tbody').html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/system/backup/status",
|
||||
"GET",
|
||||
{ },
|
||||
function(r) {
|
||||
$('#backup-location').text(r.encdirectory);
|
||||
$('#backup-encpassword-file').text(r.encpwfile);
|
||||
if (r.error) {
|
||||
show_modal_error("Backup Error", $("<pre/>").text(r.error));
|
||||
return;
|
||||
}
|
||||
|
||||
$('#backup-status tbody').html("");
|
||||
var total_disk_size = 0;
|
||||
|
||||
if (r.backups.length == 0) {
|
||||
if (typeof r.backups == "undefined") {
|
||||
var tr = $('<tr><td colspan="3">Backups are turned off.</td></tr>');
|
||||
$('#backup-status tbody').append(tr);
|
||||
return;
|
||||
} else if (r.backups.length == 0) {
|
||||
var tr = $('<tr><td colspan="3">No backups have been made yet.</td></tr>');
|
||||
$('#backup-status tbody').append(tr);
|
||||
}
|
||||
@@ -69,21 +196,111 @@ function show_system_backup() {
|
||||
var b = r.backups[i];
|
||||
var tr = $('<tr/>');
|
||||
if (b.full) tr.addClass("full-backup");
|
||||
tr.append( $('<td/>').text(b.date_str + " " + r.tz) );
|
||||
tr.append( $('<td/>').text(b.date_str) );
|
||||
tr.append( $('<td/>').text(b.date_delta + " ago") );
|
||||
tr.append( $('<td/>').text(b.full ? "full" : "increment") );
|
||||
tr.append( $('<td style="text-align: right"/>').text( nice_size(b.encsize)) );
|
||||
tr.append( $('<td style="text-align: right"/>').text( nice_size(b.size)) );
|
||||
if (b.deleted_in)
|
||||
tr.append( $('<td/>').text(b.deleted_in) );
|
||||
else
|
||||
tr.append( $('<td class="text-muted">n/a</td>') );
|
||||
tr.append( $('<td class="text-muted">unknown</td>') );
|
||||
$('#backup-status tbody').append(tr);
|
||||
|
||||
total_disk_size += b.size;
|
||||
total_disk_size += b.encsize;
|
||||
}
|
||||
|
||||
total_disk_size += r.unmatched_file_size;
|
||||
$('#backup-total-size').text(nice_size(total_disk_size));
|
||||
})
|
||||
}
|
||||
|
||||
function show_custom_backup() {
|
||||
$(".backup-target-local, .backup-target-rsync, .backup-target-s3").hide();
|
||||
api(
|
||||
"/system/backup/config",
|
||||
"GET",
|
||||
{ },
|
||||
function(r) {
|
||||
$("#backup-target-user").val(r.target_user);
|
||||
$("#backup-target-pass").val(r.target_pass);
|
||||
$("#min-age").val(r.min_age_in_days);
|
||||
$(".backup-location").text(r.file_target_directory);
|
||||
$(".backup-encpassword-file").text(r.enc_pw_file);
|
||||
$("#ssh-pub-key").val(r.ssh_pub_key);
|
||||
|
||||
if (r.target == "file://" + r.file_target_directory) {
|
||||
$("#backup-target-type").val("local");
|
||||
} else if (r.target == "off") {
|
||||
$("#backup-target-type").val("off");
|
||||
} else if (r.target.substring(0, 8) == "rsync://") {
|
||||
$("#backup-target-type").val("rsync");
|
||||
var path = r.target.substring(8).split('//');
|
||||
var host_parts = path.shift().split('@');
|
||||
$("#backup-target-rsync-user").val(host_parts[0]);
|
||||
$("#backup-target-rsync-host").val(host_parts[1]);
|
||||
$("#backup-target-rsync-path").val('/'+path[0]);
|
||||
} else if (r.target.substring(0, 5) == "s3://") {
|
||||
$("#backup-target-type").val("s3");
|
||||
var hostpath = r.target.substring(5).split('/');
|
||||
var host = hostpath.shift();
|
||||
$("#backup-target-s3-host").val(host);
|
||||
$("#backup-target-s3-path").val(hostpath.join('/'));
|
||||
}
|
||||
toggle_form()
|
||||
})
|
||||
}
|
||||
|
||||
function set_custom_backup() {
|
||||
var target_type = $("#backup-target-type").val();
|
||||
var target_user = $("#backup-target-user").val();
|
||||
var target_pass = $("#backup-target-pass").val();
|
||||
|
||||
var target;
|
||||
if (target_type == "local" || target_type == "off")
|
||||
target = target_type;
|
||||
else if (target_type == "s3")
|
||||
target = "s3://" + $("#backup-target-s3-host").val() + "/" + $("#backup-target-s3-path").val();
|
||||
else if (target_type == "rsync") {
|
||||
target = "rsync://" + $("#backup-target-rsync-user").val() + "@" + $("#backup-target-rsync-host").val()
|
||||
+ "/" + $("#backup-target-rsync-path").val();
|
||||
target_user = '';
|
||||
}
|
||||
|
||||
|
||||
var min_age = $("#min-age").val();
|
||||
api(
|
||||
"/system/backup/config",
|
||||
"POST",
|
||||
{
|
||||
target: target,
|
||||
target_user: target_user,
|
||||
target_pass: target_pass,
|
||||
min_age: min_age
|
||||
},
|
||||
function(r) {
|
||||
// use .text() --- it's a text response, not html
|
||||
show_modal_error("Backup configuration", $("<p/>").text(r), function() { if (r == "OK") show_system_backup(); }); // refresh after modal on success
|
||||
},
|
||||
function(r) {
|
||||
// use .text() --- it's a text response, not html
|
||||
show_modal_error("Backup configuration", $("<p/>").text(r));
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
function init_inputs(target_type) {
|
||||
function set_host(host) {
|
||||
if(host !== 'other') {
|
||||
$("#backup-target-s3-host").val(host);
|
||||
} else {
|
||||
$("#backup-target-s3-host").val('');
|
||||
}
|
||||
}
|
||||
if (target_type == "s3") {
|
||||
$('#backup-target-s3-host-select').off('change').on('change', function() {
|
||||
set_host($('#backup-target-s3-host-select').val());
|
||||
});
|
||||
set_host($('#backup-target-s3-host-select').val());
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -36,6 +36,22 @@
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-push-9 col-md-3">
|
||||
|
||||
<div id="system-reboot-required" style="display: none; margin-bottom: 1em;">
|
||||
<button type="button" class="btn btn-danger" onclick="confirm_reboot(); return false;">Reboot Box</button>
|
||||
<div>No reboot is necessary.</div>
|
||||
</div>
|
||||
|
||||
<div id="system-privacy-setting" style="display: none">
|
||||
<div><a onclick="return enable_privacy(!current_privacy_setting)" href="#"><span>Enable/Disable</span> New-Version Check</a></div>
|
||||
<p style="line-height: 125%"><small>(When enabled, status checks phone-home to check for a new release of Mail-in-a-Box.)</small></p>
|
||||
</div>
|
||||
|
||||
</div> <!-- /col -->
|
||||
<div class="col-md-pull-3 col-md-8">
|
||||
|
||||
<table id="system-checks" class="table" style="max-width: 60em">
|
||||
<thead>
|
||||
</thead>
|
||||
@@ -43,9 +59,34 @@
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
</div> <!-- /col -->
|
||||
</div> <!-- /row -->
|
||||
|
||||
<script>
|
||||
function show_system_status() {
|
||||
$('#system-checks tbody').html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
|
||||
|
||||
api(
|
||||
"/system/privacy",
|
||||
"GET",
|
||||
{ },
|
||||
function(r) {
|
||||
current_privacy_setting = r;
|
||||
$('#system-privacy-setting').show();
|
||||
$('#system-privacy-setting a span').text(r ? "Enable" : "Disable");
|
||||
$('#system-privacy-setting p').toggle(r);
|
||||
});
|
||||
|
||||
api(
|
||||
"/system/reboot",
|
||||
"GET",
|
||||
{ },
|
||||
function(r) {
|
||||
$('#system-reboot-required').show(); // show when r becomes available
|
||||
$('#system-reboot-required').find('button').toggle(r);
|
||||
$('#system-reboot-required').find('div').toggle(!r);
|
||||
});
|
||||
|
||||
api(
|
||||
"/system/status",
|
||||
"POST",
|
||||
@@ -82,5 +123,38 @@ function show_system_status() {
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
var current_privacy_setting = null;
|
||||
function enable_privacy(status) {
|
||||
api(
|
||||
"/system/privacy",
|
||||
"POST",
|
||||
{
|
||||
value: (status ? "private" : "off")
|
||||
},
|
||||
function(res) {
|
||||
show_system_status();
|
||||
});
|
||||
return false; // disable link
|
||||
}
|
||||
|
||||
function confirm_reboot() {
|
||||
show_modal_confirm(
|
||||
"Reboot",
|
||||
$("<p>This will reboot your Mail-in-a-Box <code>{{hostname}}</code>.</p> <p>Until the machine is fully restarted, your users will not be able to send and receive email, and you will not be able to connect to this control panel or with SSH. The reboot cannot be cancelled.</p>"),
|
||||
"Reboot Now",
|
||||
function() {
|
||||
api(
|
||||
"/system/reboot",
|
||||
"POST",
|
||||
{ },
|
||||
function(r) {
|
||||
var msg = "<p>Please reload this page after a minute or so.</p>";
|
||||
if (r) msg = "<p>The reboot command said:</p> <pre>" + $("<pre/>").text(r).html() + "</pre>"; // successful reboots don't produce any output; the output must be HTML-escaped
|
||||
show_modal_error("Reboot", msg);
|
||||
});
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
<h2>Users</h2>
|
||||
|
||||
<style>
|
||||
#user_table h4 { margin: 1em 0 0 0; }
|
||||
#user_table tr.account_inactive td.address { color: #888; text-decoration: line-through; }
|
||||
#user_table .aliases { font-size: 90%; }
|
||||
#user_table .aliases div:before { content: "⇖ "; }
|
||||
#user_table .aliases div { }
|
||||
#user_table .actions { margin-top: .33em; font-size: 95%; }
|
||||
#user_table .account_inactive .if_active { display: none; }
|
||||
#user_table .account_active .if_inactive { display: none; }
|
||||
#user_table .account_active.if_inactive { display: none; }
|
||||
</style>
|
||||
|
||||
<h3>Add a mail user</h3>
|
||||
|
||||
<p>Add an email address to this system. This will create a new login username/password. (Use <a href="javascript:show_panel('aliases')">aliases</a> to create email addresses that forward to existing accounts.)</p>
|
||||
<p>Add an email address to this system. This will create a new login username/password.</p>
|
||||
|
||||
<form class="form-inline" role="form" onsubmit="return do_add_user(); return false;">
|
||||
<div class="form-group">
|
||||
@@ -31,10 +30,12 @@
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Add User</button>
|
||||
</form>
|
||||
<p style="margin-top: .5em"><small>
|
||||
Passwords must be at least four characters and may not contain spaces.
|
||||
Administrators get access to this control panel.
|
||||
</small></p>
|
||||
<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>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>User accounts cannot contain any international (non-ASCII) characters, but <a href="#" onclick="return show_panel('aliases');">aliases</a> can.</li>
|
||||
</ul>
|
||||
|
||||
<h3>Existing mail users</h3>
|
||||
<table id="user_table" class="table" style="width: auto">
|
||||
@@ -42,7 +43,6 @@
|
||||
<tr>
|
||||
<th width="50%">Email Address</th>
|
||||
<th>Actions</th>
|
||||
<th>Mailbox Size</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -72,19 +72,57 @@
|
||||
archive account
|
||||
</a>
|
||||
</td>
|
||||
<td class='mailboxsize'>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="user-extra-template">
|
||||
<td colspan="3" style="border-top: 0; padding-top: 0">
|
||||
<div class='if_inactive restore_info' style='color: #888; font-size: 90%'>To restore account, create a new account with this email address. Or to permanently delete the mailbox, delete the directory <tt></tt> on the machine.</div>
|
||||
|
||||
<div class='aliases' style='display: none'> </div>
|
||||
<tr id="user-extra-template" class="if_inactive">
|
||||
<td colspan="3" style="border: 0; padding-top: 0">
|
||||
<div class='restore_info' style='color: #888; font-size: 90%'>To restore account, create a new account with this email address. Or to permanently delete the mailbox, delete the directory <tt></tt> on the machine.</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<h3>Mail user API (advanced)</h3>
|
||||
|
||||
<p>Use your box’s mail user API to add/change/remove users from the command-line or custom services you build.</p>
|
||||
|
||||
<p>Usage:</p>
|
||||
|
||||
<pre>curl -X <b>VERB</b> [-d "<b>parameters</b>"] --user {email}:{password} https://{{hostname}}/admin/mail/users[<b>action</b>]</pre>
|
||||
|
||||
<p>Brackets denote an optional argument. Please note that the POST body <code>parameters</code> must be URL-encoded.</p>
|
||||
|
||||
<p>The email and password given to the <code>--user</code> option must be an administrative user on this system.</p>
|
||||
|
||||
<h4 style="margin-bottom: 0">Verbs</h4>
|
||||
|
||||
<table class="table" style="margin-top: .5em">
|
||||
<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>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>/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>
|
||||
</table>
|
||||
|
||||
<h4>Examples:</h4>
|
||||
|
||||
<p>Try these examples. For simplicity the examples omit the <code>--user me@mydomain.com:yourpassword</code> command line argument which you must fill in with your administrative email address and password.</p>
|
||||
|
||||
<pre># Gives a JSON-encoded list of all mail users
|
||||
curl -X GET https://{{hostname}}/admin/mail/users?format=json
|
||||
|
||||
# Adds a new email user
|
||||
curl -X POST -d "email=new_user@mydomail.com" -d "password=s3curE_pa5Sw0rD" https://{{hostname}}/admin/mail/users/add
|
||||
|
||||
# Removes a email user
|
||||
curl -X POST -d "email=new_user@mydomail.com" https://{{hostname}}/admin/mail/users/remove
|
||||
|
||||
# Adds admin privilege to an email user
|
||||
curl -X POST -d "email=new_user@mydomail.com" -d "privilege=admin" https://{{hostname}}/admin/mail/users/privileges/add
|
||||
|
||||
# Removes admin privilege from an email user
|
||||
curl -X POST -d "email=new_user@mydomail.com" https://{{hostname}}/admin/mail/users/privileges/remove
|
||||
</pre>
|
||||
|
||||
<script>
|
||||
function show_users() {
|
||||
@@ -96,7 +134,7 @@ function show_users() {
|
||||
function(r) {
|
||||
$('#user_table tbody').html("");
|
||||
for (var i = 0; i < r.length; i++) {
|
||||
var hdr = $("<tr><td><h4/></td></tr>");
|
||||
var hdr = $("<tr><td colspan='3'><h4/></td></tr>");
|
||||
hdr.find('h4').text(r[i].domain);
|
||||
$('#user_table tbody').append(hdr);
|
||||
|
||||
@@ -115,7 +153,6 @@ function show_users() {
|
||||
|
||||
n.attr('data-email', user.email);
|
||||
n.find('.address').text(user.email)
|
||||
n.find('.mailboxsize').text(nice_size(user.mailbox_size))
|
||||
n2.find('.restore_info tt').text(user.mailbox);
|
||||
|
||||
if (user.status == 'inactive') continue;
|
||||
@@ -135,16 +172,6 @@ function show_users() {
|
||||
p.find('span.name').text(add_privs[j]);
|
||||
n.find('.add-privs').append(p);
|
||||
}
|
||||
|
||||
if (user.aliases && user.aliases.length > 0) {
|
||||
n2.find('.aliases').show();
|
||||
for (var j = 0; j < user.aliases.length; j++) {
|
||||
n2.find('.aliases').append($("<div/>").text(
|
||||
user.aliases[j][0]
|
||||
+ (user.aliases[j][1].length > 0 ? " ⇐ " + user.aliases[j][1].join(", ") : "")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -175,9 +202,14 @@ function do_add_user() {
|
||||
|
||||
function users_set_password(elem) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
|
||||
var yourpw = "";
|
||||
if (api_credentials != null && email == api_credentials[0])
|
||||
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(
|
||||
"Archive User",
|
||||
$("<p>Set a new password for <b>" + email + "</b>?</p> <p><label for='users_set_password_pw' style='display: block; font-weight: normal'>New Password:</label><input type='password' id='users_set_password_pw'></p><p><small>Passwords must be at least four characters and may not contain spaces.</small></p>"),
|
||||
"Set Password",
|
||||
$("<p>Set a new password for <b>" + email + "</b>?</p> <p><label for='users_set_password_pw' style='display: block; font-weight: normal'>New Password:</label><input type='password' id='users_set_password_pw'></p><p><small>Passwords must be at least eight characters and may not contain spaces.</small>" + yourpw + "</p>"),
|
||||
"Set Password",
|
||||
function() {
|
||||
api(
|
||||
@@ -199,6 +231,13 @@ function users_set_password(elem) {
|
||||
|
||||
function users_remove(elem) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
|
||||
// can't remove yourself
|
||||
if (api_credentials != null && email == api_credentials[0]) {
|
||||
show_modal_error("Archive User", "You cannot archive your own account.");
|
||||
return;
|
||||
}
|
||||
|
||||
show_modal_confirm(
|
||||
"Archive User",
|
||||
$("<p>Are you sure you want to archive <b>" + email + "</b>?</p> <p>The user's mailboxes will not be deleted (you can do that later), but the user will no longer be able to log into any services on this machine.</p>"),
|
||||
@@ -234,7 +273,7 @@ function mod_priv(elem, add_remove) {
|
||||
var add_remove1 = add_remove.charAt(0).toUpperCase() + add_remove.substring(1);
|
||||
show_modal_confirm(
|
||||
"Modify Privileges",
|
||||
"Are you sure you want to " + add_remove + " the " + priv + " privilege for <b>" + email + "</b>?",
|
||||
$("<p>Are you sure you want to " + add_remove + " the " + priv + " privilege for <b>" + email + "</b>?</p>"),
|
||||
add_remove1,
|
||||
function() {
|
||||
api(
|
||||
@@ -249,4 +288,13 @@ function mod_priv(elem, add_remove) {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function generate_random_password() {
|
||||
var pw = "";
|
||||
var charset = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"; // confusable characters skipped
|
||||
for (var i = 0; i < 12; i++)
|
||||
pw += charset.charAt(Math.floor(Math.random() * charset.length));
|
||||
show_modal_error("Random Password", "<p>Here, try this:</p> <p><code style='font-size: 110%'>" + pw + "</code></pr");
|
||||
return false; // cancel click
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
<h3>Uploading web files</h3>
|
||||
|
||||
<p>You can replace the default website with your own HTML pages and other static files. This control panel won’t help you design a website, but once you have <tt>.html</tt> files you can upload it following these instructions:</p>
|
||||
<p>You can replace the default website with your own HTML pages and other static files. This control panel won’t help you design a website, but once you have <tt>.html</tt> files you can upload them following these instructions:</p>
|
||||
|
||||
<ol>
|
||||
<li>Ensure that any domains you are publishing a website for have no problems on the <a href="#system_status" onclick="return show_panel(this);">Status Checks</a> page.</li>
|
||||
@@ -18,41 +18,24 @@
|
||||
|
||||
<li>Upload your <tt>.html</tt> or other files to the directory <tt>{{storage_root}}/www/default</tt> on this machine. They will appear directly and immediately on the web.</li>
|
||||
|
||||
<li>The websites set up on this machine are listed in the table below with where to put the files for each website (if you have customized that, see next section).</li>
|
||||
<li>The websites set up on this machine are listed in the table below with where to put the files for each website.</li>
|
||||
|
||||
<table id="web_domains_existing" class="table" style="margin-bottom: 2em; width: auto;">
|
||||
<table id="web_domains_existing" class="table" style="margin-bottom: 1em; width: auto;">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Site</th>
|
||||
<th>Directory for Files</th>
|
||||
<th/>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<li>If you want to have this box host a static website on a domain that is not listed in the table, create a dummy <a href="#users" onclick="return show_panel(this);">mail user</a> or <a href="#aliases" onclick="return show_panel(this);">alias</a> on the domain first.</li>
|
||||
<p>To add a domain to this table, create a dummy <a href="#users" onclick="return show_panel(this);">mail user</a> or <a href="#aliases" onclick="return show_panel(this);">alias</a> on the domain first and see the <a href="https://mailinabox.email/guide.html#domain-name-configuration">setup guide</a> for adding nameserver records to the new domain at your registrar (but <i>not</i> glue records).</p>
|
||||
|
||||
</ol>
|
||||
|
||||
<h3>Different sites for different domains</h3>
|
||||
|
||||
<p>Create one of the directories shown in the table below to create a space for different files for one of the websites.</p>
|
||||
|
||||
<p>After you create one of these directories, click <button id="web_update" class="btn btn-primary" onclick="do_web_update()">Web Update</button> to restart the box’s web server so that it sees the new website file location.</p>
|
||||
|
||||
<table id="web_domains_custom" class="table" style="margin-bottom: 2em; width: auto;">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Site</th>
|
||||
<th>Create Directory</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
|
||||
<script>
|
||||
function show_web() {
|
||||
api(
|
||||
@@ -64,24 +47,18 @@ function show_web() {
|
||||
var tb = $('#web_domains_existing tbody');
|
||||
tb.text('');
|
||||
for (var i = 0; i < domains.length; i++) {
|
||||
var row = $("<tr><th class='domain'><a href=''></a></th><td class='directory'><tt/></td></tr>");
|
||||
if (!domains[i].static_enabled) continue;
|
||||
var row = $("<tr><th class='domain'><a href=''></a></th><td class='directory'><tt/></td> <td class='change-root hidden'><button class='btn btn-default btn-xs' onclick='show_change_web_root(this)'>Change</button></td></tr>");
|
||||
tb.append(row);
|
||||
row.attr('data-domain', domains[i].domain);
|
||||
row.attr('data-custom-web-root', domains[i].custom_root);
|
||||
row.find('.domain a').text('https://' + domains[i].domain);
|
||||
row.find('.domain a').attr('href', 'https://' + domains[i].domain);
|
||||
row.find('.directory tt').text(domains[i].root);
|
||||
if (domains[i].root != domains[i].custom_root)
|
||||
row.find('.change-root').removeClass('hidden');
|
||||
}
|
||||
|
||||
tb = $('#web_domains_custom tbody');
|
||||
tb.text('');
|
||||
for (var i = 0; i < domains.length; i++) {
|
||||
if (domains[i].root != domains[i].custom_root) {
|
||||
var row = $("<tr><th class='domain'><a href=''></a></th><td class='directory'><tt></td></tr>");
|
||||
tb.append(row);
|
||||
row.find('.domain a').text('https://' + domains[i].domain);
|
||||
row.find('.domain a').attr('href', 'https://' + domains[i].domain);
|
||||
row.find('.directory tt').text(domains[i].custom_root);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -99,4 +76,14 @@ function do_web_update() {
|
||||
show_modal_error("Web Update", data, function() { show_web() });
|
||||
});
|
||||
}
|
||||
|
||||
function show_change_web_root(elem) {
|
||||
var domain = $(elem).parents('tr').attr('data-domain');
|
||||
var root = $(elem).parents('tr').attr('data-custom-web-root');
|
||||
show_modal_confirm(
|
||||
'Change Root Directory for ' + domain,
|
||||
$('<p>You can change the static directory for <tt>' + domain + '</tt> to:</p> <p><tt>' + root + '</tt></p> <p>First create this directory on the server. Then click Update to scan for the directory and update web settings.</p>'),
|
||||
'Update',
|
||||
function() { do_web_update(); });
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import os.path
|
||||
|
||||
CONF_DIR = os.path.join(os.path.dirname(__file__), "../conf")
|
||||
# DO NOT import non-standard modules. This module is imported by
|
||||
# migrate.py which runs on fresh machines before anything is installed
|
||||
# besides Python.
|
||||
|
||||
# THE ENVIRONMENT FILE AT /etc/mailinabox.conf
|
||||
|
||||
def load_environment():
|
||||
# Load settings from /etc/mailinabox.conf.
|
||||
@@ -18,38 +22,78 @@ def save_environment(env):
|
||||
for k, v in env.items():
|
||||
f.write("%s=%s\n" % (k, v))
|
||||
|
||||
# THE SETTINGS FILE AT STORAGE_ROOT/settings.yaml.
|
||||
|
||||
def write_settings(config, env):
|
||||
import rtyaml
|
||||
fn = os.path.join(env['STORAGE_ROOT'], 'settings.yaml')
|
||||
with open(fn, "w") as f:
|
||||
f.write(rtyaml.dump(config))
|
||||
|
||||
def load_settings(env):
|
||||
import rtyaml
|
||||
fn = os.path.join(env['STORAGE_ROOT'], 'settings.yaml')
|
||||
try:
|
||||
config = rtyaml.load(open(fn, "r"))
|
||||
if not isinstance(config, dict): raise ValueError() # caught below
|
||||
return config
|
||||
except:
|
||||
return { }
|
||||
|
||||
# UTILITIES
|
||||
|
||||
def safe_domain_name(name):
|
||||
# Sanitize a domain name so it is safe to use as a file name on disk.
|
||||
import urllib.parse
|
||||
return urllib.parse.quote(name, safe='')
|
||||
|
||||
def sort_domains(domain_names, env):
|
||||
# Put domain names in a nice sorted order. For web_update, PRIMARY_HOSTNAME
|
||||
# must appear first so it becomes the nginx default server.
|
||||
# Put domain names in a nice sorted order.
|
||||
|
||||
# First group PRIMARY_HOSTNAME and its subdomains, then parent domains of PRIMARY_HOSTNAME, then other domains.
|
||||
groups = ( [], [], [] )
|
||||
for d in domain_names:
|
||||
if d == env['PRIMARY_HOSTNAME'] or d.endswith("." + env['PRIMARY_HOSTNAME']):
|
||||
groups[0].append(d)
|
||||
elif env['PRIMARY_HOSTNAME'].endswith("." + d):
|
||||
groups[1].append(d)
|
||||
# The nice order will group domain names by DNS zone, i.e. the top-most
|
||||
# domain name that we serve that ecompasses a set of subdomains. Map
|
||||
# each of the domain names to the zone that contains them. Walk the domains
|
||||
# from shortest to longest since zones are always shorter than their
|
||||
# subdomains.
|
||||
zones = { }
|
||||
for domain in sorted(domain_names, key=lambda d : len(d)):
|
||||
for z in zones.values():
|
||||
if domain.endswith("." + z):
|
||||
# We found a parent domain already in the list.
|
||||
zones[domain] = z
|
||||
break
|
||||
else:
|
||||
groups[2].append(d)
|
||||
# 'break' did not occur: there is no parent domain, so it is its
|
||||
# own zone.
|
||||
zones[domain] = domain
|
||||
|
||||
# Within each group, sort parent domains before subdomains and after that sort lexicographically.
|
||||
def sort_group(group):
|
||||
# Find the top-most domains.
|
||||
top_domains = sorted(d for d in group if len([s for s in group if d.endswith("." + s)]) == 0)
|
||||
ret = []
|
||||
for d in top_domains:
|
||||
ret.append(d)
|
||||
ret.extend( sort_group([s for s in group if s.endswith("." + d)]) )
|
||||
return ret
|
||||
# Sort the zones.
|
||||
zone_domains = sorted(zones.values(),
|
||||
key = lambda d : (
|
||||
# PRIMARY_HOSTNAME or the zone that contains it is always first.
|
||||
not (d == env['PRIMARY_HOSTNAME'] or env['PRIMARY_HOSTNAME'].endswith("." + d)),
|
||||
|
||||
groups = [sort_group(g) for g in groups]
|
||||
# Then just dumb lexicographically.
|
||||
d,
|
||||
))
|
||||
|
||||
return groups[0] + groups[1] + groups[2]
|
||||
# Now sort the domain names that fall within each zone.
|
||||
domain_names = sorted(domain_names,
|
||||
key = lambda d : (
|
||||
# First by zone.
|
||||
zone_domains.index(zones[d]),
|
||||
|
||||
# PRIMARY_HOSTNAME is always first within the zone that contains it.
|
||||
d != env['PRIMARY_HOSTNAME'],
|
||||
|
||||
# Followed by any of its subdomains.
|
||||
not d.endswith("." + env['PRIMARY_HOSTNAME']),
|
||||
|
||||
# Then in right-to-left lexicographic order of the .-separated parts of the name.
|
||||
list(reversed(d.split("."))),
|
||||
))
|
||||
|
||||
return domain_names
|
||||
|
||||
def sort_email_addresses(email_addresses, env):
|
||||
email_addresses = set(email_addresses)
|
||||
@@ -62,76 +106,6 @@ def sort_email_addresses(email_addresses, env):
|
||||
ret.extend(sorted(email_addresses)) # whatever is left
|
||||
return ret
|
||||
|
||||
def exclusive_process(name):
|
||||
# Ensure that a process named `name` does not execute multiple
|
||||
# times concurrently.
|
||||
import os, sys, atexit
|
||||
pidfile = '/var/run/mailinabox-%s.pid' % name
|
||||
mypid = os.getpid()
|
||||
|
||||
# Attempt to get a lock on ourself so that the concurrency check
|
||||
# itself is not executed in parallel.
|
||||
with open(__file__, 'r+') as flock:
|
||||
# Try to get a lock. This blocks until a lock is acquired. The
|
||||
# lock is held until the flock file is closed at the end of the
|
||||
# with block.
|
||||
os.lockf(flock.fileno(), os.F_LOCK, 0)
|
||||
|
||||
# While we have a lock, look at the pid file. First attempt
|
||||
# to write our pid to a pidfile if no file already exists there.
|
||||
try:
|
||||
with open(pidfile, 'x') as f:
|
||||
# Successfully opened a new file. Since the file is new
|
||||
# there is no concurrent process. Write our pid.
|
||||
f.write(str(mypid))
|
||||
atexit.register(clear_my_pid, pidfile)
|
||||
return
|
||||
except FileExistsError:
|
||||
# The pid file already exixts, but it may contain a stale
|
||||
# pid of a terminated process.
|
||||
with open(pidfile, 'r+') as f:
|
||||
# Read the pid in the file.
|
||||
existing_pid = None
|
||||
try:
|
||||
existing_pid = int(f.read().strip())
|
||||
except ValueError:
|
||||
pass # No valid integer in the file.
|
||||
|
||||
# Check if the pid in it is valid.
|
||||
if existing_pid:
|
||||
if is_pid_valid(existing_pid):
|
||||
print("Another %s is already running (pid %d)." % (name, existing_pid), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Write our pid.
|
||||
f.seek(0)
|
||||
f.write(str(mypid))
|
||||
f.truncate()
|
||||
atexit.register(clear_my_pid, pidfile)
|
||||
|
||||
|
||||
def clear_my_pid(pidfile):
|
||||
import os
|
||||
os.unlink(pidfile)
|
||||
|
||||
|
||||
def is_pid_valid(pid):
|
||||
"""Checks whether a pid is a valid process ID of a currently running process."""
|
||||
# adapted from http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
|
||||
import os, errno
|
||||
if pid <= 0: raise ValueError('Invalid PID.')
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except OSError as err:
|
||||
if err.errno == errno.ESRCH: # No such process
|
||||
return False
|
||||
elif err.errno == errno.EPERM: # Not permitted to send signal
|
||||
return True
|
||||
else: # EINVAL
|
||||
raise
|
||||
else:
|
||||
return True
|
||||
|
||||
def shell(method, cmd_args, env={}, capture_stderr=False, return_bytes=False, trap=False, input=None):
|
||||
# A safe way to execute processes.
|
||||
# Some processes like apt-get require being given a sane PATH.
|
||||
@@ -184,3 +158,34 @@ def du(path):
|
||||
seen.add(stat.st_ino)
|
||||
total_size += stat.st_size
|
||||
return total_size
|
||||
|
||||
def wait_for_service(port, public, env, timeout):
|
||||
# Block until a service on a given port (bound privately or publicly)
|
||||
# is taking connections, with a maximum timeout.
|
||||
import socket, time
|
||||
start = time.perf_counter()
|
||||
while True:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.settimeout(timeout/3)
|
||||
try:
|
||||
s.connect(("127.0.0.1" if not public else env['PUBLIC_IP'], port))
|
||||
return True
|
||||
except OSError:
|
||||
if time.perf_counter() > start+timeout:
|
||||
return False
|
||||
time.sleep(min(timeout/4, 1))
|
||||
|
||||
def fix_boto():
|
||||
# Google Compute Engine instances install some Python-2-only boto plugins that
|
||||
# conflict with boto running under Python 3. Disable boto's default configuration
|
||||
# file prior to importing boto so that GCE's plugin is not loaded:
|
||||
import os
|
||||
os.environ["BOTO_CONFIG"] = "/etc/boto3.cfg"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from web_update import get_web_domains
|
||||
env = load_environment()
|
||||
domains = get_web_domains(env)
|
||||
for domain in domains:
|
||||
print(domain)
|
||||
|
||||
@@ -2,51 +2,103 @@
|
||||
# domains for which a mail account has been set up.
|
||||
########################################################################
|
||||
|
||||
import os, os.path, shutil, re, rtyaml
|
||||
import os.path, re, rtyaml
|
||||
|
||||
from mailconfig import get_mail_domains
|
||||
from dns_update import get_custom_dns_config, do_dns_update
|
||||
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 utils import shell, safe_domain_name, sort_domains
|
||||
|
||||
def get_web_domains(env):
|
||||
# What domains should we serve websites for?
|
||||
def get_web_domains(env, include_www_redirects=True, exclude_dns_elsewhere=True):
|
||||
# What domains should we serve HTTP(S) for?
|
||||
domains = set()
|
||||
|
||||
# At the least it's the PRIMARY_HOSTNAME so we can serve webmail
|
||||
# as well as Z-Push for Exchange ActiveSync.
|
||||
domains.add(env['PRIMARY_HOSTNAME'])
|
||||
|
||||
# Also serve web for all mail domains so that we might at least
|
||||
# provide Webfinger and ActiveSync auto-discover of email settings
|
||||
# (though the latter isn't really working). These will require that
|
||||
# an SSL cert be installed.
|
||||
# Serve web for all mail domains so that we might at least
|
||||
# provide auto-discover of email settings, and also a static website
|
||||
# if the user wants to make one.
|
||||
domains |= get_mail_domains(env)
|
||||
|
||||
if include_www_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.
|
||||
# the topmost of each domain we serve.
|
||||
domains |= set('www.' + zone for zone, zonefile in get_dns_zones(env))
|
||||
|
||||
if exclude_dns_elsewhere:
|
||||
# ...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.
|
||||
dns = get_custom_dns_config(env)
|
||||
for domain, value in dns.items():
|
||||
if domain not in domains: continue
|
||||
if (isinstance(value, str) and (value != "local")) \
|
||||
or (isinstance(value, dict) and ("A" in value) and (value["A"] != "local")) \
|
||||
or (isinstance(value, dict) and ("AAAA" in value) and (value["AAAA"] != "local")):
|
||||
domains.remove(domain)
|
||||
domains -= get_domains_with_a_records(env)
|
||||
|
||||
# Sort the list. Put PRIMARY_HOSTNAME first so it becomes the
|
||||
# default server (nginx's default_server).
|
||||
# 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
|
||||
# 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.
|
||||
domains.add(env['PRIMARY_HOSTNAME'])
|
||||
|
||||
# Sort the list so the nginx conf gets written in a stable order.
|
||||
domains = sort_domains(domains, env)
|
||||
|
||||
return domains
|
||||
|
||||
def do_web_update(env, ok_status="web updated\n"):
|
||||
def get_domains_with_a_records(env):
|
||||
domains = set()
|
||||
dns = get_custom_dns_config(env)
|
||||
for domain, rtype, value in dns:
|
||||
if rtype == "CNAME" or (rtype in ("A", "AAAA") and value not in ("local", env['PUBLIC_IP'])):
|
||||
domains.add(domain)
|
||||
return domains
|
||||
|
||||
def get_web_domains_with_root_overrides(env):
|
||||
# Load custom settings so we can tell what domains have a redirect or proxy set up on '/',
|
||||
# which means static hosting is not happening.
|
||||
root_overrides = { }
|
||||
nginx_conf_custom_fn = os.path.join(env["STORAGE_ROOT"], "www/custom.yaml")
|
||||
if os.path.exists(nginx_conf_custom_fn):
|
||||
custom_settings = rtyaml.load(open(nginx_conf_custom_fn))
|
||||
for domain, settings in custom_settings.items():
|
||||
for type, value in [('redirect', settings.get('redirects', {}).get('/')),
|
||||
('proxy', settings.get('proxies', {}).get('/'))]:
|
||||
if value:
|
||||
root_overrides[domain] = (type, value)
|
||||
return root_overrides
|
||||
|
||||
def do_web_update(env):
|
||||
# Pre-load what SSL certificates we will use for each domain.
|
||||
ssl_certificates = get_ssl_certificates(env)
|
||||
|
||||
# Build an nginx configuration file.
|
||||
nginx_conf = open(os.path.join(os.path.dirname(__file__), "../conf/nginx-top.conf")).read()
|
||||
|
||||
# Add configuration for each web domain.
|
||||
template1 = open(os.path.join(os.path.dirname(__file__), "../conf/nginx.conf")).read()
|
||||
# Load the templates.
|
||||
template0 = open(os.path.join(os.path.dirname(__file__), "../conf/nginx.conf")).read()
|
||||
template1 = open(os.path.join(os.path.dirname(__file__), "../conf/nginx-alldomains.conf")).read()
|
||||
template2 = open(os.path.join(os.path.dirname(__file__), "../conf/nginx-primaryonly.conf")).read()
|
||||
template3 = "\trewrite ^(.*) https://$REDIRECT_DOMAIN$1 permanent;\n"
|
||||
|
||||
# Add the PRIMARY_HOST configuration first so it becomes nginx's default server.
|
||||
nginx_conf += make_domain_config(env['PRIMARY_HOSTNAME'], [template0, template1, template2], ssl_certificates, env)
|
||||
|
||||
# Add configuration all other web domains.
|
||||
has_root_proxy_or_redirect = get_web_domains_with_root_overrides(env)
|
||||
web_domains_not_redirect = get_web_domains(env, include_www_redirects=False)
|
||||
for domain in get_web_domains(env):
|
||||
nginx_conf += make_domain_config(domain, template1, template2, env)
|
||||
if domain == env['PRIMARY_HOSTNAME']:
|
||||
# PRIMARY_HOSTNAME is handled above.
|
||||
continue
|
||||
if domain in web_domains_not_redirect:
|
||||
# This is a regular domain.
|
||||
if domain not in has_root_proxy_or_redirect:
|
||||
nginx_conf += make_domain_config(domain, [template0, template1], ssl_certificates, env)
|
||||
else:
|
||||
nginx_conf += make_domain_config(domain, [template0], ssl_certificates, env)
|
||||
else:
|
||||
# Add default 'www.' redirect.
|
||||
nginx_conf += make_domain_config(domain, [template0, template3], ssl_certificates, env)
|
||||
|
||||
# Did the file change? If not, don't bother writing & restarting nginx.
|
||||
nginx_conf_fn = "/etc/nginx/conf.d/local.conf"
|
||||
@@ -65,34 +117,20 @@ def do_web_update(env, ok_status="web updated\n"):
|
||||
# enough and doesn't break any open connections.
|
||||
shell('check_call', ["/usr/sbin/service", "nginx", "reload"])
|
||||
|
||||
return ok_status
|
||||
return "web updated\n"
|
||||
|
||||
def make_domain_config(domain, template, template_for_primaryhost, env):
|
||||
# How will we configure this domain.
|
||||
def make_domain_config(domain, templates, ssl_certificates, env):
|
||||
# GET SOME VARIABLES
|
||||
|
||||
# Where will its root directory be for static files?
|
||||
|
||||
root = get_web_root(domain, env)
|
||||
|
||||
# What private key and SSL certificate will we use for this domain?
|
||||
ssl_key, ssl_certificate, csr_path = get_domain_ssl_files(domain, env)
|
||||
tls_cert = get_domain_ssl_files(domain, ssl_certificates, env)
|
||||
|
||||
# For hostnames created after the initial setup, ensure we have an SSL certificate
|
||||
# available. Make a self-signed one now if one doesn't exist.
|
||||
ensure_ssl_certificate_exists(domain, ssl_key, ssl_certificate, csr_path, env)
|
||||
# ADDITIONAL DIRECTIVES.
|
||||
|
||||
# Put pieces together.
|
||||
nginx_conf_parts = re.split("\s*# ADDITIONAL DIRECTIVES HERE\s*", template)
|
||||
nginx_conf = nginx_conf_parts[0] + "\n"
|
||||
if domain == env['PRIMARY_HOSTNAME']:
|
||||
nginx_conf += template_for_primaryhost + "\n"
|
||||
|
||||
# Replace substitution strings in the template & return.
|
||||
nginx_conf = nginx_conf.replace("$STORAGE_ROOT", env['STORAGE_ROOT'])
|
||||
nginx_conf = nginx_conf.replace("$HOSTNAME", domain)
|
||||
nginx_conf = nginx_conf.replace("$ROOT", root)
|
||||
nginx_conf = nginx_conf.replace("$SSL_KEY", ssl_key)
|
||||
nginx_conf = nginx_conf.replace("$SSL_CERTIFICATE", ssl_certificate)
|
||||
nginx_conf_extra = ""
|
||||
|
||||
# Because the certificate may change, we should recognize this so we
|
||||
# can trigger an nginx update.
|
||||
@@ -105,26 +143,53 @@ def make_domain_config(domain, template, template_for_primaryhost, env):
|
||||
finally:
|
||||
f.close()
|
||||
return sha1.hexdigest()
|
||||
nginx_conf += "# ssl files sha1: %s / %s\n" % (hashfile(ssl_key), hashfile(ssl_certificate))
|
||||
nginx_conf_extra += "# ssl files sha1: %s / %s\n" % (hashfile(tls_cert["private-key"]), hashfile(tls_cert["certificate"]))
|
||||
|
||||
# Add in any user customizations in YAML format.
|
||||
hsts = "yes"
|
||||
nginx_conf_custom_fn = os.path.join(env["STORAGE_ROOT"], "www/custom.yaml")
|
||||
if os.path.exists(nginx_conf_custom_fn):
|
||||
yaml = rtyaml.load(open(nginx_conf_custom_fn))
|
||||
if domain in yaml:
|
||||
yaml = yaml[domain]
|
||||
|
||||
# any proxy or redirect here?
|
||||
for path, url in yaml.get("proxies", {}).items():
|
||||
nginx_conf += "\tlocation %s {\n\t\tproxy_pass %s;\n\t}\n" % (path, url)
|
||||
nginx_conf_extra += "\tlocation %s {" % path
|
||||
nginx_conf_extra += "\n\t\tproxy_pass %s;" % url
|
||||
nginx_conf_extra += "\n\t\tproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;"
|
||||
nginx_conf_extra += "\n\t}\n"
|
||||
for path, url in yaml.get("redirects", {}).items():
|
||||
nginx_conf += "\trewrite %s %s permanent;\n" % (path, url)
|
||||
nginx_conf_extra += "\trewrite %s %s permanent;\n" % (path, url)
|
||||
|
||||
# override the HSTS directive type
|
||||
hsts = yaml.get("hsts", hsts)
|
||||
|
||||
# Add the HSTS header.
|
||||
if hsts == "yes":
|
||||
nginx_conf_extra += "add_header Strict-Transport-Security max-age=15768000;\n"
|
||||
elif hsts == "preload":
|
||||
nginx_conf_extra += "add_header Strict-Transport-Security \"max-age=15768000; includeSubDomains; preload\";\n"
|
||||
|
||||
# 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")
|
||||
if os.path.exists(nginx_conf_custom_include):
|
||||
nginx_conf += "\tinclude %s;\n" % (nginx_conf_custom_include)
|
||||
nginx_conf_extra += "\tinclude %s;\n" % (nginx_conf_custom_include)
|
||||
# PUT IT ALL TOGETHER
|
||||
|
||||
# Ending.
|
||||
nginx_conf += nginx_conf_parts[1]
|
||||
# Combine the pieces. Iteratively place each template into the "# ADDITIONAL DIRECTIVES HERE" placeholder
|
||||
# of the previous template.
|
||||
nginx_conf = "# ADDITIONAL DIRECTIVES HERE\n"
|
||||
for t in templates + [nginx_conf_extra]:
|
||||
nginx_conf = re.sub("[ \t]*# ADDITIONAL DIRECTIVES HERE *\n", t, nginx_conf)
|
||||
|
||||
# Replace substitution strings in the template & return.
|
||||
nginx_conf = nginx_conf.replace("$STORAGE_ROOT", env['STORAGE_ROOT'])
|
||||
nginx_conf = nginx_conf.replace("$HOSTNAME", domain)
|
||||
nginx_conf = nginx_conf.replace("$ROOT", root)
|
||||
nginx_conf = nginx_conf.replace("$SSL_KEY", tls_cert["private-key"])
|
||||
nginx_conf = nginx_conf.replace("$SSL_CERTIFICATE", tls_cert["certificate"])
|
||||
nginx_conf = nginx_conf.replace("$REDIRECT_DOMAIN", re.sub(r"^www\.", "", domain)) # for default www redirects to parent domain
|
||||
|
||||
return nginx_conf
|
||||
|
||||
@@ -135,139 +200,21 @@ def get_web_root(domain, env, test_exists=True):
|
||||
if os.path.exists(root) or not test_exists: break
|
||||
return root
|
||||
|
||||
def get_domain_ssl_files(domain, env, allow_shared_cert=True):
|
||||
# What SSL private key will we use? Allow the user to override this, but
|
||||
# in many cases using the same private key for all domains would be fine.
|
||||
# Don't allow the user to override the key for PRIMARY_HOSTNAME because
|
||||
# that's what's in the main file.
|
||||
ssl_key = os.path.join(env["STORAGE_ROOT"], 'ssl/ssl_private_key.pem')
|
||||
ssl_key_is_alt = False
|
||||
alt_key = os.path.join(env["STORAGE_ROOT"], 'ssl/%s/private_key.pem' % safe_domain_name(domain))
|
||||
if domain != env['PRIMARY_HOSTNAME'] and os.path.exists(alt_key):
|
||||
ssl_key = alt_key
|
||||
ssl_key_is_alt = True
|
||||
|
||||
# What SSL certificate will we use?
|
||||
ssl_certificate_primary = os.path.join(env["STORAGE_ROOT"], 'ssl/ssl_certificate.pem')
|
||||
if domain == env['PRIMARY_HOSTNAME']:
|
||||
# For PRIMARY_HOSTNAME, use the one we generated at set-up time.
|
||||
ssl_certificate = ssl_certificate_primary
|
||||
else:
|
||||
# For other domains, we'll probably use a certificate in a different path.
|
||||
ssl_certificate = os.path.join(env["STORAGE_ROOT"], 'ssl/%s/ssl_certificate.pem' % safe_domain_name(domain))
|
||||
|
||||
# But we can be smart and reuse the main SSL certificate if is has
|
||||
# a Subject Alternative Name matching this domain. Don't do this if
|
||||
# the user has uploaded a different private key for this domain.
|
||||
if not ssl_key_is_alt and allow_shared_cert:
|
||||
from status_checks import check_certificate
|
||||
if check_certificate(domain, ssl_certificate_primary, None)[0] == "OK":
|
||||
ssl_certificate = ssl_certificate_primary
|
||||
|
||||
# Where would the CSR go? As with the SSL cert itself, the CSR must be
|
||||
# different for each domain name.
|
||||
if domain == env['PRIMARY_HOSTNAME']:
|
||||
csr_path = os.path.join(env["STORAGE_ROOT"], 'ssl/ssl_cert_sign_req.csr')
|
||||
else:
|
||||
csr_path = os.path.join(env["STORAGE_ROOT"], 'ssl/%s/certificate_signing_request.csr' % safe_domain_name(domain))
|
||||
|
||||
return ssl_key, ssl_certificate, csr_path
|
||||
|
||||
def ensure_ssl_certificate_exists(domain, ssl_key, ssl_certificate, csr_path, env):
|
||||
# For domains besides PRIMARY_HOSTNAME, generate a self-signed certificate if
|
||||
# a certificate doesn't already exist. See setup/mail.sh for documentation.
|
||||
|
||||
if domain == env['PRIMARY_HOSTNAME']:
|
||||
return
|
||||
|
||||
# Sanity check. Shouldn't happen. A non-primary domain might use this
|
||||
# certificate (see above), but then the certificate should exist anyway.
|
||||
if ssl_certificate == os.path.join(env["STORAGE_ROOT"], 'ssl/ssl_certificate.pem'):
|
||||
return
|
||||
|
||||
if os.path.exists(ssl_certificate):
|
||||
return
|
||||
|
||||
os.makedirs(os.path.dirname(ssl_certificate), exist_ok=True)
|
||||
|
||||
# Generate a new self-signed certificate using the same private key that we already have.
|
||||
|
||||
# Start with a CSR.
|
||||
with open(csr_path, "w") as f:
|
||||
f.write(create_csr(domain, ssl_key, env))
|
||||
|
||||
# And then make the certificate.
|
||||
shell("check_call", [
|
||||
"openssl", "x509", "-req",
|
||||
"-days", "365",
|
||||
"-in", csr_path,
|
||||
"-signkey", ssl_key,
|
||||
"-out", ssl_certificate])
|
||||
|
||||
def create_csr(domain, ssl_key, env):
|
||||
return shell("check_output", [
|
||||
"openssl", "req", "-new",
|
||||
"-key", ssl_key,
|
||||
"-out", "/dev/stdout",
|
||||
"-sha256",
|
||||
"-subj", "/C=%s/ST=/L=/O=/CN=%s" % (env["CSR_COUNTRY"], domain)])
|
||||
|
||||
def install_cert(domain, ssl_cert, ssl_chain, env):
|
||||
if domain not in get_web_domains(env):
|
||||
return "Invalid domain name."
|
||||
|
||||
# Write the combined cert+chain to a temporary path and validate that it is OK.
|
||||
# The certificate always goes above the chain.
|
||||
import tempfile, os
|
||||
fd, fn = tempfile.mkstemp('.pem')
|
||||
os.write(fd, (ssl_cert + '\n' + ssl_chain).encode("ascii"))
|
||||
os.close(fd)
|
||||
|
||||
# Do validation on the certificate before installing it.
|
||||
from status_checks import check_certificate
|
||||
ssl_key, ssl_certificate, ssl_csr_path = get_domain_ssl_files(domain, env, allow_shared_cert=False)
|
||||
cert_status, cert_status_details = check_certificate(domain, fn, ssl_key)
|
||||
if cert_status != "OK":
|
||||
if cert_status == "SELF-SIGNED":
|
||||
cert_status = "This is a self-signed certificate. I can't install that."
|
||||
os.unlink(fn)
|
||||
if cert_status_details is not None:
|
||||
cert_status += " " + cert_status_details
|
||||
return cert_status
|
||||
|
||||
# Copy the certificate to its expected location.
|
||||
os.makedirs(os.path.dirname(ssl_certificate), exist_ok=True)
|
||||
shutil.move(fn, ssl_certificate)
|
||||
|
||||
ret = []
|
||||
|
||||
# When updating the cert for PRIMARY_HOSTNAME, also update DNS because it is
|
||||
# used in the DANE TLSA record and restart postfix and dovecot which use
|
||||
# that certificate.
|
||||
if domain == env['PRIMARY_HOSTNAME']:
|
||||
ret.append( do_dns_update(env) )
|
||||
|
||||
shell('check_call', ["/usr/sbin/service", "postfix", "restart"])
|
||||
shell('check_call', ["/usr/sbin/service", "dovecot", "restart"])
|
||||
ret.append("mail services restarted")
|
||||
|
||||
# Kick nginx so it sees the cert.
|
||||
ret.append( do_web_update(env, ok_status="") )
|
||||
return "\n".join(r for r in ret if r.strip() != "")
|
||||
|
||||
def get_web_domains_info(env):
|
||||
www_redirects = set(get_web_domains(env)) - set(get_web_domains(env, include_www_redirects=False))
|
||||
has_root_proxy_or_redirect = set(get_web_domains_with_root_overrides(env))
|
||||
ssl_certificates = get_ssl_certificates(env)
|
||||
|
||||
# for the SSL config panel, get cert status
|
||||
def check_cert(domain):
|
||||
from status_checks import check_certificate
|
||||
ssl_key, ssl_certificate, ssl_csr_path = get_domain_ssl_files(domain, env)
|
||||
if not os.path.exists(ssl_certificate):
|
||||
return ("danger", "No Certificate Installed")
|
||||
cert_status, cert_status_details = check_certificate(domain, ssl_certificate, ssl_key)
|
||||
try:
|
||||
tls_cert = get_domain_ssl_files(domain, ssl_certificates, env, allow_missing_cert=True)
|
||||
except OSError: # PRIMARY_HOSTNAME cert is missing
|
||||
tls_cert = None
|
||||
if tls_cert is None: return ("danger", "No certificate installed.")
|
||||
cert_status, cert_status_details = check_certificate(domain, tls_cert["certificate"], tls_cert["private-key"])
|
||||
if cert_status == "OK":
|
||||
if domain == env['PRIMARY_HOSTNAME'] or ssl_certificate != get_domain_ssl_files(env['PRIMARY_HOSTNAME'], env)[1]:
|
||||
return ("success", "Signed & valid. " + cert_status_details)
|
||||
else:
|
||||
# This is an alternate domain but using the same cert as the primary domain.
|
||||
return ("success", "Signed & valid. Using multi/wildcard certificate of %s." % env['PRIMARY_HOSTNAME'])
|
||||
elif cert_status == "SELF-SIGNED":
|
||||
return ("warning", "Self-signed. Get a signed certificate to stop warnings.")
|
||||
else:
|
||||
@@ -279,6 +226,7 @@ def get_web_domains_info(env):
|
||||
"root": get_web_root(domain, env),
|
||||
"custom_root": get_web_root(domain, env, test_exists=False),
|
||||
"ssl_certificate": check_cert(domain),
|
||||
"static_enabled": domain not in (www_redirects | has_root_proxy_or_redirect),
|
||||
}
|
||||
for domain in get_web_domains(env)
|
||||
]
|
||||
|
||||
115
security.md
Normal file
115
security.md
Normal file
@@ -0,0 +1,115 @@
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Threat Model
|
||||
------------
|
||||
|
||||
Nothing is perfectly secure, and an adversary with sufficient resources can always penetrate a system.
|
||||
|
||||
The primary goal of Mail-in-a-Box is to make deploying a good mail server easy, so we balance ― as everyone does ― privacy and security concerns with the practicality of actually deploying the system. That means we make certain assumptions about adversaries. We assume that adversaries . . .
|
||||
|
||||
* Do not have physical access to the box (i.e., we do not aim to protect the box from physical access).
|
||||
* Have not been given Unix accounts on the box (i.e., we assume all users with shell access are trusted).
|
||||
|
||||
On the other hand, we do assume that adversaries are performing passive surveillance and, possibly, active man-in-the-middle attacks. And so:
|
||||
|
||||
* User credentials are always sent through SSH/TLS, never in the clear, with modern TLS settings.
|
||||
* Outbound mail is sent with the highest level of TLS possible.
|
||||
* The box advertises its support for [DANE TLSA](https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities), when DNSSEC is enabled at the domain name registrar, so that inbound mail is more likely to be transmitted securely.
|
||||
|
||||
Additional details follow.
|
||||
|
||||
User Credentials
|
||||
----------------
|
||||
|
||||
The box's administrator and its (non-administrative) mail users must sometimes communicate their credentials to the box.
|
||||
|
||||
### Services behind TLS
|
||||
|
||||
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.
|
||||
* 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.
|
||||
|
||||
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))
|
||||
* Only TLSv1, TLSv1.1 and 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).
|
||||
* 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:
|
||||
|
||||
* 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))
|
||||
* 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
|
||||
|
||||
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))
|
||||
|
||||
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 (e.g. via SSH) is configured by the system image used to create the box, typically from by a cloud virtual machine provider (e.g. Digital Ocean). Mail-in-a-Box does not set any console access settings, although it will warn the administrator in the System Status Checks if password-based login is turned on.
|
||||
|
||||
The [setup guide video](https://mailinabox.email/) explains how to verify the host key fingerprint on first login.
|
||||
|
||||
If DNSSEC is enabled at the box's domain name's registrar, the SSHFP record that the box automatically puts into DNS can also be used to verify the host key fingerprint by setting `VerifyHostKeyDNS yes` in your `ssh/.config` file or by logging in with `ssh -o VerifyHostKeyDNS=yes`. ([source](management/dns_update.py))
|
||||
|
||||
### Brute-force attack mitigation
|
||||
|
||||
`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).
|
||||
|
||||
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
|
||||
-------------
|
||||
|
||||
The basic protocols of email delivery did not plan for the presence of adversaries on the network. For a number of reasons it is not possible in most cases to guarantee that a connection to a recipient server is secure.
|
||||
|
||||
### DNSSEC
|
||||
|
||||
The first step in resolving the destination server for an email address is performing a DNS look-up for the MX record of the domain name. The box uses a locally-running [DNSSEC](https://en.wikipedia.org/wiki/DNSSEC)-aware nameserver to perform the lookup. If the domain name has DNSSEC enabled, DNSSEC guards against DNS records being tampered with.
|
||||
|
||||
### Encryption
|
||||
|
||||
The box (along with the vast majority of mail servers) uses [opportunistic encryption](https://en.wikipedia.org/wiki/Opportunistic_encryption), meaning the mail is encrypted in transit and protected from passive eavesdropping, but it is not protected from an active man-in-the-middle attack. Modern encryption settings (TLSv1 and later, no RC4) will be used to the extent the recipient server supports them. ([source](setup/mail-postfix.sh))
|
||||
|
||||
### DANE
|
||||
|
||||
If the recipient's domain name supports DNSSEC and has published a [DANE TLSA](https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities) record, then on-the-wire encryption is forced between the box and the recipient MTA and this encryption is not subject to a man-in-the-middle attack. The TLSA record contains a certificate fingerprint which the receiving MTA (server) must present to the box. ([source](setup/mail-postfix.sh))
|
||||
|
||||
### Domain Policy Records
|
||||
|
||||
Domain policy records allow recipient MTAs to detect when the _domain_ part of of the sender address in incoming mail has been spoofed. All outbound mail is signed with [DKIM](https://en.wikipedia.org/wiki/DomainKeys_Identified_Mail) and "quarantine" [DMARC](https://en.wikipedia.org/wiki/DMARC) records are automatically set in DNS. Receiving MTAs that implement DMARC will automatically quarantine mail that is "From:" a domain hosted by the box but which was not sent by the box. (Strong [SPF](https://en.wikipedia.org/wiki/Sender_Policy_Framework) records are also automatically set in DNS.) ([source](management/dns_update.py))
|
||||
|
||||
### 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.
|
||||
|
||||
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
|
||||
-------------
|
||||
|
||||
### Encryption
|
||||
|
||||
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))
|
||||
|
||||
### DANE
|
||||
|
||||
When DNSSEC is enabled at the box's domain name's registrar, [DANE TLSA](https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities) records are automatically published in DNS. Senders supporting DANE will enforce encryption on-the-wire between them and the box --- see the section on DANE for outgoing mail above. ([source](management/dns_update.py))
|
||||
|
||||
### Filters
|
||||
|
||||
Incoming mail is run through several filters. Email is bounced if the sender's IP address is listed in the [Spamhaus Zen blacklist](http://www.spamhaus.org/zen/) or if the sender's domain is listed in the [Spamhaus Domain Block List](http://www.spamhaus.org/dbl/). Greylisting (with [postgrey](http://postgrey.schweikert.ch/)) is also used to cut down on spam. ([source](setup/mail-postfix.sh))
|
||||
@@ -2,12 +2,41 @@
|
||||
#########################################################
|
||||
# This script is intended to be run like this:
|
||||
#
|
||||
# curl https://.../bootstrap.sh | sudo bash
|
||||
# curl https://mailinabox.email/setup.sh | sudo bash
|
||||
#
|
||||
#########################################################
|
||||
|
||||
if [ -z "$TAG" ]; then
|
||||
TAG=v0.06
|
||||
# If a version to install isn't explicitly given as an environment
|
||||
# variable, then install the latest version. But the latest version
|
||||
# depends on the operating system. Existing Ubuntu 14.04 users need
|
||||
# to be able to upgrade to the latest version supporting Ubuntu 14.04,
|
||||
# in part because an upgrade is required before jumping to Ubuntu 18.04.
|
||||
# New users on Ubuntu 18.04 need to get the latest version number too.
|
||||
#
|
||||
# Also, the system status checks read this script for TAG = (without the
|
||||
# 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
|
||||
# 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
|
||||
# This machine is running Ubuntu 18.04.
|
||||
TAG=v0.42
|
||||
|
||||
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.
|
||||
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 "stop now and switch to a machine running Ubuntu 18.04. If you are"
|
||||
echo "upgrading an existing Mail-in-a-Box --- great. After upgrading this"
|
||||
echo "box, please visit https://mailinabox.email for notes on how to upgrade"
|
||||
echo "to Ubuntu 18.04."
|
||||
echo ""
|
||||
TAG=v0.30
|
||||
|
||||
else
|
||||
echo "This script must be run on a system running Ubuntu 18.04 or Ubuntu 14.04."
|
||||
exit
|
||||
fi
|
||||
fi
|
||||
|
||||
# Are we running as root?
|
||||
@@ -18,9 +47,12 @@ fi
|
||||
|
||||
# Clone the Mail-in-a-Box repository if it doesn't exist.
|
||||
if [ ! -d $HOME/mailinabox ]; then
|
||||
if [ ! -f /usr/bin/git ]; then
|
||||
echo Installing git . . .
|
||||
apt-get -q -q update
|
||||
DEBIAN_FRONTEND=noninteractive apt-get -q -q install -y git < /dev/null
|
||||
echo
|
||||
fi
|
||||
|
||||
echo Downloading Mail-in-a-Box $TAG. . .
|
||||
git clone \
|
||||
|
||||
52
setup/dkim.sh
Normal file → Executable file
52
setup/dkim.sh
Normal file → Executable file
@@ -10,7 +10,8 @@ source setup/functions.sh # load our functions
|
||||
source /etc/mailinabox.conf # load global vars
|
||||
|
||||
# Install DKIM...
|
||||
apt_install opendkim opendkim-tools
|
||||
echo Installing OpenDKIM/OpenDMARC...
|
||||
apt_install opendkim opendkim-tools opendmarc
|
||||
|
||||
# Make sure configuration directories exist.
|
||||
mkdir -p /etc/opendkim;
|
||||
@@ -20,6 +21,11 @@ mkdir -p $STORAGE_ROOT/mail/dkim
|
||||
# Not quite sure why.
|
||||
echo "127.0.0.1" > /etc/opendkim/TrustedHosts
|
||||
|
||||
# We need to at least create these files, since we reference them later.
|
||||
# Otherwise, opendkim startup will fail
|
||||
touch /etc/opendkim/KeyTable
|
||||
touch /etc/opendkim/SigningTable
|
||||
|
||||
if grep -q "ExternalIgnoreList" /etc/opendkim.conf; then
|
||||
true # already done #NODOC
|
||||
else
|
||||
@@ -30,33 +36,55 @@ ExternalIgnoreList refile:/etc/opendkim/TrustedHosts
|
||||
InternalHosts refile:/etc/opendkim/TrustedHosts
|
||||
KeyTable refile:/etc/opendkim/KeyTable
|
||||
SigningTable refile:/etc/opendkim/SigningTable
|
||||
Socket inet:8891@localhost
|
||||
Socket inet:8891@127.0.0.1
|
||||
RequireSafeKeys false
|
||||
EOF
|
||||
fi
|
||||
|
||||
# Create a new DKIM key. This creates
|
||||
# mail.private and mail.txt in $STORAGE_ROOT/mail/dkim. The former
|
||||
# is the actual private key and the latter is the suggested DNS TXT
|
||||
# entry which we'll want to include in our DNS setup.
|
||||
# Create a new DKIM key. This creates mail.private and mail.txt
|
||||
# in $STORAGE_ROOT/mail/dkim. The former is the private key and
|
||||
# the latter is the suggested DNS TXT entry which we'll include
|
||||
# in our DNS setup. Note that the files are named after the
|
||||
# 'selector' of the key, which we can change later on to support
|
||||
# key rotation.
|
||||
#
|
||||
# A 1024-bit key is seen as a minimum standard by several providers
|
||||
# such as Google. But they and others use a 2048 bit key, so we'll
|
||||
# do the same. Keys beyond 2048 bits may exceed DNS record limits.
|
||||
if [ ! -f "$STORAGE_ROOT/mail/dkim/mail.private" ]; then
|
||||
# Should we specify -h rsa-sha256?
|
||||
opendkim-genkey -r -s mail -D $STORAGE_ROOT/mail/dkim
|
||||
opendkim-genkey -b 2048 -r -s mail -D $STORAGE_ROOT/mail/dkim
|
||||
fi
|
||||
|
||||
# Ensure files are owned by the opendkim user and are private otherwise.
|
||||
chown -R opendkim:opendkim $STORAGE_ROOT/mail/dkim
|
||||
chmod go-rwx $STORAGE_ROOT/mail/dkim
|
||||
|
||||
# Add OpenDKIM as a milter to postfix, which is how it intercepts outgoing
|
||||
# mail to perform the signing (by adding a mail header).
|
||||
# Be careful. If we add other milters later, it needs to be concatenated on the smtpd_milters line. #NODOC
|
||||
tools/editconf.py /etc/opendmarc.conf -s \
|
||||
"Syslog=true" \
|
||||
"Socket=inet:8893@[127.0.0.1]"
|
||||
|
||||
# Add OpenDKIM and OpenDMARC as milters to postfix, which is how OpenDKIM
|
||||
# intercepts outgoing mail to perform the signing (by adding a mail header)
|
||||
# and how they both intercept incoming mail to add Authentication-Results
|
||||
# headers. The order possibly/probably matters: OpenDMARC relies on the
|
||||
# OpenDKIM Authentication-Results header already being present.
|
||||
#
|
||||
# Be careful. If we add other milters later, this needs to be concatenated
|
||||
# on the smtpd_milters line.
|
||||
#
|
||||
# The OpenDMARC milter is skipped in the SMTP submission listener by
|
||||
# configuring smtpd_milters there to only list the OpenDKIM milter
|
||||
# (see mail-postfix.sh).
|
||||
tools/editconf.py /etc/postfix/main.cf \
|
||||
smtpd_milters=inet:127.0.0.1:8891 \
|
||||
"smtpd_milters=inet:127.0.0.1:8891 inet:127.0.0.1:8893"\
|
||||
non_smtpd_milters=\$smtpd_milters \
|
||||
milter_default_action=accept
|
||||
|
||||
# We need to explicitly enable the opendmarc service, or it will not start
|
||||
hide_output systemctl enable opendmarc
|
||||
|
||||
# Restart services.
|
||||
restart_service opendkim
|
||||
restart_service opendmarc
|
||||
restart_service postfix
|
||||
|
||||
|
||||
68
setup/dns.sh
68
setup/dns.sh
@@ -10,30 +10,60 @@
|
||||
source setup/functions.sh # load our functions
|
||||
source /etc/mailinabox.conf # load global vars
|
||||
|
||||
# Install `nsd`, our DNS server software, and `ldnsutils` which helps
|
||||
# us sign zones for DNSSEC.
|
||||
|
||||
# ...but first, we have to create the user because the
|
||||
# current Ubuntu forgets to do so in the .deb
|
||||
# (see issue #25 and https://bugs.launchpad.net/ubuntu/+source/nsd/+bug/1311886)
|
||||
if id nsd > /dev/null 2>&1; then
|
||||
true #echo "nsd user exists... good"; #NODOC
|
||||
else
|
||||
useradd nsd;
|
||||
fi
|
||||
|
||||
# Okay now install the packages.
|
||||
# Install the packages.
|
||||
#
|
||||
# * nsd: The non-recursive nameserver that publishes our DNS records.
|
||||
# * ldnsutils: Helper utilities for signing DNSSEC zones.
|
||||
# * openssh-client: Provides ssh-keyscan which we use to create SSHFP records.
|
||||
|
||||
echo "Installing nsd (DNS server)..."
|
||||
apt_install nsd ldnsutils openssh-client
|
||||
|
||||
# Prepare nsd's configuration.
|
||||
|
||||
mkdir -p /var/run/nsd
|
||||
|
||||
cat > /etc/nsd/nsd.conf << EOF;
|
||||
# Do not edit. Overwritten by Mail-in-a-Box setup.
|
||||
server:
|
||||
hide-version: yes
|
||||
logfile: "/var/log/nsd.log"
|
||||
|
||||
# identify the server (CH TXT ID.SERVER entry).
|
||||
identity: ""
|
||||
|
||||
# The directory for zonefile: files.
|
||||
zonesdir: "/etc/nsd/zones"
|
||||
|
||||
# Allows NSD to bind to IP addresses that are not (yet) added to the
|
||||
# network interface. This allows nsd to start even if the network stack
|
||||
# isn't fully ready, which apparently happens in some cases.
|
||||
# See https://www.nlnetlabs.nl/projects/nsd/nsd.conf.5.html.
|
||||
ip-transparent: yes
|
||||
|
||||
EOF
|
||||
|
||||
# Add log rotation
|
||||
cat > /etc/logrotate.d/nsd <<EOF;
|
||||
/var/log/nsd.log {
|
||||
weekly
|
||||
missingok
|
||||
rotate 12
|
||||
compress
|
||||
delaycompress
|
||||
notifempty
|
||||
}
|
||||
EOF
|
||||
|
||||
# Since we have bind9 listening on localhost for locally-generated
|
||||
# DNS queries that require a recursive nameserver, and the system
|
||||
# might have other network interfaces for e.g. tunnelling, we have
|
||||
# to be specific about the network interfaces that nsd binds to.
|
||||
for ip in $PRIVATE_IP $PRIVATE_IPV6; do
|
||||
echo " ip-address: $ip" >> /etc/nsd/nsd.conf;
|
||||
done
|
||||
|
||||
echo "include: /etc/nsd/zones.conf" >> /etc/nsd/nsd.conf;
|
||||
|
||||
# Create DNSSEC signing keys.
|
||||
|
||||
mkdir -p "$STORAGE_ROOT/dns/dnssec";
|
||||
@@ -61,7 +91,7 @@ FIRST=1 #NODOC
|
||||
for algo in RSASHA1-NSEC3-SHA1 RSASHA256; do
|
||||
if [ ! -f "$STORAGE_ROOT/dns/dnssec/$algo.conf" ]; then
|
||||
if [ $FIRST == 1 ]; then
|
||||
echo "Generating DNSSEC signing keys. This may take a few minutes..."
|
||||
echo "Generating DNSSEC signing keys..."
|
||||
FIRST=0 #NODOC
|
||||
fi
|
||||
|
||||
@@ -71,13 +101,17 @@ if [ ! -f "$STORAGE_ROOT/dns/dnssec/$algo.conf" ]; then
|
||||
#
|
||||
# `ldns-keygen` outputs the new key's filename to stdout, which
|
||||
# we're capturing into the `KSK` variable.
|
||||
KSK=$(umask 077; cd $STORAGE_ROOT/dns/dnssec; ldns-keygen -a $algo -b 2048 -k _domain_);
|
||||
#
|
||||
# ldns-keygen uses /dev/random for generating random numbers by default.
|
||||
# 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.
|
||||
KSK=$(umask 077; cd $STORAGE_ROOT/dns/dnssec; ldns-keygen -r /dev/urandom -a $algo -b 2048 -k _domain_);
|
||||
|
||||
# Now create a Zone-Signing Key (ZSK) which is expected to be
|
||||
# rotated more often than a KSK, although we have no plans to
|
||||
# rotate it (and doing so would be difficult to do without
|
||||
# disturbing DNS availability.) Omit `-k` and use a shorter key length.
|
||||
ZSK=$(umask 077; cd $STORAGE_ROOT/dns/dnssec; ldns-keygen -a $algo -b 1024 _domain_);
|
||||
ZSK=$(umask 077; cd $STORAGE_ROOT/dns/dnssec; ldns-keygen -r /dev/urandom -a $algo -b 1024 _domain_);
|
||||
|
||||
# These generate two sets of files like:
|
||||
#
|
||||
|
||||
@@ -4,9 +4,9 @@ if [ -z "`tools/mail.py user`" ]; then
|
||||
# aren't any yet, it'll be empty.
|
||||
|
||||
# If we didn't ask for an email address at the start, do so now.
|
||||
if [ -z "$EMAIL_ADDR" ]; then
|
||||
if [ -z "${EMAIL_ADDR:-}" ]; then
|
||||
# In an interactive shell, ask the user for an email address.
|
||||
if [ -z "$NONINTERACTIVE" ]; then
|
||||
if [ -z "${NONINTERACTIVE:-}" ]; then
|
||||
input_box "Mail Account" \
|
||||
"Let's create your first mail account.
|
||||
\n\nWhat email address do you want?" \
|
||||
@@ -35,7 +35,7 @@ if [ -z "`tools/mail.py user`" ]; then
|
||||
else
|
||||
# Use me@PRIMARY_HOSTNAME
|
||||
EMAIL_ADDR=me@$PRIMARY_HOSTNAME
|
||||
EMAIL_PW=1234
|
||||
EMAIL_PW=12345678
|
||||
echo
|
||||
echo "Creating a new administrative mail account for $EMAIL_ADDR with password $EMAIL_PW."
|
||||
echo
|
||||
@@ -47,11 +47,11 @@ if [ -z "`tools/mail.py user`" ]; then
|
||||
fi
|
||||
|
||||
# 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
|
||||
tools/mail.py user add $EMAIL_ADDR ${EMAIL_PW:-}
|
||||
|
||||
# Make it an admin.
|
||||
hide_output tools/mail.py user make-admin $EMAIL_ADDR
|
||||
|
||||
# Create an alias to which we'll direct all automatically-created administrative aliases.
|
||||
tools/mail.py alias add administrator@$PRIMARY_HOSTNAME $EMAIL_ADDR
|
||||
tools/mail.py alias add administrator@$PRIMARY_HOSTNAME $EMAIL_ADDR > /dev/null
|
||||
fi
|
||||
@@ -1,3 +1,9 @@
|
||||
# Turn on "strict mode." See http://redsymbol.net/articles/unofficial-bash-strict-mode/.
|
||||
# -e: exit if any command unexpectedly fails.
|
||||
# -u: exit if we have a variable typo.
|
||||
# -o pipefail: don't ignore errors in the non-last command in a pipeline
|
||||
set -euo pipefail
|
||||
|
||||
function hide_output {
|
||||
# This function hides the output of a command unless the command fails
|
||||
# and returns a non-zero exit code.
|
||||
@@ -5,59 +11,59 @@ function hide_output {
|
||||
# Get a temporary file.
|
||||
OUTPUT=$(tempfile)
|
||||
|
||||
# Execute command, redirecting stderr/stdout to the temporary file.
|
||||
# Execute command, redirecting stderr/stdout to the temporary file. Since we
|
||||
# check the return code ourselves, disable 'set -e' temporarily.
|
||||
set +e
|
||||
$@ &> $OUTPUT
|
||||
E=$?
|
||||
set -e
|
||||
|
||||
# If the command failed, show the output that was captured in the temporary file.
|
||||
if [ $? != 0 ]; then
|
||||
if [ $E != 0 ]; then
|
||||
# Something failed.
|
||||
echo
|
||||
echo FAILED: $@
|
||||
echo -----------------------------------------
|
||||
cat $OUTPUT
|
||||
echo -----------------------------------------
|
||||
exit $E
|
||||
fi
|
||||
|
||||
# Remove temporary file.
|
||||
rm -f $OUTPUT
|
||||
}
|
||||
|
||||
function apt_install {
|
||||
# Report any packages already installed.
|
||||
PACKAGES=$@
|
||||
TO_INSTALL=""
|
||||
ALREADY_INSTALLED=""
|
||||
for pkg in $PACKAGES; do
|
||||
if dpkg -s $pkg 2>/dev/null | grep "^Status: install ok installed" > /dev/null; then
|
||||
if [[ ! -z "$ALREADY_INSTALLED" ]]; then ALREADY_INSTALLED="$ALREADY_INSTALLED, "; fi
|
||||
ALREADY_INSTALLED="$ALREADY_INSTALLED$pkg (`dpkg -s $pkg | grep ^Version: | sed -e 's/.*: //'`)"
|
||||
else
|
||||
TO_INSTALL="$TO_INSTALL""$pkg "
|
||||
fi
|
||||
done
|
||||
|
||||
# List the packages already installed.
|
||||
if [[ ! -z "$ALREADY_INSTALLED" ]]; then
|
||||
echo already installed: $ALREADY_INSTALLED
|
||||
fi
|
||||
|
||||
# List the packages about to be installed.
|
||||
if [[ ! -z "$TO_INSTALL" ]]; then
|
||||
echo installing $TO_INSTALL...
|
||||
fi
|
||||
|
||||
# 'DEBIAN_FRONTEND=noninteractive' is to prevent dbconfig-common from asking you questions.
|
||||
function apt_get_quiet {
|
||||
# Run apt-get in a totally non-interactive mode.
|
||||
#
|
||||
# Somehow all of these options are needed to get it to not ask the user
|
||||
# questions about a) whether to proceed (-y), b) package options (noninteractive),
|
||||
# and c) what to do about files changed locally (we don't cause that to happen but
|
||||
# some VM providers muck with their images; -o).
|
||||
#
|
||||
# Although we could pass -qq to apt-get to make output quieter, many packages write to stdout
|
||||
# and stderr things that aren't really important. Use our hide_output function to capture
|
||||
# all of that and only show it if there is a problem (i.e. if apt_get returns a failure exit status).
|
||||
#
|
||||
# Also note that we still include the whole original package list in the apt-get command in
|
||||
# case it wants to upgrade anything, I guess? Maybe we can remove it. Doesn't normally make
|
||||
# a difference.
|
||||
DEBIAN_FRONTEND=noninteractive \
|
||||
hide_output \
|
||||
apt-get -y install $PACKAGES
|
||||
DEBIAN_FRONTEND=noninteractive hide_output apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confnew" "$@"
|
||||
}
|
||||
|
||||
function apt_install {
|
||||
# Install a bunch of packages. We used to report which packages were already
|
||||
# installed and which needed installing, before just running an 'apt-get
|
||||
# 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
|
||||
# not do that anymore.
|
||||
PACKAGES=$@
|
||||
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 {
|
||||
@@ -78,7 +84,7 @@ function get_publicip_from_web_service {
|
||||
#
|
||||
# Pass '4' or '6' as an argument to this function to specify
|
||||
# what type of address to get (IPv4, IPv6).
|
||||
curl -$1 --fail --silent --max-time 15 icanhazip.com 2>/dev/null
|
||||
curl -$1 --fail --silent --max-time 15 icanhazip.com 2>/dev/null || /bin/true
|
||||
}
|
||||
|
||||
function get_default_privateip {
|
||||
@@ -121,7 +127,7 @@ function get_default_privateip {
|
||||
if [ "$1" == "6" ]; then target=2001:4860:4860::8888; fi
|
||||
|
||||
# Get the route information.
|
||||
route=$(ip -$1 -o route get $target | grep -v unreachable)
|
||||
route=$(ip -$1 -o route get $target 2>/dev/null | grep -v unreachable)
|
||||
|
||||
# Parse the address out of the route information.
|
||||
address=$(echo $route | sed "s/.* src \([^ ]*\).*/\1/")
|
||||
@@ -134,11 +140,10 @@ function get_default_privateip {
|
||||
fi
|
||||
|
||||
echo $address
|
||||
|
||||
}
|
||||
|
||||
function ufw_allow {
|
||||
if [ -z "$DISABLE_FIREWALL" ]; then
|
||||
if [ -z "${DISABLE_FIREWALL:-}" ]; then
|
||||
# ufw has completely unhelpful output
|
||||
ufw allow $1 > /dev/null;
|
||||
fi
|
||||
@@ -157,10 +162,13 @@ function input_box {
|
||||
# input_box "title" "prompt" "defaultvalue" VARIABLE
|
||||
# The user's input will be stored in the variable VARIABLE.
|
||||
# The exit code from dialog will be stored in VARIABLE_EXITCODE.
|
||||
# Temporarily turn off 'set -e' because we need the dialog return code.
|
||||
declare -n result=$4
|
||||
declare -n result_code=$4_EXITCODE
|
||||
set +e
|
||||
result=$(dialog --stdout --title "$1" --inputbox "$2" 0 0 "$3")
|
||||
result_code=$?
|
||||
set -e
|
||||
}
|
||||
|
||||
function input_menu {
|
||||
@@ -170,6 +178,48 @@ function input_menu {
|
||||
declare -n result=$4
|
||||
declare -n result_code=$4_EXITCODE
|
||||
local IFS=^$'\n'
|
||||
set +e
|
||||
result=$(dialog --stdout --title "$1" --menu "$2" 0 0 0 $3)
|
||||
result_code=$?
|
||||
set -e
|
||||
}
|
||||
|
||||
function wget_verify {
|
||||
# Downloads a file from the web and checks that it matches
|
||||
# a provided hash. If the comparison fails, exit immediately.
|
||||
URL=$1
|
||||
HASH=$2
|
||||
DEST=$3
|
||||
CHECKSUM="$HASH $DEST"
|
||||
rm -f $DEST
|
||||
hide_output wget -O $DEST $URL
|
||||
if ! echo "$CHECKSUM" | sha1sum --check --strict > /dev/null; then
|
||||
echo "------------------------------------------------------------"
|
||||
echo "Download of $URL did not match expected checksum."
|
||||
echo "Found:"
|
||||
sha1sum $DEST
|
||||
echo
|
||||
echo "Expected:"
|
||||
echo "$CHECKSUM"
|
||||
rm -f $DEST
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
function git_clone {
|
||||
# Clones a git repository, checks out a particular commit or tag,
|
||||
# and moves the repository (or a subdirectory in it) to some path.
|
||||
# We use separate clone and checkout because -b only supports tags
|
||||
# and branches, but we sometimes want to reference a commit hash
|
||||
# directly when the repo doesn't provide a tag.
|
||||
REPO=$1
|
||||
TREEISH=$2
|
||||
SUBDIR=$3
|
||||
TARGETPATH=$4
|
||||
TMPPATH=/tmp/git-clone-$$
|
||||
rm -rf $TMPPATH $TARGETPATH
|
||||
git clone -q $REPO $TMPPATH || exit 1
|
||||
(cd $TMPPATH; git checkout -q $TREEISH;) || exit 1
|
||||
mv $TMPPATH/$SUBDIR $TARGETPATH
|
||||
rm -rf $TMPPATH
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Dovecot (IMAP and LDA)
|
||||
# Dovecot (IMAP/POP and LDA)
|
||||
# ----------------------
|
||||
#
|
||||
# Dovecot is *both* the IMAP server (the protocol that email applications
|
||||
# Dovecot is *both* the IMAP/POP server (the protocol that email applications
|
||||
# use to query a mailbox) as well as the local delivery agent (LDA),
|
||||
# meaning it is responsible for writing emails to mailbox storage on disk.
|
||||
# You could imagine why these things would be bundled together.
|
||||
@@ -18,13 +18,18 @@
|
||||
source setup/functions.sh # load our functions
|
||||
source /etc/mailinabox.conf # load global vars
|
||||
|
||||
# Install packages...
|
||||
|
||||
# Install packages for dovecot. These are all core dovecot plugins,
|
||||
# but dovecot-lucene is packaged by *us* in the Mail-in-a-Box PPA,
|
||||
# not by Ubuntu.
|
||||
|
||||
echo "Installing Dovecot (IMAP server)..."
|
||||
apt_install \
|
||||
dovecot-core dovecot-imapd dovecot-lmtpd dovecot-sqlite sqlite3 \
|
||||
dovecot-core dovecot-imapd dovecot-pop3d dovecot-lmtpd dovecot-sqlite sqlite3 \
|
||||
dovecot-sieve dovecot-managesieved
|
||||
|
||||
# The `dovecot-imapd` and `dovecot-lmtpd` packages automatically enable IMAP and LMTP protocols.
|
||||
# The `dovecot-imapd`, `dovecot-pop3d`, and `dovecot-lmtpd` packages automatically
|
||||
# enable IMAP, POP and LMTP protocols.
|
||||
|
||||
# Set basic daemon options.
|
||||
|
||||
@@ -32,8 +37,17 @@ apt_install \
|
||||
# of active IMAP connections (at, say, 5 open connections per user that
|
||||
# would be 20 users). Set it to 250 times the number of cores this
|
||||
# machine has, so on a two-core machine that's 500 processes/100 users).
|
||||
# The `default_vsz_limit` is the maximum amount of virtual memory that
|
||||
# can be allocated. It should be set *reasonably high* to avoid allocation
|
||||
# issues with larger mailboxes. We're setting it to 1/3 of the total
|
||||
# available memory (physical mem + swap) to be sure.
|
||||
# See here for discussion:
|
||||
# - https://www.dovecot.org/list/dovecot/2012-August/137569.html
|
||||
# - https://www.dovecot.org/list/dovecot/2011-December/132455.html
|
||||
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 \
|
||||
log_path=/var/log/mail.log
|
||||
|
||||
# The inotify `max_user_instances` default is 128, which constrains
|
||||
# the total number of watched (IMAP IDLE push) folders by open connections.
|
||||
@@ -51,7 +65,10 @@ tools/editconf.py /etc/dovecot/conf.d/10-mail.conf \
|
||||
mail_privileged_group=mail \
|
||||
first_valid_uid=0
|
||||
|
||||
# ### IMAP
|
||||
# Create, subscribe, and mark as special folders: INBOX, Drafts, Sent, Trash, Spam and Archive.
|
||||
cp conf/dovecot-mailboxes.conf /etc/dovecot/conf.d/15-mailboxes.conf
|
||||
|
||||
# ### IMAP/POP
|
||||
|
||||
# Require that passwords are sent over SSL only, and allow the usual IMAP authentication mechanisms.
|
||||
# The LOGIN mechanism is supposedly for Microsoft products like Outlook to do SMTP login (I guess
|
||||
@@ -62,16 +79,20 @@ tools/editconf.py /etc/dovecot/conf.d/10-auth.conf \
|
||||
|
||||
# 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/.
|
||||
# Enable strong ssl dh parameters
|
||||
|
||||
tools/editconf.py /etc/dovecot/conf.d/10-ssl.conf \
|
||||
ssl=required \
|
||||
"ssl_cert=<$STORAGE_ROOT/ssl/ssl_certificate.pem" \
|
||||
"ssl_key=<$STORAGE_ROOT/ssl/ssl_private_key.pem" \
|
||||
"ssl_protocols=!SSLv3 !SSLv2" \
|
||||
"ssl_cipher_list=TLSv1+HIGH !SSLv2 !RC4 !aNULL !eNULL !3DES @STRENGTH"
|
||||
"ssl_protocols=!SSLv3" \
|
||||
"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_prefer_server_ciphers = yes" \
|
||||
"ssl_dh_parameters_length = 2048"
|
||||
|
||||
# Disable in-the-clear IMAP because there is no reason for a user to transmit
|
||||
# login credentials outside of an encrypted connection. Although we haven't
|
||||
# even installed the POP server, ensure it is disabled too.
|
||||
# Disable in-the-clear IMAP/POP because there is no reason for a user to transmit
|
||||
# login credentials outside of an encrypted connection. Only the over-TLS versions
|
||||
# are made available (IMAPS on port 993; POP3S on port 995).
|
||||
sed -i "s/#port = 143/port = 0/" /etc/dovecot/conf.d/10-master.conf
|
||||
sed -i "s/#port = 110/port = 0/" /etc/dovecot/conf.d/10-master.conf
|
||||
|
||||
@@ -80,10 +101,18 @@ sed -i "s/#port = 110/port = 0/" /etc/dovecot/conf.d/10-master.conf
|
||||
# this are minimal. But for good measure, let's go to 4 minutes to halve the
|
||||
# bandwidth and number of times the device's networking might be woken up.
|
||||
# The risk is that if the connection is silent for too long it might be reset
|
||||
# by a peer. See #129 and http://razor.occams.info/blog/2014/08/09/how-bad-is-imap-idle/.
|
||||
# by a peer. See [#129](https://github.com/mail-in-a-box/mailinabox/issues/129)
|
||||
# and [How bad is IMAP IDLE](http://razor.occams.info/blog/2014/08/09/how-bad-is-imap-idle/).
|
||||
tools/editconf.py /etc/dovecot/conf.d/20-imap.conf \
|
||||
imap_idle_notify_interval="4 mins"
|
||||
|
||||
# Set POP3 UIDL.
|
||||
# UIDLs are used by POP3 clients to keep track of what messages they've downloaded.
|
||||
# For new POP3 servers, the easiest way to set up UIDLs is to use IMAP's UIDVALIDITY
|
||||
# and UID values, the default in Dovecot.
|
||||
tools/editconf.py /etc/dovecot/conf.d/20-pop3.conf \
|
||||
pop3_uidl_format="%08Xu%08Xv"
|
||||
|
||||
# ### LDA (LMTP)
|
||||
|
||||
# Enable Dovecot's LDA service with the LMTP protocol. It will listen
|
||||
@@ -107,6 +136,14 @@ service lmtp {
|
||||
}
|
||||
}
|
||||
|
||||
# Enable imap-login on localhost to allow the user_external plugin
|
||||
# for Nextcloud to do imap authentication. (See #1577)
|
||||
service imap-login {
|
||||
inet_listener imap {
|
||||
address = 127.0.0.1
|
||||
port = 143
|
||||
}
|
||||
}
|
||||
protocol imap {
|
||||
mail_max_userip_connections = 20
|
||||
}
|
||||
@@ -128,6 +165,12 @@ sed -i "s/#mail_plugins = .*/mail_plugins = \$mail_plugins sieve/" /etc/dovecot/
|
||||
#
|
||||
# * `sieve_before`: The path to our global sieve which handles moving spam to the Spam folder.
|
||||
#
|
||||
# * `sieve_before2`: The path to our global sieve directory for sieve which can contain .sieve files
|
||||
# to run globally for every user before their own sieve files run.
|
||||
#
|
||||
# * `sieve_after`: The path to our global sieve directory which can contain .sieve files
|
||||
# to run globally for every user after their own sieve files run.
|
||||
#
|
||||
# * `sieve`: The path to the user's main active script. ManageSieve will create a symbolic
|
||||
# link here to the actual sieve script. It should not be in the mailbox directory
|
||||
# (because then it might appear as a folder) and it should not be in the sieve_dir
|
||||
@@ -137,6 +180,8 @@ sed -i "s/#mail_plugins = .*/mail_plugins = \$mail_plugins sieve/" /etc/dovecot/
|
||||
cat > /etc/dovecot/conf.d/99-local-sieve.conf << EOF;
|
||||
plugin {
|
||||
sieve_before = /etc/dovecot/sieve-spam.sieve
|
||||
sieve_before2 = $STORAGE_ROOT/mail/sieve/global_before
|
||||
sieve_after = $STORAGE_ROOT/mail/sieve/global_after
|
||||
sieve = $STORAGE_ROOT/mail/sieve/%d/%n.sieve
|
||||
sieve_dir = $STORAGE_ROOT/mail/sieve/%d/%n
|
||||
}
|
||||
@@ -160,10 +205,16 @@ chown -R mail.mail $STORAGE_ROOT/mail/mailboxes
|
||||
|
||||
# Same for the sieve scripts.
|
||||
mkdir -p $STORAGE_ROOT/mail/sieve
|
||||
mkdir -p $STORAGE_ROOT/mail/sieve/global_before
|
||||
mkdir -p $STORAGE_ROOT/mail/sieve/global_after
|
||||
chown -R mail.mail $STORAGE_ROOT/mail/sieve
|
||||
|
||||
# Allow the IMAP port in the firewall.
|
||||
# Allow the IMAP/POP ports in the firewall.
|
||||
ufw_allow imaps
|
||||
ufw_allow pop3s
|
||||
|
||||
# Allow the Sieve port in the firewall.
|
||||
ufw_allow sieve
|
||||
|
||||
# Restart services.
|
||||
restart_service dovecot
|
||||
|
||||
@@ -41,44 +41,73 @@ source /etc/mailinabox.conf # load global vars
|
||||
# always will.
|
||||
# * `ca-certificates`: A trust store used to squelch postfix warnings about
|
||||
# untrusted opportunistically-encrypted connections.
|
||||
|
||||
apt_install postfix postfix-pcre postgrey ca-certificates
|
||||
echo "Installing Postfix (SMTP server)..."
|
||||
apt_install postfix postfix-sqlite postfix-pcre postgrey ca-certificates
|
||||
|
||||
# ### Basic Settings
|
||||
|
||||
# Set some basic settings...
|
||||
#
|
||||
# * Have postfix listen on all network interfaces.
|
||||
# * Make outgoing connections on a particular interface (if multihomed) so that SPF passes on the receiving side.
|
||||
# * Set our name (the Debian default seems to be "localhost" but make it our hostname).
|
||||
# * Set the name of the local machine to localhost, which means xxx@localhost is delivered locally, although we don't use it.
|
||||
# * Set the SMTP banner (which must have the hostname first, then anything).
|
||||
tools/editconf.py /etc/postfix/main.cf \
|
||||
inet_interfaces=all \
|
||||
smtp_bind_address=$PRIVATE_IP \
|
||||
smtp_bind_address6=$PRIVATE_IPV6 \
|
||||
myhostname=$PRIMARY_HOSTNAME\
|
||||
smtpd_banner="\$myhostname ESMTP Hi, I'm a Mail-in-a-Box (Ubuntu/Postfix; see https://mailinabox.email/)" \
|
||||
mydestination=localhost
|
||||
|
||||
# Tweak some queue settings:
|
||||
# * Inform users when their e-mail delivery is delayed more than 3 hours (default is not to warn).
|
||||
# * Stop trying to send an undeliverable e-mail after 2 days (instead of 5), and for bounce messages just try for 1 day.
|
||||
tools/editconf.py /etc/postfix/main.cf \
|
||||
delay_warning_time=3h \
|
||||
maximal_queue_lifetime=2d \
|
||||
bounce_queue_lifetime=1d
|
||||
|
||||
# ### Outgoing Mail
|
||||
|
||||
# Enable the 'submission' port 587 smtpd server and tweak its settings.
|
||||
#
|
||||
# * Enable authentication. It's disabled globally so that it is disabled on port 25,
|
||||
# so we need to explicitly enable it here.
|
||||
# * Do not add the OpenDMAC Authentication-Results header. That should only be added
|
||||
# on incoming mail. Omit the OpenDMARC milter by re-setting smtpd_milters to the
|
||||
# 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
|
||||
# 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/.
|
||||
# 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.
|
||||
# * Add a new cleanup service specific to the submission service ('authclean')
|
||||
# that filters out privacy-sensitive headers on mail being sent out by
|
||||
# authenticated users.
|
||||
# authenticated users. By default Postfix also applies this to attached
|
||||
# emails but we turn this off by setting nested_header_checks empty.
|
||||
tools/editconf.py /etc/postfix/master.cf -s -w \
|
||||
"submission=inet n - - - - smtpd
|
||||
-o smtpd_sasl_auth_enable=yes
|
||||
-o syslog_name=postfix/submission
|
||||
-o smtpd_tls_ciphers=high -o smtpd_tls_protocols=!SSLv2,!SSLv3
|
||||
-o smtpd_milters=inet:127.0.0.1:8891
|
||||
-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" \
|
||||
"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
|
||||
-o nested_header_checks="
|
||||
|
||||
# Install the `outgoing_mail_header_filters` file required by the new 'authclean' service.
|
||||
cp conf/postfix_outgoing_mail_header_filters /etc/postfix/outgoing_mail_header_filters
|
||||
|
||||
# Modify the `outgoing_mail_header_filters` file to use the local machine name and ip
|
||||
# on the first received header line. This may help reduce the spam score of email by
|
||||
# removing the 127.0.0.1 reference.
|
||||
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
|
||||
|
||||
# Enable TLS on these and all other connections (i.e. ports 25 *and* 587) and
|
||||
# require TLS before a user is allowed to authenticate. This also makes
|
||||
# opportunistic TLS available on *incoming* mail.
|
||||
@@ -90,6 +119,9 @@ tools/editconf.py /etc/postfix/main.cf \
|
||||
smtpd_tls_cert_file=$STORAGE_ROOT/ssl/ssl_certificate.pem \
|
||||
smtpd_tls_key_file=$STORAGE_ROOT/ssl/ssl_private_key.pem \
|
||||
smtpd_tls_dh1024_param_file=$STORAGE_ROOT/ssl/dh2048.pem \
|
||||
smtpd_tls_protocols=\!SSLv2,\!SSLv3 \
|
||||
smtpd_tls_ciphers=medium \
|
||||
smtpd_tls_exclude_ciphers=aNULL,RC4 \
|
||||
smtpd_tls_received_header=yes
|
||||
|
||||
# Prevent non-authenticated users from sending mail that requires being
|
||||
@@ -117,13 +149,17 @@ tools/editconf.py /etc/postfix/main.cf \
|
||||
# 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
|
||||
# itself but assumes the system's nameserver does and reports DNSSEC status. Thus this also
|
||||
# relies on our local bind9 server being present and `smtp_dns_support_level=dnssec`.
|
||||
# relies on our local DNS server (see system.sh) and `smtp_dns_support_level=dnssec`.
|
||||
#
|
||||
# The `smtp_tls_CAfile` is superflous, but it eliminates warnings in the logs about untrusted certs,
|
||||
# which we don't care about seeing because Postfix is doing opportunistic TLS anyway. Better to encrypt,
|
||||
# even if we don't know if it's to the right party, than to not encrypt at all. Instead we'll
|
||||
# now see notices about trusted certs. The CA file is provided by the package `ca-certificates`.
|
||||
tools/editconf.py /etc/postfix/main.cf \
|
||||
smtp_tls_protocols=\!SSLv2,\!SSLv3 \
|
||||
smtp_tls_mandatory_protocols=\!SSLv2,\!SSLv3 \
|
||||
smtp_tls_ciphers=medium \
|
||||
smtp_tls_exclude_ciphers=aNULL,RC4 \
|
||||
smtp_tls_security_level=dane \
|
||||
smtp_dns_support_level=dnssec \
|
||||
smtp_tls_CAfile=/etc/ssl/certs/ca-certificates.crt \
|
||||
@@ -137,13 +173,17 @@ tools/editconf.py /etc/postfix/main.cf \
|
||||
#
|
||||
# In a basic setup we would pass mail directly to Dovecot by setting
|
||||
# virtual_transport to `lmtp:unix:private/dovecot-lmtp`.
|
||||
#
|
||||
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.
|
||||
# See https://github.com/mail-in-a-box/mailinabox/issues/1523.
|
||||
tools/editconf.py /etc/postfix/main.cf lmtp_destination_recipient_limit=1
|
||||
|
||||
|
||||
# Who can send mail to us? Some basic filters.
|
||||
#
|
||||
# * `reject_non_fqdn_sender`: Reject not-nice-looking return paths.
|
||||
# * `reject_unknown_sender_domain`: Reject return paths with invalid domains.
|
||||
# * `reject_authenticated_sender_login_mismatch`: Reject if mail FROM address does not match the client SASL login
|
||||
# * `reject_rhsbl_sender`: Reject return paths that use blacklisted domains.
|
||||
# * `permit_sasl_authenticated`: Authenticated users (i.e. on port 587) can skip further checks.
|
||||
# * `permit_mynetworks`: Mail that originates locally can skip further checks.
|
||||
@@ -157,13 +197,18 @@ tools/editconf.py /etc/postfix/main.cf virtual_transport=lmtp:[127.0.0.1]:10025
|
||||
# whitelisted) then postfix does a DEFER_IF_REJECT, which results in all "unknown user" sorts of messages turning into #NODOC
|
||||
# "450 4.7.1 Client host rejected: Service unavailable". This is a retry code, so the mail doesn't properly bounce. #NODOC
|
||||
tools/editconf.py /etc/postfix/main.cf \
|
||||
smtpd_sender_restrictions="reject_non_fqdn_sender,reject_unknown_sender_domain,reject_rhsbl_sender dbl.spamhaus.org" \
|
||||
smtpd_sender_restrictions="reject_non_fqdn_sender,reject_unknown_sender_domain,reject_authenticated_sender_login_mismatch,reject_rhsbl_sender dbl.spamhaus.org" \
|
||||
smtpd_recipient_restrictions=permit_sasl_authenticated,permit_mynetworks,"reject_rbl_client zen.spamhaus.org",reject_unlisted_recipient,"check_policy_service inet:127.0.0.1:10023"
|
||||
|
||||
# Postfix connects to Postgrey on the 127.0.0.1 interface specifically. Ensure that
|
||||
# Postgrey listens on the same interface (and not IPv6, for instance).
|
||||
# A lot of legit mail servers try to resend before 300 seconds.
|
||||
# As a matter of fact RFC is not strict about retry timer so postfix and
|
||||
# other MTA have their own intervals. To fix the problem of receiving
|
||||
# e-mails really latter, delay of greylisting has been set to
|
||||
# 180 seconds (default is 300 seconds).
|
||||
tools/editconf.py /etc/default/postgrey \
|
||||
POSTGREY_OPTS=\"--inet=127.0.0.1:10023\"
|
||||
POSTGREY_OPTS=\"'--inet=127.0.0.1:10023 --delay=180'\"
|
||||
|
||||
# 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.
|
||||
@@ -178,3 +223,4 @@ ufw_allow submission
|
||||
# Restart services
|
||||
|
||||
restart_service postfix
|
||||
restart_service postgrey
|
||||
|
||||
@@ -21,7 +21,7 @@ db_path=$STORAGE_ROOT/mail/users.sqlite
|
||||
if [ ! -f $db_path ]; then
|
||||
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 aliases (id INTEGER PRIMARY KEY AUTOINCREMENT, source TEXT NOT NULL UNIQUE, destination TEXT NOT NULL);" | 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;
|
||||
fi
|
||||
|
||||
# ### User Authentication
|
||||
@@ -38,17 +38,19 @@ passdb {
|
||||
args = /etc/dovecot/dovecot-sql.conf.ext
|
||||
}
|
||||
userdb {
|
||||
driver = static
|
||||
args = uid=mail gid=mail home=$STORAGE_ROOT/mail/mailboxes/%d/%n
|
||||
driver = sql
|
||||
args = /etc/dovecot/dovecot-sql.conf.ext
|
||||
}
|
||||
EOF
|
||||
|
||||
# Configure the SQL to query for a user's password.
|
||||
# Configure the SQL to query for a user's metadata and password.
|
||||
cat > /etc/dovecot/dovecot-sql.conf.ext << EOF;
|
||||
driver = sqlite
|
||||
connect = $db_path
|
||||
default_pass_scheme = SHA512-CRYPT
|
||||
password_query = SELECT email as user, password FROM users WHERE email='%u';
|
||||
user_query = SELECT email AS user, "mail" as uid, "mail" as gid, "$STORAGE_ROOT/mail/mailboxes/%d/%n" as home FROM users WHERE email='%u';
|
||||
iterate_query = SELECT email AS user FROM users;
|
||||
EOF
|
||||
chmod 0600 /etc/dovecot/dovecot-sql.conf.ext # per Dovecot instructions
|
||||
|
||||
@@ -63,11 +65,36 @@ service auth {
|
||||
}
|
||||
EOF
|
||||
|
||||
# And have Postfix use that service.
|
||||
# And have Postfix use that service. We *disable* it here
|
||||
# so that authentication is not permitted on port 25 (which
|
||||
# does not run DKIM on relayed mail, so outbound mail isn't
|
||||
# correct, see #830), but we enable it specifically for the
|
||||
# submission port.
|
||||
tools/editconf.py /etc/postfix/main.cf \
|
||||
smtpd_sasl_type=dovecot \
|
||||
smtpd_sasl_path=private/auth \
|
||||
smtpd_sasl_auth_enable=yes
|
||||
smtpd_sasl_auth_enable=no
|
||||
|
||||
# ### Sender Validation
|
||||
|
||||
# We use Postfix's reject_authenticated_sender_login_mismatch filter to
|
||||
# prevent intra-domain spoofing by logged in but untrusted users in outbound
|
||||
# email. In all outbound mail (the sender has authenticated), the MAIL FROM
|
||||
# address (aka envelope or return path address) must be "owned" by the user
|
||||
# who authenticated. An SQL query will find who are the owners of any given
|
||||
# address.
|
||||
tools/editconf.py /etc/postfix/main.cf \
|
||||
smtpd_sender_login_maps=sqlite:/etc/postfix/sender-login-maps.cf
|
||||
|
||||
# Postfix will query the exact address first, where the priority will be alias
|
||||
# records first, then user records. If there are no matches for the exact
|
||||
# address, then Postfix will query just the domain part, which we call
|
||||
# catch-alls and domain aliases. A NULL permitted_senders column means to
|
||||
# take the value from the destination column.
|
||||
cat > /etc/postfix/sender-login-maps.cf << EOF;
|
||||
dbpath=$db_path
|
||||
query = SELECT permitted_senders FROM (SELECT permitted_senders, 0 AS priority FROM aliases WHERE source='%s' AND permitted_senders IS NOT NULL UNION SELECT destination AS permitted_senders, 1 AS priority FROM aliases WHERE source='%s' AND permitted_senders IS NULL UNION SELECT email as permitted_senders, 2 AS priority FROM users WHERE email='%s') ORDER BY priority LIMIT 1;
|
||||
EOF
|
||||
|
||||
# ### Destination Validation
|
||||
|
||||
@@ -79,29 +106,45 @@ tools/editconf.py /etc/postfix/main.cf \
|
||||
virtual_alias_maps=sqlite:/etc/postfix/virtual-alias-maps.cf \
|
||||
local_recipient_maps=\$virtual_mailbox_maps
|
||||
|
||||
# SQL statement to check if we handle 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;
|
||||
dbpath=$db_path
|
||||
query = SELECT 1 FROM users WHERE email LIKE '%%@%s' UNION SELECT 1 FROM aliases WHERE source LIKE '%%@%s'
|
||||
EOF
|
||||
|
||||
# SQL statement to check if we handle mail for a user.
|
||||
# SQL statement to check if we handle incoming mail for a user.
|
||||
cat > /etc/postfix/virtual-mailbox-maps.cf << EOF;
|
||||
dbpath=$db_path
|
||||
query = SELECT 1 FROM users WHERE email='%s'
|
||||
EOF
|
||||
|
||||
# SQL statement to rewrite an email address if an alias is present.
|
||||
# Aliases have precedence over users, but that's counter-intuitive for
|
||||
# catch-all aliases ("@domain.com") which should *not* catch mail users.
|
||||
# To fix this, not only query the aliases table but also the users
|
||||
# table, i.e. turn users into aliases from themselves to themselves.
|
||||
#
|
||||
# Postfix makes multiple queries for each incoming mail. It first
|
||||
# queries the whole email address, then just the user part in certain
|
||||
# locally-directed cases (but we don't use this), then just `@`+the
|
||||
# domain part. The first query that returns something wins. See
|
||||
# http://www.postfix.org/virtual.5.html.
|
||||
#
|
||||
# virtual-alias-maps has precedence over virtual-mailbox-maps, but
|
||||
# we don't want catch-alls and domain aliases to catch mail for users
|
||||
# that have been defined on those domains. To fix this, we not only
|
||||
# query the aliases table but also the users table when resolving
|
||||
# aliases, i.e. we turn users into aliases from themselves to
|
||||
# themselves. That means users will match in postfix's first query
|
||||
# before postfix gets to the third query for catch-alls/domain alises.
|
||||
#
|
||||
# If there is both an alias and a user for the same address either
|
||||
# might be returned by the UNION, so the whole query is wrapped in
|
||||
# another select that prioritizes the alias definition.
|
||||
# another select that prioritizes the alias definition to preserve
|
||||
# postfix's preference for aliases for whole email addresses.
|
||||
#
|
||||
# Since we might have alias records with an empty destination because
|
||||
# it might have just permitted_senders, skip any records with an
|
||||
# empty destination here so that other lower priority rules might match.
|
||||
cat > /etc/postfix/virtual-alias-maps.cf << EOF;
|
||||
dbpath=$db_path
|
||||
query = SELECT destination from (SELECT destination, 0 as priority FROM aliases WHERE source='%s' 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') ORDER BY priority LIMIT 1;
|
||||
EOF
|
||||
|
||||
# Restart Services
|
||||
|
||||
@@ -2,8 +2,57 @@
|
||||
|
||||
source setup/functions.sh
|
||||
|
||||
apt_install python3-flask links duplicity libyaml-dev python3-dnspython python3-dateutil
|
||||
hide_output pip3 install rtyaml
|
||||
echo "Installing Mail-in-a-Box system management daemon..."
|
||||
|
||||
# DEPENDENCIES
|
||||
|
||||
# We used to install management daemon-related Python packages
|
||||
# directly to /usr/local/lib. We moved to a virtualenv because
|
||||
# these packages might conflict with apt-installed packages.
|
||||
# We may have a lingering version of acme that conflcits with
|
||||
# certbot, which we're about to install below, so remove it
|
||||
# first. Once acme is installed by an apt package, this might
|
||||
# break the package version and `apt-get install --reinstall python3-acme`
|
||||
# might be needed in that case.
|
||||
while [ -d /usr/local/lib/python3.4/dist-packages/acme ]; do
|
||||
pip3 uninstall -y acme;
|
||||
done
|
||||
|
||||
# duplicity is used to make backups of user data. It uses boto
|
||||
# (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
|
||||
# install via pip from the system-installed packages.
|
||||
#
|
||||
# certbot installs EFF's certbot which we use to
|
||||
# provision free TLS certificates.
|
||||
apt_install duplicity python-pip virtualenv certbot
|
||||
hide_output pip2 install --upgrade boto
|
||||
|
||||
# Create a virtualenv for the installation of Python 3 packages
|
||||
# used by the management daemon.
|
||||
inst_dir=/usr/local/lib/mailinabox
|
||||
mkdir -p $inst_dir
|
||||
venv=$inst_dir/env
|
||||
if [ ! -d $venv ]; then
|
||||
hide_output virtualenv -ppython3 $venv
|
||||
fi
|
||||
|
||||
# Upgrade pip because the Ubuntu-packaged version is out of date.
|
||||
hide_output $venv/bin/pip install --upgrade pip
|
||||
|
||||
# Install other Python 3 packages used by the management daemon.
|
||||
# The first line is the packages that Josh maintains himself!
|
||||
# NOTE: email_validator is repeated in setup/questions.sh, so please keep the versions synced.
|
||||
hide_output $venv/bin/pip install --upgrade \
|
||||
rtyaml "email_validator>=1.0.0" "exclusiveprocess" \
|
||||
flask dnspython python-dateutil \
|
||||
"idna>=2.0.0" "cryptography==2.2.2" boto psutil
|
||||
|
||||
# CONFIGURATION
|
||||
|
||||
# Create a backup directory and a random key for encrypting backups.
|
||||
mkdir -p $STORAGE_ROOT/backup
|
||||
@@ -11,24 +60,51 @@ if [ ! -f $STORAGE_ROOT/backup/secret_key.txt ]; then
|
||||
$(umask 077; openssl rand -base64 2048 > $STORAGE_ROOT/backup/secret_key.txt)
|
||||
fi
|
||||
|
||||
# Link the management server daemon into a well known location.
|
||||
rm -f /usr/local/bin/mailinabox-daemon
|
||||
ln -s `pwd`/management/daemon.py /usr/local/bin/mailinabox-daemon
|
||||
|
||||
# Download jQuery and Bootstrap local files
|
||||
|
||||
# Make sure we have the directory to save to.
|
||||
assets_dir=$inst_dir/vendor/assets
|
||||
rm -rf $assets_dir
|
||||
mkdir -p $assets_dir
|
||||
|
||||
# jQuery CDN URL
|
||||
jquery_version=2.1.4
|
||||
jquery_url=https://code.jquery.com
|
||||
|
||||
# Get jQuery
|
||||
wget_verify $jquery_url/jquery-$jquery_version.min.js 43dc554608df885a59ddeece1598c6ace434d747 $assets_dir/jquery.min.js
|
||||
|
||||
# Bootstrap CDN URL
|
||||
bootstrap_version=3.3.7
|
||||
bootstrap_url=https://github.com/twbs/bootstrap/releases/download/v$bootstrap_version/bootstrap-$bootstrap_version-dist.zip
|
||||
|
||||
# Get Bootstrap
|
||||
wget_verify $bootstrap_url e6b1000b94e835ffd37f4c6dcbdad43f4b48a02a /tmp/bootstrap.zip
|
||||
unzip -q /tmp/bootstrap.zip -d $assets_dir
|
||||
mv $assets_dir/bootstrap-$bootstrap_version-dist $assets_dir/bootstrap
|
||||
rm -f /tmp/bootstrap.zip
|
||||
|
||||
# Create an init script to start the management daemon and keep it
|
||||
# running after a reboot.
|
||||
rm -f /etc/init.d/mailinabox
|
||||
ln -s $(pwd)/conf/management-initscript /etc/init.d/mailinabox
|
||||
hide_output update-rc.d mailinabox defaults
|
||||
|
||||
# Perform a daily backup.
|
||||
cat > /etc/cron.daily/mailinabox-backup << EOF;
|
||||
cat > $inst_dir/start <<EOF;
|
||||
#!/bin/bash
|
||||
# Mail-in-a-Box --- Do not edit / will be overwritten on update.
|
||||
# Perform a backup.
|
||||
$(pwd)/management/backup.py
|
||||
source $venv/bin/activate
|
||||
exec python `pwd`/management/daemon.py
|
||||
EOF
|
||||
chmod +x /etc/cron.daily/mailinabox-backup
|
||||
chmod +x $inst_dir/start
|
||||
hide_output systemctl link -f conf/mailinabox.service
|
||||
hide_output systemctl daemon-reload
|
||||
hide_output systemctl enable mailinabox.service
|
||||
|
||||
# Start it.
|
||||
# Perform nightly tasks at 3am in system time: take a backup, run
|
||||
# status checks and email the administrator any changes.
|
||||
|
||||
cat > /etc/cron.d/mailinabox-nightly << EOF;
|
||||
# Mail-in-a-Box --- Do not edit / will be overwritten on update.
|
||||
# Run nightly tasks: backup, status checks.
|
||||
0 3 * * * root (cd `pwd` && management/daily_tasks.sh)
|
||||
EOF
|
||||
|
||||
# Start the management server.
|
||||
restart_service mailinabox
|
||||
|
||||
130
setup/migrate.py
130
setup/migrate.py
@@ -67,6 +67,121 @@ def migration_6(env):
|
||||
basepath = os.path.join(env["STORAGE_ROOT"], 'dns/dnssec')
|
||||
shutil.move(os.path.join(basepath, 'keys.conf'), os.path.join(basepath, 'RSASHA1-NSEC3-SHA1.conf'))
|
||||
|
||||
def migration_7(env):
|
||||
# I previously wanted domain names to be stored in Unicode in the database. Now I want them
|
||||
# to be in IDNA. Affects aliases only.
|
||||
import sqlite3
|
||||
conn = sqlite3.connect(os.path.join(env["STORAGE_ROOT"], "mail/users.sqlite"))
|
||||
|
||||
# Get existing alias source addresses.
|
||||
c = conn.cursor()
|
||||
c.execute('SELECT source FROM aliases')
|
||||
aliases = [ row[0] for row in c.fetchall() ]
|
||||
|
||||
# Update to IDNA-encoded domains.
|
||||
for email in aliases:
|
||||
try:
|
||||
localpart, domainpart = email.split("@")
|
||||
domainpart = domainpart.encode("idna").decode("ascii")
|
||||
newemail = localpart + "@" + domainpart
|
||||
if newemail != email:
|
||||
c = conn.cursor()
|
||||
c.execute("UPDATE aliases SET source=? WHERE source=?", (newemail, email))
|
||||
if c.rowcount != 1: raise ValueError("Alias not found.")
|
||||
print("Updated alias", email, "to", newemail)
|
||||
except Exception as e:
|
||||
print("Error updating IDNA alias", email, e)
|
||||
|
||||
# Save.
|
||||
conn.commit()
|
||||
|
||||
def migration_8(env):
|
||||
# Delete DKIM keys. We had generated 1024-bit DKIM keys.
|
||||
# By deleting the key file we'll automatically generate
|
||||
# a new key, which will be 2048 bits.
|
||||
os.unlink(os.path.join(env['STORAGE_ROOT'], 'mail/dkim/mail.private'))
|
||||
|
||||
def migration_9(env):
|
||||
# Add a column to the aliases table to store permitted_senders,
|
||||
# which is a list of user account email addresses that are
|
||||
# permitted to send mail using this alias instead of their own
|
||||
# address. This was motivated by the addition of #427 ("Reject
|
||||
# outgoing mail if FROM does not match Login") - which introduced
|
||||
# the notion of outbound permitted-senders.
|
||||
db = os.path.join(env["STORAGE_ROOT"], 'mail/users.sqlite')
|
||||
shell("check_call", ["sqlite3", db, "ALTER TABLE aliases ADD permitted_senders TEXT"])
|
||||
|
||||
def migration_10(env):
|
||||
# Clean up the SSL certificates directory.
|
||||
|
||||
# Move the primary certificate to a new name and then
|
||||
# symlink it to the system certificate path.
|
||||
import datetime
|
||||
system_certificate = os.path.join(env["STORAGE_ROOT"], 'ssl/ssl_certificate.pem')
|
||||
if not os.path.islink(system_certificate): # not already a symlink
|
||||
new_path = os.path.join(env["STORAGE_ROOT"], 'ssl', env['PRIMARY_HOSTNAME'] + "-" + datetime.datetime.now().date().isoformat().replace("-", "") + ".pem")
|
||||
print("Renamed", system_certificate, "to", new_path, "and created a symlink for the original location.")
|
||||
shutil.move(system_certificate, new_path)
|
||||
os.symlink(new_path, system_certificate)
|
||||
|
||||
# Flatten the directory structure. For any directory
|
||||
# that contains a single file named ssl_certificate.pem,
|
||||
# move the file out and name it the same as the directory,
|
||||
# and remove the directory.
|
||||
for sslcert in glob.glob(os.path.join( env["STORAGE_ROOT"], 'ssl/*/ssl_certificate.pem' )):
|
||||
d = os.path.dirname(sslcert)
|
||||
if len(os.listdir(d)) == 1:
|
||||
# This certificate is the only file in that directory.
|
||||
newname = os.path.join(env["STORAGE_ROOT"], 'ssl', os.path.basename(d) + '.pem')
|
||||
if not os.path.exists(newname):
|
||||
shutil.move(sslcert, newname)
|
||||
os.rmdir(d)
|
||||
|
||||
def migration_11(env):
|
||||
# Archive the old Let's Encrypt account directory managed by free_tls_certificates
|
||||
# because we'll use that path now for the directory managed by certbot.
|
||||
try:
|
||||
old_path = os.path.join(env["STORAGE_ROOT"], 'ssl', 'lets_encrypt')
|
||||
new_path = os.path.join(env["STORAGE_ROOT"], 'ssl', 'lets_encrypt-old')
|
||||
shutil.move(old_path, new_path)
|
||||
except:
|
||||
# meh
|
||||
pass
|
||||
|
||||
def migration_12(env):
|
||||
# Upgrading to Carddav Roundcube plugin to version 3+, it requires the carddav_*
|
||||
# tables to be dropped.
|
||||
# Checking that the roundcube database already exists.
|
||||
if os.path.exists(os.path.join(env["STORAGE_ROOT"], "mail/roundcube/roundcube.sqlite")):
|
||||
import sqlite3
|
||||
conn = sqlite3.connect(os.path.join(env["STORAGE_ROOT"], "mail/roundcube/roundcube.sqlite"))
|
||||
c = conn.cursor()
|
||||
# Get a list of all the tables that begin with 'carddav_'
|
||||
c.execute("SELECT name FROM sqlite_master WHERE type = ? AND name LIKE ?", ('table', 'carddav_%'))
|
||||
carddav_tables = c.fetchall()
|
||||
# If there were tables that begin with 'carddav_', drop them
|
||||
if carddav_tables:
|
||||
for table in carddav_tables:
|
||||
try:
|
||||
table = table[0]
|
||||
c = conn.cursor()
|
||||
dropcmd = "DROP TABLE %s" % table
|
||||
c.execute(dropcmd)
|
||||
except:
|
||||
print("Failed to drop table", table, e)
|
||||
# Save.
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
# Delete all sessions, requring users to login again to recreate carddav_*
|
||||
# databases
|
||||
conn = sqlite3.connect(os.path.join(env["STORAGE_ROOT"], "mail/roundcube/roundcube.sqlite"))
|
||||
c = conn.cursor()
|
||||
c.execute("delete from session;")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_current_migration():
|
||||
ver = 0
|
||||
while True:
|
||||
@@ -84,13 +199,22 @@ def run_migrations():
|
||||
env = load_environment()
|
||||
|
||||
migration_id_file = os.path.join(env['STORAGE_ROOT'], 'mailinabox.version')
|
||||
migration_id = None
|
||||
if os.path.exists(migration_id_file):
|
||||
with open(migration_id_file) as f:
|
||||
ourver = int(f.read().strip())
|
||||
else:
|
||||
migration_id = f.read().strip();
|
||||
|
||||
if migration_id is None:
|
||||
# Load the legacy location of the migration ID. We'll drop support
|
||||
# for this eventually.
|
||||
ourver = int(env.get("MIGRATIONID", "0"))
|
||||
migration_id = env.get("MIGRATIONID")
|
||||
|
||||
if migration_id is None:
|
||||
print()
|
||||
print("%s file doesn't exists. Skipping migration..." % (migration_id_file,))
|
||||
return
|
||||
|
||||
ourver = int(migration_id)
|
||||
|
||||
while True:
|
||||
next_ver = (ourver + 1)
|
||||
|
||||
83
setup/munin.sh
Executable file
83
setup/munin.sh
Executable file
@@ -0,0 +1,83 @@
|
||||
#!/bin/bash
|
||||
# Munin: resource monitoring tool
|
||||
#################################################
|
||||
|
||||
source setup/functions.sh # load our functions
|
||||
source /etc/mailinabox.conf # load global vars
|
||||
|
||||
# install Munin
|
||||
echo "Installing Munin (system monitoring)..."
|
||||
apt_install munin munin-node libcgi-fast-perl
|
||||
# libcgi-fast-perl is needed by /usr/lib/munin/cgi/munin-cgi-graph
|
||||
|
||||
# edit config
|
||||
cat > /etc/munin/munin.conf <<EOF;
|
||||
dbdir /var/lib/munin
|
||||
htmldir /var/cache/munin/www
|
||||
logdir /var/log/munin
|
||||
rundir /var/run/munin
|
||||
tmpldir /etc/munin/templates
|
||||
|
||||
includedir /etc/munin/munin-conf.d
|
||||
|
||||
# path dynazoom uses for requests
|
||||
cgiurl_graph /admin/munin/cgi-graph
|
||||
|
||||
# a simple host tree
|
||||
[$PRIMARY_HOSTNAME]
|
||||
address 127.0.0.1
|
||||
|
||||
# send alerts to the following address
|
||||
contacts admin
|
||||
contact.admin.command mail -s "Munin notification \${var:host}" administrator@$PRIMARY_HOSTNAME
|
||||
contact.admin.always_send warning critical
|
||||
EOF
|
||||
|
||||
# The Debian installer touches these files and chowns them to www-data:adm for use with spawn-fcgi
|
||||
chown munin. /var/log/munin/munin-cgi-html.log
|
||||
chown munin. /var/log/munin/munin-cgi-graph.log
|
||||
|
||||
# ensure munin-node knows the name of this machine
|
||||
# and reduce logging level to warning
|
||||
tools/editconf.py /etc/munin/munin-node.conf -s \
|
||||
host_name=$PRIMARY_HOSTNAME \
|
||||
log_level=1
|
||||
|
||||
# Update the activated plugins through munin's autoconfiguration.
|
||||
munin-node-configure --shell --remove-also 2>/dev/null | sh || /bin/true
|
||||
|
||||
# Deactivate monitoring of NTP peers. Not sure why anyone would want to monitor a NTP peer. The addresses seem to change
|
||||
# (which is taken care of my munin-node-configure, but only when we re-run it.)
|
||||
find /etc/munin/plugins/ -lname /usr/share/munin/plugins/ntp_ -print0 | xargs -0 /bin/rm -f
|
||||
|
||||
# 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
|
||||
IF=$(echo $f | sed s/.*_//);
|
||||
if ! ifquery $IF >/dev/null 2>/dev/null; then
|
||||
rm $f;
|
||||
fi;
|
||||
done
|
||||
|
||||
# Create a 'state' directory. Not sure why we need to do this manually.
|
||||
mkdir -p /var/lib/munin-node/plugin-state/
|
||||
|
||||
# Create a systemd service for munin.
|
||||
ln -sf $(pwd)/management/munin_start.sh /usr/local/lib/mailinabox/munin_start.sh
|
||||
chmod 0744 /usr/local/lib/mailinabox/munin_start.sh
|
||||
hide_output systemctl link -f conf/munin.service
|
||||
hide_output systemctl daemon-reload
|
||||
hide_output systemctl unmask munin.service
|
||||
hide_output systemctl enable munin.service
|
||||
|
||||
# Restart services.
|
||||
restart_service munin
|
||||
restart_service munin-node
|
||||
|
||||
# generate initial statistics so the directory isn't empty
|
||||
# (We get "Pango-WARNING **: error opening config file '/root/.config/pango/pangorc': Permission denied"
|
||||
# if we don't explicitly set the HOME directory when sudo'ing.)
|
||||
# We check to see if munin-cron is already running, if it is, there is no need to run it simultaneously
|
||||
# generating an error.
|
||||
if [ ! -f /var/run/munin/munin-update.lock ]; then
|
||||
sudo -H -u munin munin-cron
|
||||
fi
|
||||
@@ -1,6 +1,6 @@
|
||||
# Install the 'host', 'sed', and and 'nc' tools. This script is run before
|
||||
# the rest of the system setup so we may not yet have things installed.
|
||||
hide_output apt-get -y install bind9-host sed netcat-openbsd
|
||||
apt_get_quiet install bind9-host sed netcat-openbsd
|
||||
|
||||
# Stop if the PRIMARY_HOSTNAME is listed in the Spamhaus Domain Block List.
|
||||
# The user might have chosen a name that was previously in use by a spammer
|
||||
|
||||
308
setup/nextcloud.sh
Executable file
308
setup/nextcloud.sh
Executable file
@@ -0,0 +1,308 @@
|
||||
#!/bin/bash
|
||||
# Nextcloud
|
||||
##########################
|
||||
|
||||
source setup/functions.sh # load our functions
|
||||
source /etc/mailinabox.conf # load global vars
|
||||
|
||||
# ### Installing Nextcloud
|
||||
|
||||
echo "Installing Nextcloud (contacts/calendar)..."
|
||||
|
||||
apt-get purge -qq -y owncloud* # we used to use the package manager
|
||||
|
||||
apt_install php php-fpm \
|
||||
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-intl php-imagick
|
||||
|
||||
InstallNextcloud() {
|
||||
|
||||
version=$1
|
||||
hash=$2
|
||||
|
||||
echo
|
||||
echo "Upgrading to Nextcloud version $version"
|
||||
echo
|
||||
|
||||
# Remove the current owncloud/Nextcloud
|
||||
rm -rf /usr/local/lib/owncloud
|
||||
|
||||
# Download and verify
|
||||
wget_verify https://download.nextcloud.com/server/releases/nextcloud-$version.zip $hash /tmp/nextcloud.zip
|
||||
|
||||
# Extract ownCloud/Nextcloud
|
||||
unzip -q /tmp/nextcloud.zip -d /usr/local/lib
|
||||
mv /usr/local/lib/nextcloud /usr/local/lib/owncloud
|
||||
rm -f /tmp/nextcloud.zip
|
||||
|
||||
# The two apps we actually want are not in Nextcloud core. Download the releases from
|
||||
# their github repositories.
|
||||
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
|
||||
tar xf /tmp/contacts.tgz -C /usr/local/lib/owncloud/apps/
|
||||
rm /tmp/contacts.tgz
|
||||
|
||||
wget_verify https://github.com/nextcloud/calendar/releases/download/v1.6.5/calendar.tar.gz 79941255521a5172f7e4ce42dc7773838b5ede2f /tmp/calendar.tgz
|
||||
tar xf /tmp/calendar.tgz -C /usr/local/lib/owncloud/apps/
|
||||
rm /tmp/calendar.tgz
|
||||
|
||||
# Starting with Nextcloud 15, the app user_external is no longer included in Nextcloud core,
|
||||
# we will install from their github repository.
|
||||
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
|
||||
tar -xf /tmp/user_external.tgz -C /usr/local/lib/owncloud/apps/
|
||||
rm /tmp/user_external.tgz
|
||||
|
||||
# Fix weird permissions.
|
||||
chmod 750 /usr/local/lib/owncloud/{apps,config}
|
||||
|
||||
# Create a symlink to the config.php in STORAGE_ROOT (for upgrades we're restoring the symlink we previously
|
||||
# put in, and in new installs we're creating a symlink and will create the actual config later).
|
||||
ln -sf $STORAGE_ROOT/owncloud/config.php /usr/local/lib/owncloud/config/config.php
|
||||
|
||||
# Make sure permissions are correct or the upgrade step won't run.
|
||||
# $STORAGE_ROOT/owncloud may not yet exist, so use -f to suppress
|
||||
# that error.
|
||||
chown -f -R www-data.www-data $STORAGE_ROOT/owncloud /usr/local/lib/owncloud || /bin/true
|
||||
|
||||
# If this isn't a new installation, immediately run the upgrade script.
|
||||
# Then check for success (0=ok and 3=no upgrade needed, both are success).
|
||||
if [ -e $STORAGE_ROOT/owncloud/owncloud.db ]; then
|
||||
# ownCloud 8.1.1 broke upgrades. It may fail on the first attempt, but
|
||||
# that can be OK.
|
||||
sudo -u www-data php /usr/local/lib/owncloud/occ upgrade
|
||||
if [ \( $? -ne 0 \) -a \( $? -ne 3 \) ]; then
|
||||
echo "Trying ownCloud upgrade again to work around ownCloud upgrade bug..."
|
||||
sudo -u www-data php /usr/local/lib/owncloud/occ upgrade
|
||||
if [ \( $? -ne 0 \) -a \( $? -ne 3 \) ]; then exit 1; fi
|
||||
sudo -u www-data php /usr/local/lib/owncloud/occ maintenance:mode --off
|
||||
echo "...which seemed to work."
|
||||
fi
|
||||
|
||||
# Add missing indices. NextCloud didn't include this in the normal upgrade because it might take some time.
|
||||
sudo -u www-data php /usr/local/lib/owncloud/occ db:add-missing-indices
|
||||
|
||||
# Run conversion to BigInt identifiers, this process may take some time on large tables.
|
||||
sudo -u www-data php /usr/local/lib/owncloud/occ db:convert-filecache-bigint --no-interaction
|
||||
fi
|
||||
}
|
||||
|
||||
nextcloud_ver=15.0.8
|
||||
nextcloud_hash=4129d8d4021c435f2e86876225fb7f15adf764a3
|
||||
# Check if Nextcloud dir exist, and check if version matches nextcloud_ver (if either doesn't - install/upgrade)
|
||||
if [ ! -d /usr/local/lib/owncloud/ ] \
|
||||
|| ! grep -q $nextcloud_ver /usr/local/lib/owncloud/version.php; then
|
||||
|
||||
# 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
|
||||
|
||||
# Backup the existing ownCloud/Nextcloud.
|
||||
# Create a backup directory to store the current installation and database to
|
||||
BACKUP_DIRECTORY=$STORAGE_ROOT/owncloud-backup/`date +"%Y-%m-%d-%T"`
|
||||
mkdir -p "$BACKUP_DIRECTORY"
|
||||
if [ -d /usr/local/lib/owncloud/ ]; then
|
||||
echo "Upgrading Nextcloud --- backing up existing installation, configuration, and database to directory to $BACKUP_DIRECTORY..."
|
||||
cp -r /usr/local/lib/owncloud "$BACKUP_DIRECTORY/owncloud-install"
|
||||
fi
|
||||
if [ -e $STORAGE_ROOT/owncloud/owncloud.db ]; then
|
||||
cp $STORAGE_ROOT/owncloud/owncloud.db $BACKUP_DIRECTORY
|
||||
fi
|
||||
if [ -e $STORAGE_ROOT/owncloud/config.php ]; then
|
||||
cp $STORAGE_ROOT/owncloud/config.php $BACKUP_DIRECTORY
|
||||
fi
|
||||
|
||||
# If ownCloud or Nextcloud was previously installed....
|
||||
if [ -e /usr/local/lib/owncloud/version.php ]; then
|
||||
# Database migrations from ownCloud are no longer possible because ownCloud cannot be run under
|
||||
# PHP 7.
|
||||
if grep -q "OC_VersionString = '[89]\." /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 8 or 9) are not supported. Upgrade to Mail-in-a-Box version v0.30 first. Setup aborting."
|
||||
exit 1
|
||||
fi
|
||||
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 aborting."
|
||||
exit 1
|
||||
fi
|
||||
# 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.
|
||||
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
|
||||
fi
|
||||
fi
|
||||
|
||||
InstallNextcloud $nextcloud_ver $nextcloud_hash
|
||||
fi
|
||||
|
||||
# ### Configuring Nextcloud
|
||||
|
||||
# Setup Nextcloud if the Nextcloud database does not yet exist. Running setup when
|
||||
# the database does exist wipes the database and user data.
|
||||
if [ ! -f $STORAGE_ROOT/owncloud/owncloud.db ]; then
|
||||
# Create user data directory
|
||||
mkdir -p $STORAGE_ROOT/owncloud
|
||||
|
||||
# Create an initial configuration file.
|
||||
instanceid=oc$(echo $PRIMARY_HOSTNAME | sha1sum | fold -w 10 | head -n 1)
|
||||
cat > $STORAGE_ROOT/owncloud/config.php <<EOF;
|
||||
<?php
|
||||
\$CONFIG = array (
|
||||
'datadirectory' => '$STORAGE_ROOT/owncloud',
|
||||
|
||||
'instanceid' => '$instanceid',
|
||||
|
||||
'forcessl' => true, # if unset/false, Nextcloud sends a HSTS=0 header, which conflicts with nginx config
|
||||
|
||||
'overwritewebroot' => '/cloud',
|
||||
'overwrite.cli.url' => '/cloud',
|
||||
'user_backends' => array(
|
||||
array(
|
||||
'class' => 'OC_User_IMAP',
|
||||
'arguments' => array(
|
||||
'127.0.0.1', 143, null
|
||||
),
|
||||
),
|
||||
),
|
||||
'memcache.local' => '\OC\Memcache\APCu',
|
||||
'mail_smtpmode' => 'sendmail',
|
||||
'mail_smtpsecure' => '',
|
||||
'mail_smtpauthtype' => 'LOGIN',
|
||||
'mail_smtpauth' => false,
|
||||
'mail_smtphost' => '',
|
||||
'mail_smtpport' => '',
|
||||
'mail_smtpname' => '',
|
||||
'mail_smtppassword' => '',
|
||||
'mail_from_address' => 'owncloud',
|
||||
);
|
||||
?>
|
||||
EOF
|
||||
|
||||
# Create an auto-configuration file to fill in database settings
|
||||
# when the install script is run. Make an administrator account
|
||||
# here or else the install can't finish.
|
||||
adminpassword=$(dd if=/dev/urandom bs=1 count=40 2>/dev/null | sha1sum | fold -w 30 | head -n 1)
|
||||
cat > /usr/local/lib/owncloud/config/autoconfig.php <<EOF;
|
||||
<?php
|
||||
\$AUTOCONFIG = array (
|
||||
# storage/database
|
||||
'directory' => '$STORAGE_ROOT/owncloud',
|
||||
'dbtype' => 'sqlite3',
|
||||
|
||||
# create an administrator account with a random password so that
|
||||
# the user does not have to enter anything on first load of Nextcloud
|
||||
'adminlogin' => 'root',
|
||||
'adminpass' => '$adminpassword',
|
||||
);
|
||||
?>
|
||||
EOF
|
||||
|
||||
# Set permissions
|
||||
chown -R www-data.www-data $STORAGE_ROOT/owncloud /usr/local/lib/owncloud
|
||||
|
||||
# Execute Nextcloud's setup step, which creates the Nextcloud sqlite database.
|
||||
# It also wipes it if it exists. And it updates config.php with database
|
||||
# settings and deletes the autoconfig.php file.
|
||||
(cd /usr/local/lib/owncloud; sudo -u www-data php /usr/local/lib/owncloud/index.php;)
|
||||
fi
|
||||
|
||||
# Update config.php.
|
||||
# * trusted_domains is reset to localhost by autoconfig starting with ownCloud 8.1.1,
|
||||
# so set it here. It also can change if the box's PRIMARY_HOSTNAME changes, so
|
||||
# this will make sure it has the right value.
|
||||
# * Some settings weren't included in previous versions of Mail-in-a-Box.
|
||||
# * We need to set the timezone to the system timezone to allow fail2ban to ban
|
||||
# users within the proper timeframe
|
||||
# * We need to set the logdateformat to something that will work correctly with fail2ban
|
||||
# * mail_domain' needs to be set every time we run the setup. Making sure we are setting
|
||||
# the correct domain name if the domain is being change from the previous setup.
|
||||
# Use PHP to read the settings file, modify it, and write out the new settings array.
|
||||
TIMEZONE=$(cat /etc/timezone)
|
||||
CONFIG_TEMP=$(/bin/mktemp)
|
||||
php <<EOF > $CONFIG_TEMP && mv $CONFIG_TEMP $STORAGE_ROOT/owncloud/config.php;
|
||||
<?php
|
||||
include("$STORAGE_ROOT/owncloud/config.php");
|
||||
|
||||
\$CONFIG['trusted_domains'] = array('$PRIMARY_HOSTNAME');
|
||||
|
||||
\$CONFIG['memcache.local'] = '\OC\Memcache\APCu';
|
||||
\$CONFIG['overwrite.cli.url'] = '/cloud';
|
||||
\$CONFIG['mail_from_address'] = 'administrator'; # just the local part, matches our master administrator address
|
||||
|
||||
\$CONFIG['logtimezone'] = '$TIMEZONE';
|
||||
\$CONFIG['logdateformat'] = 'Y-m-d H:i:s';
|
||||
|
||||
\$CONFIG['mail_domain'] = '$PRIMARY_HOSTNAME';
|
||||
|
||||
\$CONFIG['user_backends'] = array(array('class' => 'OC_User_IMAP','arguments' => array('127.0.0.1', 143, null),),);
|
||||
|
||||
echo "<?php\n\\\$CONFIG = ";
|
||||
var_export(\$CONFIG);
|
||||
echo ";";
|
||||
?>
|
||||
EOF
|
||||
chown www-data.www-data $STORAGE_ROOT/owncloud/config.php
|
||||
|
||||
# Enable/disable apps. Note that this must be done after the Nextcloud setup.
|
||||
# The firstrunwizard gave Josh all sorts of problems, so disabling that.
|
||||
# user_external is what allows Nextcloud to use IMAP for login. The contacts
|
||||
# and calendar apps are the extensions we really care about here.
|
||||
hide_output sudo -u www-data php /usr/local/lib/owncloud/console.php app:disable firstrunwizard
|
||||
hide_output sudo -u www-data php /usr/local/lib/owncloud/console.php app:enable user_external
|
||||
hide_output sudo -u www-data php /usr/local/lib/owncloud/console.php app:enable contacts
|
||||
hide_output sudo -u www-data php /usr/local/lib/owncloud/console.php app:enable calendar
|
||||
|
||||
# When upgrading, run the upgrade script again now that apps are enabled. It seems like
|
||||
# the first upgrade at the top won't work because apps may be disabled during upgrade?
|
||||
# Check for success (0=ok, 3=no upgrade needed).
|
||||
sudo -u www-data php /usr/local/lib/owncloud/occ upgrade
|
||||
if [ \( $? -ne 0 \) -a \( $? -ne 3 \) ]; then exit 1; fi
|
||||
|
||||
# Set PHP FPM values to support large file uploads
|
||||
# (semicolon is the comment character in this file, hashes produce deprecation warnings)
|
||||
tools/editconf.py /etc/php/7.2/fpm/php.ini -c ';' \
|
||||
upload_max_filesize=16G \
|
||||
post_max_size=16G \
|
||||
output_buffering=16384 \
|
||||
memory_limit=512M \
|
||||
max_execution_time=600 \
|
||||
short_open_tag=On
|
||||
|
||||
# Set Nextcloud recommended opcache settings
|
||||
tools/editconf.py /etc/php/7.2/cli/conf.d/10-opcache.ini -c ';' \
|
||||
opcache.enable=1 \
|
||||
opcache.enable_cli=1 \
|
||||
opcache.interned_strings_buffer=8 \
|
||||
opcache.max_accelerated_files=10000 \
|
||||
opcache.memory_consumption=128 \
|
||||
opcache.save_comments=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 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 ';' \
|
||||
apc.enabled=1
|
||||
fi
|
||||
|
||||
# Set up a cron job for Nextcloud.
|
||||
cat > /etc/cron.hourly/mailinabox-owncloud << EOF;
|
||||
#!/bin/bash
|
||||
# Mail-in-a-Box
|
||||
sudo -u www-data php -f /usr/local/lib/owncloud/cron.php
|
||||
EOF
|
||||
chmod +x /etc/cron.hourly/mailinabox-owncloud
|
||||
|
||||
# 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.
|
||||
# But if we wanted to, we would do this:
|
||||
# ```
|
||||
# for user in $(tools/mail.py user admins); do
|
||||
# sqlite3 $STORAGE_ROOT/owncloud/owncloud.db "INSERT OR IGNORE INTO oc_group_user VALUES ('admin', '$user')"
|
||||
# done
|
||||
# ```
|
||||
|
||||
# Enable PHP modules and restart PHP.
|
||||
restart_service php7.2-fpm
|
||||
@@ -1,141 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Owncloud
|
||||
##########################
|
||||
|
||||
source setup/functions.sh # load our functions
|
||||
source /etc/mailinabox.conf # load global vars
|
||||
|
||||
# ### Installing ownCloud
|
||||
|
||||
apt_install \
|
||||
dbconfig-common \
|
||||
php5-cli php5-sqlite php5-gd php5-imap php5-curl php-pear php-apc curl libapr1 libtool libcurl4-openssl-dev php-xml-parser \
|
||||
php5 php5-dev php5-gd php5-fpm memcached php5-memcache unzip
|
||||
|
||||
apt-get purge -qq -y owncloud*
|
||||
|
||||
# Install ownCloud from source of this version:
|
||||
owncloud_ver=7.0.4
|
||||
|
||||
# Check if ownCloud dir exist, and check if version matches owncloud_ver (if either doesn't - install/upgrade)
|
||||
if [ ! -d /usr/local/lib/owncloud/ ] \
|
||||
|| ! grep -q $owncloud_ver /usr/local/lib/owncloud/version.php; then
|
||||
|
||||
echo installing ownCloud...
|
||||
rm -f /tmp/owncloud.zip
|
||||
wget -qO /tmp/owncloud.zip https://download.owncloud.org/community/owncloud-$owncloud_ver.zip
|
||||
unzip -u -o -q /tmp/owncloud.zip -d /usr/local/lib #either extracts new or replaces current files
|
||||
hide_output php /usr/local/lib/owncloud/occ upgrade #if OC is up-to-date it wont matter
|
||||
rm -f /tmp/owncloud.zip
|
||||
fi
|
||||
|
||||
# ### Configuring ownCloud
|
||||
|
||||
# Setup ownCloud if the ownCloud database does not yet exist. Running setup when
|
||||
# the database does exist wipes the database and user data.
|
||||
if [ ! -f $STORAGE_ROOT/owncloud/owncloud.db ]; then
|
||||
# Create a configuration file.
|
||||
TIMEZONE=$(cat /etc/timezone)
|
||||
instanceid=oc$(echo $PRIMARY_HOSTNAME | sha1sum | fold -w 10 | head -n 1)
|
||||
cat > /usr/local/lib/owncloud/config/config.php <<EOF;
|
||||
<?php
|
||||
\$CONFIG = array (
|
||||
'datadirectory' => '$STORAGE_ROOT/owncloud',
|
||||
|
||||
'instanceid' => '$instanceid',
|
||||
|
||||
'trusted_domains' =>
|
||||
array (
|
||||
0 => '$PRIMARY_HOSTNAME',
|
||||
),
|
||||
'forcessl' => true, # if unset/false, ownCloud sends a HSTS=0 header, which conflicts with nginx config
|
||||
|
||||
'overwritewebroot' => '/cloud',
|
||||
'user_backends' => array(
|
||||
array(
|
||||
'class'=>'OC_User_IMAP',
|
||||
'arguments'=>array('{localhost:993/imap/ssl/novalidate-cert}')
|
||||
)
|
||||
),
|
||||
"memcached_servers" => array (
|
||||
array('localhost', 11211),
|
||||
),
|
||||
'mail_smtpmode' => 'sendmail',
|
||||
'mail_smtpsecure' => '',
|
||||
'mail_smtpauthtype' => 'LOGIN',
|
||||
'mail_smtpauth' => false,
|
||||
'mail_smtphost' => '',
|
||||
'mail_smtpport' => '',
|
||||
'mail_smtpname' => '',
|
||||
'mail_smtppassword' => '',
|
||||
'mail_from_address' => 'owncloud',
|
||||
'mail_domain' => '$PRIMARY_HOSTNAME',
|
||||
'logtimezone' => '$TIMEZONE',
|
||||
);
|
||||
?>
|
||||
EOF
|
||||
|
||||
# Create an auto-configuration file to fill in database settings
|
||||
# when the install script is run. Make an administrator account
|
||||
# here or else the install can't finish.
|
||||
adminpassword=$(dd if=/dev/random bs=1 count=40 2>/dev/null | sha1sum | fold -w 30 | head -n 1)
|
||||
cat > /usr/local/lib/owncloud/config/autoconfig.php <<EOF;
|
||||
<?php
|
||||
\$AUTOCONFIG = array (
|
||||
# storage/database
|
||||
'directory' => '$STORAGE_ROOT/owncloud',
|
||||
'dbtype' => 'sqlite3',
|
||||
|
||||
# create an administrator account with a random password so that
|
||||
# the user does not have to enter anything on first load of ownCloud
|
||||
'adminlogin' => 'root',
|
||||
'adminpass' => '$adminpassword',
|
||||
);
|
||||
?>
|
||||
EOF
|
||||
|
||||
# Create user data directory and set permissions
|
||||
mkdir -p $STORAGE_ROOT/owncloud
|
||||
chown -R www-data.www-data $STORAGE_ROOT/owncloud /usr/local/lib/owncloud
|
||||
|
||||
# Execute ownCloud's setup step, which creates the ownCloud sqlite database.
|
||||
# It also wipes it if it exists. And it deletes the autoconfig.php file.
|
||||
(cd /usr/local/lib/owncloud; sudo -u www-data php /usr/local/lib/owncloud/index.php;)
|
||||
fi
|
||||
|
||||
# Enable/disable apps. Note that this must be done after the ownCloud setup.
|
||||
# The firstrunwizard gave Josh all sorts of problems, so disabling that.
|
||||
# user_external is what allows ownCloud to use IMAP for login.
|
||||
hide_output php /usr/local/lib/owncloud/console.php app:disable firstrunwizard
|
||||
hide_output php /usr/local/lib/owncloud/console.php app:enable user_external
|
||||
|
||||
# Set PHP FPM values to support large file uploads
|
||||
# (semicolon is the comment character in this file, hashes produce deprecation warnings)
|
||||
tools/editconf.py /etc/php5/fpm/php.ini -c ';' \
|
||||
upload_max_filesize=16G \
|
||||
post_max_size=16G \
|
||||
output_buffering=16384 \
|
||||
memory_limit=512M \
|
||||
max_execution_time=600 \
|
||||
short_open_tag=On
|
||||
|
||||
# Set up a cron job for owncloud.
|
||||
cat > /etc/cron.hourly/mailinabox-owncloud << EOF;
|
||||
#!/bin/bash
|
||||
# Mail-in-a-Box
|
||||
sudo -u www-data php -f /usr/local/lib/owncloud/cron.php
|
||||
EOF
|
||||
chmod +x /etc/cron.hourly/mailinabox-owncloud
|
||||
|
||||
# There's nothing much of interest that a user could do as an admin for ownCloud,
|
||||
# and there's a lot they could mess up, so we don't make any users admins of ownCloud.
|
||||
# But if we wanted to, we would do this:
|
||||
# ```
|
||||
# for user in $(tools/mail.py user admins); do
|
||||
# sqlite3 $STORAGE_ROOT/owncloud/owncloud.db "INSERT OR IGNORE INTO oc_group_user VALUES ('admin', '$user')"
|
||||
# done
|
||||
# ```
|
||||
|
||||
# Enable PHP modules and restart PHP.
|
||||
php5enmod imap
|
||||
restart_service php5-fpm
|
||||
@@ -7,9 +7,9 @@ if [[ $EUID -ne 0 ]]; then
|
||||
exit
|
||||
fi
|
||||
|
||||
# Check that we are running on Ubuntu 14.04 LTS (or 14.04.xx).
|
||||
if [ "`lsb_release -d | sed 's/.*:\s*//' | sed 's/14\.04\.[0-9]/14.04/' `" != "Ubuntu 14.04 LTS" ]; then
|
||||
echo "Mail-in-a-Box only supports being installed on Ubuntu 14.04, sorry. You are running:"
|
||||
# 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
|
||||
echo "Mail-in-a-Box only supports being installed on Ubuntu 18.04, sorry. You are running:"
|
||||
echo
|
||||
lsb_release -d | sed 's/.*:\s*//'
|
||||
echo
|
||||
@@ -17,13 +17,50 @@ if [ "`lsb_release -d | sed 's/.*:\s*//' | sed 's/14\.04\.[0-9]/14.04/' `" != "U
|
||||
exit
|
||||
fi
|
||||
|
||||
# Check that we have enough memory. Skip the check if we appear to be
|
||||
# running inside of Vagrant, because that's really just for testing.
|
||||
# Check that we have enough memory.
|
||||
#
|
||||
# /proc/meminfo reports free memory in kibibytes. Our baseline will be 512 MB,
|
||||
# which is 500000 kibibytes.
|
||||
#
|
||||
# We will display a warning if the memory is below 768 MB which is 750000 kibibytes
|
||||
#
|
||||
# Skip the check if we appear to be running inside of Vagrant, because that's really just for testing.
|
||||
TOTAL_PHYSICAL_MEM=$(head -n 1 /proc/meminfo | awk '{print $2}')
|
||||
if [ $TOTAL_PHYSICAL_MEM -lt 786432 ]; then
|
||||
if [ $TOTAL_PHYSICAL_MEM -lt 490000 ]; then
|
||||
if [ ! -d /vagrant ]; then
|
||||
echo "Your Mail-in-a-Box needs more than $TOTAL_PHYSICAL_MEM MB RAM."
|
||||
echo "Please provision a machine with at least 768 MB, 1 GB recommended."
|
||||
TOTAL_PHYSICAL_MEM=$(expr \( \( $TOTAL_PHYSICAL_MEM \* 1024 \) / 1000 \) / 1000)
|
||||
echo "Your Mail-in-a-Box needs more memory (RAM) to function properly."
|
||||
echo "Please provision a machine with at least 512 MB, 1 GB recommended."
|
||||
echo "This machine has $TOTAL_PHYSICAL_MEM MB memory."
|
||||
exit
|
||||
fi
|
||||
fi
|
||||
if [ $TOTAL_PHYSICAL_MEM -lt 750000 ]; then
|
||||
echo "WARNING: Your Mail-in-a-Box has less than 768 MB of memory."
|
||||
echo " It might run unreliably when under heavy load."
|
||||
fi
|
||||
|
||||
# Check that tempfs is mounted with exec
|
||||
MOUNTED_TMP_AS_NO_EXEC=$(grep "/tmp.*noexec" /proc/mounts || /bin/true)
|
||||
if [ -n "$MOUNTED_TMP_AS_NO_EXEC" ]; then
|
||||
echo "Mail-in-a-Box has to have exec rights on /tmp, please mount /tmp with exec"
|
||||
exit
|
||||
fi
|
||||
|
||||
# Check that no .wgetrc exists
|
||||
if [ -e ~/.wgetrc ]; then
|
||||
echo "Mail-in-a-Box expects no overrides to wget defaults, ~/.wgetrc exists"
|
||||
exit
|
||||
fi
|
||||
|
||||
# Check that we are running on x86_64 or i686 architecture, which are the only
|
||||
# ones we support / test.
|
||||
ARCHITECTURE=$(uname -m)
|
||||
if [ "$ARCHITECTURE" != "x86_64" ] && [ "$ARCHITECTURE" != "i686" ]; then
|
||||
echo
|
||||
echo "WARNING:"
|
||||
echo "Mail-in-a-Box has only been tested on x86_64 and i686 platform"
|
||||
echo "architectures. Your architecture, $ARCHITECTURE, may not work."
|
||||
echo "You are on your own."
|
||||
echo
|
||||
fi
|
||||
|
||||
@@ -1,19 +1,32 @@
|
||||
if [ -z "$NONINTERACTIVE" ]; then
|
||||
if [ -z "${NONINTERACTIVE:-}" ]; then
|
||||
# Install 'dialog' so we can ask the user questions. The original motivation for
|
||||
# this was being able to ask the user for input even if stdin has been redirected,
|
||||
# e.g. if we piped a bootstrapping install script to bash to get started. In that
|
||||
# case, the nifty '[ -t 0 ]' test won't work. But with Vagrant we must suppress so we
|
||||
# use a shell flag instead. Really supress any output from installing dialog.
|
||||
hide_output apt-get -y install dialog
|
||||
# use a shell flag instead. Really suppress any output from installing dialog.
|
||||
#
|
||||
# Also install dependencies needed to validate the email address.
|
||||
if [ ! -f /usr/bin/dialog ] || [ ! -f /usr/bin/python3 ] || [ ! -f /usr/bin/pip3 ]; then
|
||||
echo Installing packages needed for setup...
|
||||
apt-get -q -q update
|
||||
apt_get_quiet install dialog python3 python3-pip || exit 1
|
||||
fi
|
||||
|
||||
# Installing email_validator is repeated in setup/management.sh, but in setup/management.sh
|
||||
# we install it inside a virtualenv. In this script, we don't have the virtualenv yet
|
||||
# so we install the python package globally.
|
||||
hide_output pip3 install "email_validator>=1.0.0" || exit 1
|
||||
|
||||
message_box "Mail-in-a-Box Installation" \
|
||||
"Hello and thanks for deploying a Mail-in-a-Box!
|
||||
\n\nI'm going to ask you a few questions.
|
||||
\n\nTo change your answers later, just run 'sudo mailinabox' from the command line."
|
||||
\n\nTo change your answers later, just run 'sudo mailinabox' from the command line.
|
||||
\n\nNOTE: You should only install this on a brand new Ubuntu installation 100% dedicated to Mail-in-a-Box. Mail-in-a-Box will, for example, remove apache2."
|
||||
fi
|
||||
|
||||
# The box needs a name.
|
||||
if [ -z "$PRIMARY_HOSTNAME" ]; then
|
||||
if [ -z "$DEFAULT_PRIMARY_HOSTNAME" ]; then
|
||||
if [ -z "${PRIMARY_HOSTNAME:-}" ]; then
|
||||
if [ -z "${DEFAULT_PRIMARY_HOSTNAME:-}" ]; then
|
||||
# We recommend to use box.example.com as this hosts name. The
|
||||
# domain the user possibly wants to use is example.com then.
|
||||
# We strip the string "box." from the hostname to get the mail
|
||||
@@ -38,7 +51,7 @@ you really want.
|
||||
# user hit ESC/cancel
|
||||
exit
|
||||
fi
|
||||
while ! management/mailconfig.py validate-email "$EMAIL_ADDR"
|
||||
while ! python3 management/mailconfig.py validate-email "$EMAIL_ADDR"
|
||||
do
|
||||
input_box "Your Email Address" \
|
||||
"That's not a valid email address.\n\nWhat email address are you setting this box up to manage?" \
|
||||
@@ -73,30 +86,30 @@ fi
|
||||
# If the machine is behind a NAT, inside a VM, etc., it may not know
|
||||
# its IP address on the public network / the Internet. Ask the Internet
|
||||
# and possibly confirm with user.
|
||||
if [ -z "$PUBLIC_IP" ]; then
|
||||
if [ -z "${PUBLIC_IP:-}" ]; then
|
||||
# Ask the Internet.
|
||||
GUESSED_IP=$(get_publicip_from_web_service 4)
|
||||
|
||||
# On the first run, if we got an answer from the Internet then don't
|
||||
# ask the user.
|
||||
if [[ -z "$DEFAULT_PUBLIC_IP" && ! -z "$GUESSED_IP" ]]; then
|
||||
if [[ -z "${DEFAULT_PUBLIC_IP:-}" && ! -z "$GUESSED_IP" ]]; then
|
||||
PUBLIC_IP=$GUESSED_IP
|
||||
|
||||
# Otherwise on the first run at least provide a default.
|
||||
elif [[ -z "$DEFAULT_PUBLIC_IP" ]]; then
|
||||
elif [[ -z "${DEFAULT_PUBLIC_IP:-}" ]]; then
|
||||
DEFAULT_PUBLIC_IP=$(get_default_privateip 4)
|
||||
|
||||
# On later runs, if the previous value matches the guessed value then
|
||||
# don't ask the user either.
|
||||
elif [ "$DEFAULT_PUBLIC_IP" == "$GUESSED_IP" ]; then
|
||||
elif [ "${DEFAULT_PUBLIC_IP:-}" == "$GUESSED_IP" ]; then
|
||||
PUBLIC_IP=$GUESSED_IP
|
||||
fi
|
||||
|
||||
if [ -z "$PUBLIC_IP" ]; then
|
||||
if [ -z "${PUBLIC_IP:-}" ]; then
|
||||
input_box "Public IP Address" \
|
||||
"Enter the public IP address of this machine, as given to you by your ISP.
|
||||
\n\nPublic IP address:" \
|
||||
$DEFAULT_PUBLIC_IP \
|
||||
${DEFAULT_PUBLIC_IP:-} \
|
||||
PUBLIC_IP
|
||||
|
||||
if [ -z "$PUBLIC_IP" ]; then
|
||||
@@ -108,27 +121,27 @@ fi
|
||||
|
||||
# Same for IPv6. But it's optional. Also, if it looks like the system
|
||||
# doesn't have an IPv6, don't ask for one.
|
||||
if [ -z "$PUBLIC_IPV6" ]; then
|
||||
if [ -z "${PUBLIC_IPV6:-}" ]; then
|
||||
# Ask the Internet.
|
||||
GUESSED_IP=$(get_publicip_from_web_service 6)
|
||||
MATCHED=0
|
||||
if [[ -z "$DEFAULT_PUBLIC_IPV6" && ! -z "$GUESSED_IP" ]]; then
|
||||
if [[ -z "${DEFAULT_PUBLIC_IPV6:-}" && ! -z "$GUESSED_IP" ]]; then
|
||||
PUBLIC_IPV6=$GUESSED_IP
|
||||
elif [[ "$DEFAULT_PUBLIC_IPV6" == "$GUESSED_IP" ]]; then
|
||||
elif [[ "${DEFAULT_PUBLIC_IPV6:-}" == "$GUESSED_IP" ]]; then
|
||||
# No IPv6 entered and machine seems to have none, or what
|
||||
# the user entered matches what the Internet tells us.
|
||||
PUBLIC_IPV6=$GUESSED_IP
|
||||
MATCHED=1
|
||||
elif [[ -z "$DEFAULT_PUBLIC_IPV6" ]]; then
|
||||
elif [[ -z "${DEFAULT_PUBLIC_IPV6:-}" ]]; then
|
||||
DEFAULT_PUBLIC_IP=$(get_default_privateip 6)
|
||||
fi
|
||||
|
||||
if [[ -z "$PUBLIC_IPV6" && $MATCHED == 0 ]]; then
|
||||
if [[ -z "${PUBLIC_IPV6:-}" && $MATCHED == 0 ]]; then
|
||||
input_box "IPv6 Address (Optional)" \
|
||||
"Enter the public IPv6 address of this machine, as given to you by your ISP.
|
||||
\n\nLeave blank if the machine does not have an IPv6 address.
|
||||
\n\nPublic IPv6 address:" \
|
||||
$DEFAULT_PUBLIC_IPV6 \
|
||||
${DEFAULT_PUBLIC_IPV6:-} \
|
||||
PUBLIC_IPV6
|
||||
|
||||
if [ ! $PUBLIC_IPV6_EXITCODE ]; then
|
||||
@@ -141,10 +154,10 @@ fi
|
||||
# Get the IP addresses of the local network interface(s) that are connected
|
||||
# to the Internet. We need these when we want to have services bind only to
|
||||
# the public network interfaces (not loopback, not tunnel interfaces).
|
||||
if [ -z "$PRIVATE_IP" ]; then
|
||||
if [ -z "${PRIVATE_IP:-}" ]; then
|
||||
PRIVATE_IP=$(get_default_privateip 4)
|
||||
fi
|
||||
if [ -z "$PRIVATE_IPV6" ]; then
|
||||
if [ -z "${PRIVATE_IPV6:-}" ]; then
|
||||
PRIVATE_IPV6=$(get_default_privateip 6)
|
||||
fi
|
||||
if [[ -z "$PRIVATE_IP" && -z "$PRIVATE_IPV6" ]]; then
|
||||
@@ -158,31 +171,42 @@ if [[ -z "$PRIVATE_IP" && -z "$PRIVATE_IPV6" ]]; then
|
||||
exit
|
||||
fi
|
||||
|
||||
# We need a country code to generate a certificate signing request. However
|
||||
# if a CSR already exists then we won't be generating a new one and there's
|
||||
# no reason to ask for the country code now. $STORAGE_ROOT has not yet been
|
||||
# set so we'll check if $DEFAULT_STORAGE_ROOT and $DEFAULT_CSR_COUNTRY are
|
||||
# set (the values from the current mailinabox.conf) and if the CSR exists
|
||||
# in the expected location.
|
||||
if [ ! -z "$DEFAULT_STORAGE_ROOT" ] && [ ! -z "$DEFAULT_CSR_COUNTRY" ] && [ -f $DEFAULT_STORAGE_ROOT/ssl/ssl_cert_sign_req.csr ]; then
|
||||
CSR_COUNTRY=$DEFAULT_CSR_COUNTRY
|
||||
# Automatic configuration, e.g. as used in our Vagrant configuration.
|
||||
if [ "$PUBLIC_IP" = "auto" ]; then
|
||||
# Use a public API to get our public IP address, or fall back to local network configuration.
|
||||
PUBLIC_IP=$(get_publicip_from_web_service 4 || get_default_privateip 4)
|
||||
fi
|
||||
if [ "$PUBLIC_IPV6" = "auto" ]; then
|
||||
# Use a public API to get our public IPv6 address, or fall back to local network configuration.
|
||||
PUBLIC_IPV6=$(get_publicip_from_web_service 6 || get_default_privateip 6)
|
||||
fi
|
||||
if [ "$PRIMARY_HOSTNAME" = "auto" ]; then
|
||||
PRIMARY_HOSTNAME=$(get_default_hostname)
|
||||
fi
|
||||
|
||||
if [ -z "$CSR_COUNTRY" ]; then
|
||||
# Get a list of country codes. Separate codes from country names with a ^.
|
||||
# The input_menu function modifies shell word expansion to ignore spaces
|
||||
# (since country names can have spaces) and use ^ instead.
|
||||
country_code_list=$(grep -v "^#" setup/csr_country_codes.tsv | sed "s/\(..\)\t\([^\t]*\).*/\1^\2/")
|
||||
|
||||
input_menu "Country Code" \
|
||||
"Choose the country where you live or where your organization is based.
|
||||
\n\n(This is used to create an SSL certificate.)
|
||||
\n\nCountry Code:" \
|
||||
"$country_code_list" \
|
||||
CSR_COUNTRY
|
||||
|
||||
if [ -z "$CSR_COUNTRY" ]; then
|
||||
# user hit ESC/cancel
|
||||
exit
|
||||
# Set STORAGE_USER and STORAGE_ROOT to default values (user-data and /home/user-data), unless
|
||||
# we've already got those values from a previous run.
|
||||
if [ -z "${STORAGE_USER:-}" ]; then
|
||||
STORAGE_USER=$([[ -z "${DEFAULT_STORAGE_USER:-}" ]] && echo "user-data" || echo "$DEFAULT_STORAGE_USER")
|
||||
fi
|
||||
if [ -z "${STORAGE_ROOT:-}" ]; then
|
||||
STORAGE_ROOT=$([[ -z "${DEFAULT_STORAGE_ROOT:-}" ]] && echo "/home/$STORAGE_USER" || echo "$DEFAULT_STORAGE_ROOT")
|
||||
fi
|
||||
|
||||
# Show the configuration, since the user may have not entered it manually.
|
||||
echo
|
||||
echo "Primary Hostname: $PRIMARY_HOSTNAME"
|
||||
echo "Public IP Address: $PUBLIC_IP"
|
||||
if [ ! -z "$PUBLIC_IPV6" ]; then
|
||||
echo "Public IPv6 Address: $PUBLIC_IPV6"
|
||||
fi
|
||||
if [ "$PRIVATE_IP" != "$PUBLIC_IP" ]; then
|
||||
echo "Private IP Address: $PRIVATE_IP"
|
||||
fi
|
||||
if [ "$PRIVATE_IPV6" != "$PUBLIC_IPV6" ]; then
|
||||
echo "Private IPv6 Address: $PRIVATE_IPV6"
|
||||
fi
|
||||
if [ -f /usr/bin/git ] && [ -d .git ]; then
|
||||
echo "Mail-in-a-Box Version: " $(git describe)
|
||||
fi
|
||||
echo
|
||||
|
||||
@@ -16,19 +16,40 @@ source setup/functions.sh # load our functions
|
||||
# ----------------------------------------
|
||||
|
||||
# Install packages.
|
||||
apt_install spampd razor pyzor dovecot-antispam
|
||||
# libmail-dkim-perl is needed to make the spamassassin DKIM module work.
|
||||
# For more information see Debian Bug #689414:
|
||||
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=689414
|
||||
echo "Installing SpamAssassin..."
|
||||
apt_install spampd razor pyzor dovecot-antispam libmail-dkim-perl
|
||||
|
||||
# Allow spamassassin to download new rules.
|
||||
tools/editconf.py /etc/default/spamassassin \
|
||||
CRON=1
|
||||
|
||||
# Configure pyzor.
|
||||
hide_output pyzor discover
|
||||
# Configure pyzor, which is a client to a live database of hashes of
|
||||
# spam emails. Set the pyzor configuration directory to something sane.
|
||||
# The default is ~/.pyzor. We used to use that, so we'll kill that old
|
||||
# directory. Then write the public pyzor server to its servers file.
|
||||
# That will prevent an automatic download on first use, and also means
|
||||
# we can skip 'pyzor discover', both of which are currently broken by
|
||||
# something happening on Sourceforge (#496).
|
||||
rm -rf ~/.pyzor
|
||||
tools/editconf.py /etc/spamassassin/local.cf -s \
|
||||
pyzor_options="--homedir /etc/spamassassin/pyzor"
|
||||
mkdir -p /etc/spamassassin/pyzor
|
||||
echo "public.pyzor.org:24441" > /etc/spamassassin/pyzor/servers
|
||||
# check with: pyzor --homedir /etc/mail/spamassassin/pyzor ping
|
||||
|
||||
# Pass messages on to docevot on port 10026.
|
||||
# This is actually the default setting but we don't want to lose track of it.
|
||||
# We've already configured Dovecot to listen on this port.
|
||||
tools/editconf.py /etc/default/spampd DESTPORT=10026
|
||||
# Configure spampd:
|
||||
# * Pass messages on to docevot on port 10026. This is actually the default setting but we don't
|
||||
# want to lose track of it. (We've configured Dovecot to listen on this port elsewhere.)
|
||||
# * Increase the maximum message size of scanned messages from the default of 64KB to 500KB, which
|
||||
# is Spamassassin (spamc)'s own default. Specified in KBytes.
|
||||
# * Disable localmode so Pyzor, DKIM and DNS checks can be used.
|
||||
tools/editconf.py /etc/default/spampd \
|
||||
DESTPORT=10026 \
|
||||
ADDOPTS="\"--maxsize=2000\"" \
|
||||
LOCALONLY=0
|
||||
|
||||
# Spamassassin normally wraps spam as an attachment inside a fresh
|
||||
# email with a report about the message. This also protects the user
|
||||
@@ -40,9 +61,11 @@ tools/editconf.py /etc/default/spampd DESTPORT=10026
|
||||
# content or execute scripts, and it is probably confusing to most users.
|
||||
#
|
||||
# Tell Spamassassin not to modify the original message except for adding
|
||||
# the X-Spam-Status mail header and related headers.
|
||||
# the X-Spam-Status & X-Spam-Score mail headers and related headers.
|
||||
tools/editconf.py /etc/spamassassin/local.cf -s \
|
||||
report_safe=0
|
||||
report_safe=0 \
|
||||
add_header="all Report _REPORT_" \
|
||||
add_header="all Score _SCORE_"
|
||||
|
||||
# Bayesean learning
|
||||
# -----------------
|
||||
@@ -57,9 +80,13 @@ tools/editconf.py /etc/spamassassin/local.cf -s \
|
||||
# * Writable by the debian-spamd user, which runs /etc/cron.daily/spamassassin.
|
||||
#
|
||||
# We'll have these files owned by spampd and grant access to the other two processes.
|
||||
#
|
||||
# Spamassassin will change the access rights back to the defaults, so we must also configure
|
||||
# the filemode in the config file.
|
||||
|
||||
tools/editconf.py /etc/spamassassin/local.cf -s \
|
||||
bayes_path=$STORAGE_ROOT/mail/spamassassin/bayes
|
||||
bayes_path=$STORAGE_ROOT/mail/spamassassin/bayes \
|
||||
bayes_file_mode=0666
|
||||
|
||||
mkdir -p $STORAGE_ROOT/mail/spamassassin
|
||||
chown -R spampd:spampd $STORAGE_ROOT/mail/spamassassin
|
||||
@@ -71,12 +98,14 @@ chown -R spampd:spampd $STORAGE_ROOT/mail/spamassassin
|
||||
# Enable the Dovecot antispam plugin.
|
||||
# (Be careful if we use multiple plugins later.) #NODOC
|
||||
sed -i "s/#mail_plugins = .*/mail_plugins = \$mail_plugins antispam/" /etc/dovecot/conf.d/20-imap.conf
|
||||
sed -i "s/#mail_plugins = .*/mail_plugins = \$mail_plugins antispam/" /etc/dovecot/conf.d/20-pop3.conf
|
||||
|
||||
# Configure the antispam plugin to call sa-learn-pipe.sh.
|
||||
cat > /etc/dovecot/conf.d/99-local-spampd.conf << EOF;
|
||||
plugin {
|
||||
antispam_backend = pipe
|
||||
antispam_spam_pattern_ignorecase = SPAM
|
||||
antispam_trash_pattern_ignorecase = trash;Deleted *
|
||||
antispam_allow_append_to_spam = yes
|
||||
antispam_pipe_program_spam_args = /usr/local/bin/sa-learn-pipe.sh;--spam
|
||||
antispam_pipe_program_notspam_args = /usr/local/bin/sa-learn-pipe.sh;--ham
|
||||
|
||||
94
setup/ssl.sh
94
setup/ssl.sh
@@ -1,52 +1,98 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# SSL Certificate
|
||||
# ---------------
|
||||
# RSA private key, SSL certificate, Diffie-Hellman bits files
|
||||
# -------------------------------------------
|
||||
|
||||
# Create a self-signed SSL certificate if one has not yet been created.
|
||||
# Create an RSA private key, a self-signed SSL certificate, and some
|
||||
# Diffie-Hellman cipher bits, if they have not yet been created.
|
||||
#
|
||||
# The certificate is for PRIMARY_HOSTNAME specifically and is used for:
|
||||
# The RSA private key and certificate are used for:
|
||||
#
|
||||
# * DNSSEC DANE TLSA records
|
||||
# * IMAP
|
||||
# * SMTP submission (port 587) and opportunistic TLS (when on the receiving end)
|
||||
# * the DNSSEC DANE TLSA record for SMTP
|
||||
# * HTTPS (for PRIMARY_HOSTNAME only)
|
||||
# * SMTP (opportunistic TLS for port 25 and submission on port 587)
|
||||
# * HTTPS
|
||||
#
|
||||
# When other domains besides PRIMARY_HOSTNAME are served over HTTPS,
|
||||
# we generate a domain-specific self-signed certificate in the management
|
||||
# daemon (web_update.py) as needed.
|
||||
# The certificate is created with its CN set to the PRIMARY_HOSTNAME. It is
|
||||
# also used for other domains served over HTTPS until the user installs a
|
||||
# better certificate for those domains.
|
||||
#
|
||||
# The Diffie-Hellman cipher bits are used for SMTP and HTTPS, when a
|
||||
# Diffie-Hellman cipher is selected during TLS negotiation. Diffie-Hellman
|
||||
# provides Perfect Forward Secrecy.
|
||||
|
||||
source setup/functions.sh # load our functions
|
||||
source /etc/mailinabox.conf # load global vars
|
||||
|
||||
# Show a status line if we are going to take any action in this file.
|
||||
if [ ! -f /usr/bin/openssl ] \
|
||||
|| [ ! -f $STORAGE_ROOT/ssl/ssl_private_key.pem ] \
|
||||
|| [ ! -f $STORAGE_ROOT/ssl/ssl_certificate.pem ] \
|
||||
|| [ ! -f $STORAGE_ROOT/ssl/dh2048.pem ]; then
|
||||
echo "Creating initial SSL certificate and perfect forward secrecy Diffie-Hellman parameters..."
|
||||
fi
|
||||
|
||||
# Install openssl.
|
||||
|
||||
apt_install openssl
|
||||
|
||||
# Create a directory to store TLS-related things like "SSL" certificates.
|
||||
|
||||
mkdir -p $STORAGE_ROOT/ssl
|
||||
|
||||
# Generate a new private key.
|
||||
# Set the umask so the key file is not world-readable.
|
||||
#
|
||||
# The key is only as good as the entropy available to openssl so that it
|
||||
# can generate a random key. "OpenSSL’s built-in RSA key generator ....
|
||||
# is seeded on first use with (on Linux) 32 bytes read from /dev/urandom,
|
||||
# the process ID, user ID, and the current time in seconds. [During key
|
||||
# generation OpenSSL] mixes into the entropy pool the current time in seconds,
|
||||
# the process ID, and the possibly uninitialized contents of a ... buffer
|
||||
# ... dozens to hundreds of times."
|
||||
#
|
||||
# A perfect storm of issues can cause the generated key to be not very random:
|
||||
#
|
||||
# * improperly seeded /dev/urandom, but see system.sh for how we mitigate this
|
||||
# * the user ID of this process is always the same (we're root), so that seed is useless
|
||||
# * zero'd memory (plausible on embedded systems, cloud VMs?)
|
||||
# * a predictable process ID (likely on an embedded/virtualized system)
|
||||
# * a system clock reset to a fixed time on boot
|
||||
#
|
||||
# Since we properly seed /dev/urandom in system.sh we should be fine, but I leave
|
||||
# in the rest of the notes in case that ever changes.
|
||||
if [ ! -f $STORAGE_ROOT/ssl/ssl_private_key.pem ]; then
|
||||
# Set the umask so the key file is never world-readable.
|
||||
(umask 077; hide_output \
|
||||
openssl genrsa -out $STORAGE_ROOT/ssl/ssl_private_key.pem 2048)
|
||||
fi
|
||||
|
||||
# Generate a certificate signing request.
|
||||
if [ ! -f $STORAGE_ROOT/ssl/ssl_cert_sign_req.csr ]; then
|
||||
hide_output \
|
||||
openssl req -new -key $STORAGE_ROOT/ssl/ssl_private_key.pem -out $STORAGE_ROOT/ssl/ssl_cert_sign_req.csr \
|
||||
-sha256 -subj "/C=$CSR_COUNTRY/ST=/L=/O=/CN=$PRIMARY_HOSTNAME"
|
||||
fi
|
||||
|
||||
# Generate a SSL certificate by self-signing.
|
||||
# Generate a self-signed SSL certificate because things like nginx, dovecot,
|
||||
# etc. won't even start without some certificate in place, and we need nginx
|
||||
# so we can offer the user a control panel to install a better certificate.
|
||||
if [ ! -f $STORAGE_ROOT/ssl/ssl_certificate.pem ]; then
|
||||
# Generate a certificate signing request.
|
||||
CSR=/tmp/ssl_cert_sign_req-$$.csr
|
||||
hide_output \
|
||||
openssl req -new -key $STORAGE_ROOT/ssl/ssl_private_key.pem -out $CSR \
|
||||
-sha256 -subj "/CN=$PRIMARY_HOSTNAME"
|
||||
|
||||
# Generate the self-signed certificate.
|
||||
CERT=$STORAGE_ROOT/ssl/$PRIMARY_HOSTNAME-selfsigned-$(date --rfc-3339=date | sed s/-//g).pem
|
||||
hide_output \
|
||||
openssl x509 -req -days 365 \
|
||||
-in $STORAGE_ROOT/ssl/ssl_cert_sign_req.csr -signkey $STORAGE_ROOT/ssl/ssl_private_key.pem -out $STORAGE_ROOT/ssl/ssl_certificate.pem
|
||||
-in $CSR -signkey $STORAGE_ROOT/ssl/ssl_private_key.pem -out $CERT
|
||||
|
||||
# Delete the certificate signing request because it has no other purpose.
|
||||
rm -f $CSR
|
||||
|
||||
# Symlink the certificate into the system certificate path, so system services
|
||||
# can find it.
|
||||
ln -s $CERT $STORAGE_ROOT/ssl/ssl_certificate.pem
|
||||
fi
|
||||
|
||||
# For nginx and postfix, pre-generate some Diffie-Hellman cipher bits which is
|
||||
# used when a Diffie-Hellman cipher is selected during TLS negotiation. Diffie-Hellman
|
||||
# provides Perfect Forward Security. openssl's default is 1024 bits, but we'll
|
||||
# create 2048.
|
||||
# Generate some Diffie-Hellman cipher bits.
|
||||
# openssl's default bit length for this is 1024 bits, but we'll create
|
||||
# 2048 bits of bits per the latest recommendations.
|
||||
if [ ! -f $STORAGE_ROOT/ssl/dh2048.pem ]; then
|
||||
openssl dhparam -out $STORAGE_ROOT/ssl/dh2048.pem 2048
|
||||
fi
|
||||
|
||||
130
setup/start.sh
130
setup/start.sh
@@ -4,16 +4,17 @@
|
||||
|
||||
source setup/functions.sh # load our functions
|
||||
|
||||
# Check system setup: Are we running as root on Ubuntu 14.04 on a
|
||||
# machine with enough memory? If not, this shows an error and exits.
|
||||
# Check system setup: Are we running as root on Ubuntu 18.04 on a
|
||||
# machine with enough memory? Is /tmp mounted with exec.
|
||||
# If not, this shows an error and exits.
|
||||
source setup/preflight.sh
|
||||
|
||||
# Ensure Python reads/writes files in UTF-8. If the machine
|
||||
# triggers some other locale in Python, like ASCII encoding,
|
||||
# Python may not be able to read/write files. Here and in
|
||||
# the management daemon startup script.
|
||||
# Python may not be able to read/write files. This is also
|
||||
# in the management daemon startup script and the cron script.
|
||||
|
||||
if [ -z `locale -a | grep en_US.utf8` ]; then
|
||||
if ! locale -a | grep en_US.utf8 > /dev/null; then
|
||||
# Generate locale if not exists
|
||||
hide_output locale-gen en_US.UTF-8
|
||||
fi
|
||||
@@ -23,17 +24,22 @@ export LC_ALL=en_US.UTF-8
|
||||
export LANG=en_US.UTF-8
|
||||
export LC_TYPE=en_US.UTF-8
|
||||
|
||||
# Fix so line drawing characters are shown correctly in Putty on Windows. See #744.
|
||||
export NCURSES_NO_UTF8_ACS=1
|
||||
|
||||
# Recall the last settings used if we're running this a second time.
|
||||
if [ -f /etc/mailinabox.conf ]; then
|
||||
# Run any system migrations before proceeding. Since this is a second run,
|
||||
# we assume we have Python already installed.
|
||||
setup/migrate.py --migrate
|
||||
setup/migrate.py --migrate || exit 1
|
||||
|
||||
# Load the old .conf file to get existing configuration options loaded
|
||||
# into variables with a DEFAULT_ prefix.
|
||||
cat /etc/mailinabox.conf | sed s/^/DEFAULT_/ > /tmp/mailinabox.prev.conf
|
||||
source /tmp/mailinabox.prev.conf
|
||||
rm -f /tmp/mailinabox.prev.conf
|
||||
else
|
||||
FIRST_TIME_SETUP=1
|
||||
fi
|
||||
|
||||
# Put a start script in a global location. We tell the user to run 'mailinabox'
|
||||
@@ -45,59 +51,38 @@ source setup/start.sh
|
||||
EOF
|
||||
chmod +x /usr/local/bin/mailinabox
|
||||
|
||||
# Ask the user for the PRIMARY_HOSTNAME, PUBLIC_IP, PUBLIC_IPV6, and CSR_COUNTRY
|
||||
# Ask the user for the PRIMARY_HOSTNAME, PUBLIC_IP, and PUBLIC_IPV6,
|
||||
# if values have not already been set in environment variables. When running
|
||||
# non-interactively, be sure to set values for all!
|
||||
# non-interactively, be sure to set values for all! Also sets STORAGE_USER and
|
||||
# STORAGE_ROOT.
|
||||
source setup/questions.sh
|
||||
|
||||
# Automatic configuration, e.g. as used in our Vagrant configuration.
|
||||
if [ "$PUBLIC_IP" = "auto" ]; then
|
||||
# Use a public API to get our public IP address, or fall back to local network configuration.
|
||||
PUBLIC_IP=$(get_publicip_from_web_service 4 || get_default_privateip 4)
|
||||
fi
|
||||
if [ "$PUBLIC_IPV6" = "auto" ]; then
|
||||
# Use a public API to get our public IPv6 address, or fall back to local network configuration.
|
||||
PUBLIC_IPV6=$(get_publicip_from_web_service 6 || get_default_privateip 6)
|
||||
fi
|
||||
if [ "$PRIMARY_HOSTNAME" = "auto-easy" ]; then
|
||||
# Generate a probably-unique subdomain under our justtesting.email domain.
|
||||
PRIMARY_HOSTNAME=`echo $PUBLIC_IP | sha1sum | cut -c1-5`.justtesting.email
|
||||
fi
|
||||
|
||||
# Show the configuration, since the user may have not entered it manually.
|
||||
echo
|
||||
echo "Primary Hostname: $PRIMARY_HOSTNAME"
|
||||
echo "Public IP Address: $PUBLIC_IP"
|
||||
if [ ! -z "$PUBLIC_IPV6" ]; then
|
||||
echo "Public IPv6 Address: $PUBLIC_IPV6"
|
||||
fi
|
||||
if [ "$PRIVATE_IP" != "$PUBLIC_IP" ]; then
|
||||
echo "Private IP Address: $PRIVATE_IP"
|
||||
fi
|
||||
if [ "$PRIVATE_IPV6" != "$PUBLIC_IPV6" ]; then
|
||||
echo "Private IPv6 Address: $PRIVATE_IPV6"
|
||||
fi
|
||||
if [ -f /usr/bin/git ]; then
|
||||
echo "Mail-in-a-Box Version: " $(git describe)
|
||||
fi
|
||||
echo
|
||||
|
||||
# Run some network checks to make sure setup on this machine makes sense.
|
||||
if [ -z "$SKIP_NETWORK_CHECKS" ]; then
|
||||
. setup/network-checks.sh
|
||||
# Skip on existing installs since we don't want this to block the ability to
|
||||
# upgrade, and these checks are also in the control panel status checks.
|
||||
if [ -z "${DEFAULT_PRIMARY_HOSTNAME:-}" ]; then
|
||||
if [ -z "${SKIP_NETWORK_CHECKS:-}" ]; then
|
||||
source setup/network-checks.sh
|
||||
fi
|
||||
fi
|
||||
|
||||
# Create the user named "user-data" and store all persistent user
|
||||
# data (mailboxes, etc.) in that user's home directory.
|
||||
if [ -z "$STORAGE_ROOT" ]; then
|
||||
STORAGE_USER=user-data
|
||||
if [ ! -d /home/$STORAGE_USER ]; then useradd -m $STORAGE_USER; fi
|
||||
STORAGE_ROOT=/home/$STORAGE_USER
|
||||
# Create the STORAGE_USER and STORAGE_ROOT directory if they don't already exist.
|
||||
# If the STORAGE_ROOT is missing the mailinabox.version file that lists a
|
||||
# migration (schema) number for the files stored there, assume this is a fresh
|
||||
# installation to that directory and write the file to contain the current
|
||||
# migration number for this version of Mail-in-a-Box.
|
||||
if ! id -u $STORAGE_USER >/dev/null 2>&1; then
|
||||
useradd -m $STORAGE_USER
|
||||
fi
|
||||
if [ ! -d $STORAGE_ROOT ]; then
|
||||
mkdir -p $STORAGE_ROOT
|
||||
fi
|
||||
if [ ! -f $STORAGE_ROOT/mailinabox.version ]; then
|
||||
echo $(setup/migrate.py --current) > $STORAGE_ROOT/mailinabox.version
|
||||
chown $STORAGE_USER.$STORAGE_USER $STORAGE_ROOT/mailinabox.version
|
||||
fi
|
||||
|
||||
|
||||
# Save the global options in /etc/mailinabox.conf so that standalone
|
||||
# tools know where to look for data.
|
||||
cat > /etc/mailinabox.conf << EOF;
|
||||
@@ -108,7 +93,6 @@ PUBLIC_IP=$PUBLIC_IP
|
||||
PUBLIC_IPV6=$PUBLIC_IPV6
|
||||
PRIVATE_IP=$PRIVATE_IP
|
||||
PRIVATE_IPV6=$PRIVATE_IPV6
|
||||
CSR_COUNTRY=$CSR_COUNTRY
|
||||
EOF
|
||||
|
||||
# Start service configuration.
|
||||
@@ -122,18 +106,44 @@ source setup/dkim.sh
|
||||
source setup/spamassassin.sh
|
||||
source setup/web.sh
|
||||
source setup/webmail.sh
|
||||
source setup/owncloud.sh
|
||||
source setup/nextcloud.sh
|
||||
source setup/zpush.sh
|
||||
source setup/management.sh
|
||||
source setup/munin.sh
|
||||
|
||||
# Write the DNS and nginx configuration files.
|
||||
sleep 5 # wait for the daemon to start
|
||||
curl -s -d POSTDATA --user $(</var/lib/mailinabox/api.key): http://127.0.0.1:10222/dns/update
|
||||
curl -s -d POSTDATA --user $(</var/lib/mailinabox/api.key): http://127.0.0.1:10222/web/update
|
||||
# Wait for the management daemon to start...
|
||||
until nc -z -w 4 127.0.0.1 10222
|
||||
do
|
||||
echo Waiting for the Mail-in-a-Box management daemon to start...
|
||||
sleep 2
|
||||
done
|
||||
|
||||
# ...and then have it write the DNS and nginx configuration files and start those
|
||||
# services.
|
||||
tools/dns_update
|
||||
tools/web_update
|
||||
|
||||
# Give fail2ban another restart. The log files may not all have been present when
|
||||
# fail2ban was first configured, but they should exist now.
|
||||
restart_service fail2ban
|
||||
|
||||
# If there aren't any mail users yet, create one.
|
||||
source setup/firstuser.sh
|
||||
|
||||
# Register with Let's Encrypt, including agreeing to the Terms of Service.
|
||||
# We'd let certbot ask the user interactively, but when this script is
|
||||
# run in the recommended curl-pipe-to-bash method there is no TTY and
|
||||
# certbot will fail if it tries to ask.
|
||||
if [ ! -d $STORAGE_ROOT/ssl/lets_encrypt/accounts/acme-v02.api.letsencrypt.org/ ]; then
|
||||
echo
|
||||
echo "-----------------------------------------------"
|
||||
echo "Mail-in-a-Box uses Let's Encrypt to provision free SSL/TLS certificates"
|
||||
echo "to enable HTTPS connections to your box. We're automatically"
|
||||
echo "agreeing you to their subscriber agreement. See https://letsencrypt.org."
|
||||
echo
|
||||
certbot register --register-unsafely-without-email --agree-tos --config-dir $STORAGE_ROOT/ssl/lets_encrypt
|
||||
fi
|
||||
|
||||
# Done.
|
||||
echo
|
||||
echo "-----------------------------------------------"
|
||||
@@ -146,17 +156,19 @@ if management/status_checks.py --check-primary-hostname; then
|
||||
# Show the nice URL if it appears to be resolving and has a valid certificate.
|
||||
echo https://$PRIMARY_HOSTNAME/admin
|
||||
echo
|
||||
echo If you have a DNS problem use the box\'s IP address and check the SSL fingerprint:
|
||||
echo https://$PUBLIC_IP/admin
|
||||
echo "If you have a DNS problem put the box's IP address in the URL"
|
||||
echo "(https://$PUBLIC_IP/admin) but then check the TLS fingerprint:"
|
||||
openssl x509 -in $STORAGE_ROOT/ssl/ssl_certificate.pem -noout -fingerprint -sha256\
|
||||
| sed "s/SHA256 Fingerprint=//"
|
||||
else
|
||||
echo https://$PUBLIC_IP/admin
|
||||
echo
|
||||
echo You will be alerted that the website has an invalid certificate. Check that
|
||||
echo the certificate fingerprint matches:
|
||||
echo
|
||||
fi
|
||||
openssl x509 -in $STORAGE_ROOT/ssl/ssl_certificate.pem -noout -fingerprint \
|
||||
| sed "s/SHA1 Fingerprint=//"
|
||||
openssl x509 -in $STORAGE_ROOT/ssl/ssl_certificate.pem -noout -fingerprint -sha256\
|
||||
| sed "s/SHA256 Fingerprint=//"
|
||||
echo
|
||||
echo Then you can confirm the security exception and continue.
|
||||
echo
|
||||
fi
|
||||
|
||||
301
setup/system.sh
301
setup/system.sh
@@ -1,15 +1,111 @@
|
||||
source /etc/mailinabox.conf
|
||||
source setup/functions.sh # load our functions
|
||||
|
||||
# Basic System Configuration
|
||||
# -------------------------
|
||||
|
||||
# ### Install Packages
|
||||
# ### Set hostname of the box
|
||||
|
||||
# Update system packages to make sure we have the latest upstream versions of things from Ubuntu.
|
||||
# If the hostname is not correctly resolvable sudo can't be used. This will result in
|
||||
# errors during the install
|
||||
#
|
||||
# First set the hostname in the configuration file, then activate the setting
|
||||
|
||||
echo $PRIMARY_HOSTNAME > /etc/hostname
|
||||
hostname $PRIMARY_HOSTNAME
|
||||
|
||||
# ### Fix permissions
|
||||
|
||||
# The default Ubuntu Bionic image on Scaleway throws warnings during setup about incorrect
|
||||
# permissions (group writeable) set on the following directories.
|
||||
|
||||
chmod g-w /etc /etc/default /usr
|
||||
|
||||
# ### Add swap space to the system
|
||||
|
||||
# If the physical memory of the system is below 2GB it is wise to create a
|
||||
# swap file. This will make the system more resiliant to memory spikes and
|
||||
# prevent for instance spam filtering from crashing
|
||||
|
||||
# We will create a 1G file, this should be a good balance between disk usage
|
||||
# and buffers for the system. We will only allocate this file if there is more
|
||||
# than 5GB of disk space available
|
||||
|
||||
# The following checks are performed:
|
||||
# - Check if swap is currently mountend by looking at /proc/swaps
|
||||
# - Check if the user intents to activate swap on next boot by checking fstab entries.
|
||||
# - Check if a swapfile already exists
|
||||
# - Check if the root file system is not btrfs, might be an incompatible version with
|
||||
# swapfiles. User should hanle it them selves.
|
||||
# - Check the memory requirements
|
||||
# - Check available diskspace
|
||||
|
||||
# See https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04
|
||||
# for reference
|
||||
|
||||
SWAP_MOUNTED=$(cat /proc/swaps | tail -n+2)
|
||||
SWAP_IN_FSTAB=$(grep "swap" /etc/fstab || /bin/true)
|
||||
ROOT_IS_BTRFS=$(grep "\/ .*btrfs" /proc/mounts || /bin/true)
|
||||
TOTAL_PHYSICAL_MEM=$(head -n 1 /proc/meminfo | awk '{print $2}' || /bin/true)
|
||||
AVAILABLE_DISK_SPACE=$(df / --output=avail | tail -n 1)
|
||||
if
|
||||
[ -z "$SWAP_MOUNTED" ] &&
|
||||
[ -z "$SWAP_IN_FSTAB" ] &&
|
||||
[ ! -e /swapfile ] &&
|
||||
[ -z "$ROOT_IS_BTRFS" ] &&
|
||||
[ $TOTAL_PHYSICAL_MEM -lt 1900000 ] &&
|
||||
[ $AVAILABLE_DISK_SPACE -gt 5242880 ]
|
||||
then
|
||||
echo "Adding a swap file to the system..."
|
||||
|
||||
# Allocate and activate the swap file. Allocate in 1KB chuncks
|
||||
# doing it in one go, could fail on low memory systems
|
||||
dd if=/dev/zero of=/swapfile bs=1024 count=$[1024*1024] status=none
|
||||
if [ -e /swapfile ]; then
|
||||
chmod 600 /swapfile
|
||||
hide_output mkswap /swapfile
|
||||
swapon /swapfile
|
||||
fi
|
||||
|
||||
# Check if swap is mounted then activate on boot
|
||||
if swapon -s | grep -q "\/swapfile"; then
|
||||
echo "/swapfile none swap sw 0 0" >> /etc/fstab
|
||||
else
|
||||
echo "ERROR: Swap allocation failed"
|
||||
fi
|
||||
fi
|
||||
|
||||
# ### Add PPAs.
|
||||
|
||||
# We install some non-standard Ubuntu packages maintained by other
|
||||
# third-party providers. First ensure add-apt-repository is installed.
|
||||
|
||||
if [ ! -f /usr/bin/add-apt-repository ]; then
|
||||
echo "Installing add-apt-repository..."
|
||||
hide_output apt-get update
|
||||
apt_install software-properties-common
|
||||
fi
|
||||
|
||||
# Install the certbot PPA.
|
||||
hide_output add-apt-repository -y ppa:certbot/certbot
|
||||
|
||||
# ### Update Packages
|
||||
|
||||
# Update system packages to make sure we have the latest upstream versions
|
||||
# of things from Ubuntu, as well as the directory of packages provide by the
|
||||
# PPAs so we can install those packages later.
|
||||
|
||||
echo Updating system packages...
|
||||
hide_output apt-get update
|
||||
hide_output apt-get -y upgrade
|
||||
apt_get_quiet upgrade
|
||||
|
||||
# Old kernels pile up over time and take up a lot of disk space, and because of Mail-in-a-Box
|
||||
# changes there may be other packages that are no longer needed. Clear out anything apt knows
|
||||
# is safe to delete.
|
||||
|
||||
apt_get_quiet autoremove
|
||||
|
||||
# ### Install System Packages
|
||||
|
||||
# Install basic utilities.
|
||||
#
|
||||
@@ -17,23 +113,132 @@ hide_output apt-get -y upgrade
|
||||
# when generating random numbers for private keys (e.g. during
|
||||
# ldns-keygen).
|
||||
# * unattended-upgrades: Apt tool to install security updates automatically.
|
||||
# * cron: Runs background processes periodically.
|
||||
# * ntp: keeps the system time correct
|
||||
# * fail2ban: scans log files for repeated failed login attempts and blocks the remote IP at the firewall
|
||||
# * netcat-openbsd: `nc` command line networking tool
|
||||
# * git: we install some things directly from github
|
||||
# * sudo: allows privileged users to execute commands as root without being root
|
||||
# * coreutils: includes `nproc` tool to report number of processors
|
||||
# * coreutils: includes `nproc` tool to report number of processors, mktemp
|
||||
# * bc: allows us to do math to compute sane defaults
|
||||
|
||||
echo Installing system packages...
|
||||
apt_install python3 python3-dev python3-pip \
|
||||
wget curl sudo coreutils bc \
|
||||
haveged unattended-upgrades ntp fail2ban
|
||||
netcat-openbsd wget curl git sudo coreutils bc \
|
||||
haveged pollinate unzip \
|
||||
unattended-upgrades cron ntp fail2ban rsyslog
|
||||
|
||||
# ### Suppress Upgrade Prompts
|
||||
# When Ubuntu 20 comes out, we don't want users to be prompted to upgrade,
|
||||
# because we don't yet support it.
|
||||
if [ -f /etc/update-manager/release-upgrades ]; then
|
||||
tools/editconf.py /etc/update-manager/release-upgrades Prompt=never
|
||||
rm -f /var/lib/ubuntu-release-upgrader/release-upgrade-available
|
||||
fi
|
||||
|
||||
# ### Set the system timezone
|
||||
#
|
||||
# Some systems are missing /etc/timezone, which we cat into the configs for
|
||||
# Z-Push and ownCloud, so we need to set it to something. Daily cron tasks
|
||||
# like the system backup are run at a time tied to the system timezone, so
|
||||
# letting the user choose will help us identify the right time to do those
|
||||
# things (i.e. late at night in whatever timezone the user actually lives
|
||||
# in).
|
||||
#
|
||||
# However, changing the timezone once it is set seems to confuse fail2ban
|
||||
# and requires restarting fail2ban (done below in the fail2ban
|
||||
# section) and syslog (see #328). There might be other issues, and it's
|
||||
# not likely the user will want to change this, so we only ask on first
|
||||
# setup.
|
||||
if [ -z "${NONINTERACTIVE:-}" ]; then
|
||||
if [ ! -f /etc/timezone ] || [ ! -z ${FIRST_TIME_SETUP:-} ]; then
|
||||
# If the file is missing or this is the user's first time running
|
||||
# Mail-in-a-Box setup, run the interactive timezone configuration
|
||||
# tool.
|
||||
dpkg-reconfigure tzdata
|
||||
restart_service rsyslog
|
||||
fi
|
||||
else
|
||||
# This is a non-interactive setup so we can't ask the user.
|
||||
# If /etc/timezone is missing, set it to UTC.
|
||||
if [ ! -f /etc/timezone ]; then
|
||||
echo "Setting timezone to UTC."
|
||||
echo "Etc/UTC" > /etc/timezone
|
||||
restart_service rsyslog
|
||||
fi
|
||||
fi
|
||||
|
||||
# ### Seed /dev/urandom
|
||||
#
|
||||
# /dev/urandom is used by various components for generating random bytes for
|
||||
# encryption keys and passwords:
|
||||
#
|
||||
# * TLS private key (see `ssl.sh`, which calls `openssl genrsa`)
|
||||
# * DNSSEC signing keys (see `dns.sh`)
|
||||
# * our management server's API key (via Python's os.urandom method)
|
||||
# * Roundcube's SECRET_KEY (`webmail.sh`)
|
||||
#
|
||||
# Why /dev/urandom? It's the same as /dev/random, except that it doesn't wait
|
||||
# for a constant new stream of entropy. In practice, we only need a little
|
||||
# entropy at the start to get going. After that, we can safely pull a random
|
||||
# stream from /dev/urandom and not worry about how much entropy has been
|
||||
# added to the stream. (http://www.2uo.de/myths-about-urandom/) So we need
|
||||
# to worry about /dev/urandom being seeded properly (which is also an issue
|
||||
# for /dev/random), but after that /dev/urandom is superior to /dev/random
|
||||
# because it's faster and doesn't block indefinitely to wait for hardware
|
||||
# entropy. Note that `openssl genrsa` even uses `/dev/urandom`, and if it's
|
||||
# good enough for generating an RSA private key, it's good enough for anything
|
||||
# else we may need.
|
||||
#
|
||||
# Now about that seeding issue....
|
||||
#
|
||||
# /dev/urandom is seeded from "the uninitialized contents of the pool buffers when
|
||||
# the kernel starts, the startup clock time in nanosecond resolution,...and
|
||||
# entropy saved across boots to a local file" as well as the order of
|
||||
# execution of concurrent accesses to /dev/urandom. (Heninger et al 2012,
|
||||
# https://factorable.net/weakkeys12.conference.pdf) But when memory is zeroed,
|
||||
# the system clock is reset on boot, /etc/init.d/urandom has not yet run, or
|
||||
# the machine is single CPU or has no concurrent accesses to /dev/urandom prior
|
||||
# to this point, /dev/urandom may not be seeded well. After this, /dev/urandom
|
||||
# draws from the same entropy sources as /dev/random, but it doesn't block or
|
||||
# issue any warnings if no entropy is actually available. (http://www.2uo.de/myths-about-urandom/)
|
||||
# Entropy might not be readily available because this machine has no user input
|
||||
# devices (common on servers!) and either no hard disk or not enough IO has
|
||||
# ocurred yet --- although haveged tries to mitigate this. So there's a good chance
|
||||
# that accessing /dev/urandom will not be drawing from any hardware entropy and under
|
||||
# a perfect-storm circumstance where the other seeds are meaningless, /dev/urandom
|
||||
# may not be seeded at all.
|
||||
#
|
||||
# The first thing we'll do is block until we can seed /dev/urandom with enough
|
||||
# hardware entropy to get going, by drawing from /dev/random. haveged makes this
|
||||
# less likely to stall for very long.
|
||||
|
||||
echo Initializing system random number generator...
|
||||
dd if=/dev/random of=/dev/urandom bs=1 count=32 2> /dev/null
|
||||
|
||||
# This is supposedly sufficient. But because we're not sure if hardware entropy
|
||||
# is really any good on virtualized systems, we'll also seed from Ubuntu's
|
||||
# pollinate servers:
|
||||
|
||||
pollinate -q -r
|
||||
|
||||
# Between these two, we really ought to be all set.
|
||||
|
||||
# We need an ssh key to store backups via rsync, if it doesn't exist create one
|
||||
if [ ! -f /root/.ssh/id_rsa_miab ]; then
|
||||
echo 'Creating SSH key for backup…'
|
||||
ssh-keygen -t rsa -b 2048 -a 100 -f /root/.ssh/id_rsa_miab -N '' -q
|
||||
fi
|
||||
|
||||
# ### Package maintenance
|
||||
#
|
||||
# Allow apt to install system updates automatically every day.
|
||||
|
||||
cat > /etc/apt/apt.conf.d/02periodic <<EOF;
|
||||
APT::Periodic::MaxAge "7";
|
||||
APT::Periodic::Update-Package-Lists "1";
|
||||
APT::Periodic::Unattended-Upgrade "1";
|
||||
APT::Periodic::Verbose "1";
|
||||
APT::Periodic::Verbose "0";
|
||||
EOF
|
||||
|
||||
# ### Firewall
|
||||
@@ -41,7 +246,7 @@ EOF
|
||||
# Various virtualized environments like Docker and some VPSs don't provide #NODOC
|
||||
# a kernel that supports iptables. To avoid error-like output in these cases, #NODOC
|
||||
# we skip this if the user sets DISABLE_FIREWALL=1. #NODOC
|
||||
if [ -z "$DISABLE_FIREWALL" ]; then
|
||||
if [ -z "${DISABLE_FIREWALL:-}" ]; then
|
||||
# Install `ufw` which provides a simple firewall configuration.
|
||||
apt_install ufw
|
||||
|
||||
@@ -66,42 +271,84 @@ fi #NODOC
|
||||
|
||||
# ### Local DNS Service
|
||||
|
||||
# Install a local DNS server, rather than using the DNS server provided by the
|
||||
# ISP's network configuration.
|
||||
# Install a local recursive DNS server --- i.e. for DNS queries made by
|
||||
# local services running on this machine.
|
||||
#
|
||||
# We do this to ensure that DNS queries
|
||||
# that *we* make (i.e. looking up other external domains) perform DNSSEC checks.
|
||||
# We could use Google's Public DNS, but we don't want to create a dependency on
|
||||
# Google per our goals of decentralization. `bind9`, as packaged for Ubuntu, has
|
||||
# DNSSEC enabled by default via "dnssec-validation auto".
|
||||
# (This is unrelated to the box's public, non-recursive DNS server that
|
||||
# answers remote queries about domain names hosted on this box. For that
|
||||
# see dns.sh.)
|
||||
#
|
||||
# So we'll be running `bind9` bound to 127.0.0.1 for locally-issued DNS queries
|
||||
# and `nsd` bound to the public ethernet interface for remote DNS queries asking
|
||||
# about our domain names. `nsd` is configured later.
|
||||
# The default systemd-resolved service provides local DNS name resolution. By default it
|
||||
# is a recursive stub nameserver, which means it simply relays requests to an
|
||||
# external nameserver, usually provided by your ISP or configured in /etc/systemd/resolved.conf.
|
||||
#
|
||||
# This won't work for us for three reasons.
|
||||
#
|
||||
# 1) We have higher security goals --- we want DNSSEC to be enforced on all
|
||||
# DNS queries (some upstream DNS servers do, some don't).
|
||||
# 2) We will configure postfix to use DANE, which uses DNSSEC to find TLS
|
||||
# certificates for remote servers. DNSSEC validation *must* be performed
|
||||
# locally because we can't trust an unencrypted connection to an external
|
||||
# DNS server.
|
||||
# 3) DNS-based mail server blacklists (RBLs) typically block large ISP
|
||||
# DNS servers because they only provide free data to small users. Since
|
||||
# we use RBLs to block incoming mail from blacklisted IP addresses,
|
||||
# we have to run our own DNS server. See #1424.
|
||||
#
|
||||
# systemd-resolved has a setting to perform local DNSSEC validation on all
|
||||
# requests (in /etc/systemd/resolved.conf, set DNSSEC=yes), but because it's
|
||||
# a stub server the main part of a request still goes through an upstream
|
||||
# DNS server, which won't work for RBLs. So we really need a local recursive
|
||||
# nameserver.
|
||||
#
|
||||
# We'll install `bind9`, which as packaged for Ubuntu, has DNSSEC enabled by default via "dnssec-validation auto".
|
||||
# We'll have it be bound to 127.0.0.1 so that it does not interfere with
|
||||
# the public, recursive nameserver `nsd` bound to the public ethernet interfaces.
|
||||
#
|
||||
# About the settings:
|
||||
#
|
||||
# * RESOLVCONF=yes will have `bind9` take over /etc/resolv.conf to tell
|
||||
# local services that DNS queries are handled on localhost.
|
||||
# * Adding -4 to OPTIONS will have `bind9` not listen on IPv6 addresses
|
||||
# so that we're sure there's no conflict with nsd, our public domain
|
||||
# name server, on IPV6.
|
||||
# * The listen-on directive in named.conf.options restricts `bind9` to
|
||||
# binding to the loopback interface instead of all interfaces.
|
||||
apt_install bind9 resolvconf
|
||||
apt_install bind9
|
||||
tools/editconf.py /etc/default/bind9 \
|
||||
RESOLVCONF=yes \
|
||||
"OPTIONS=\"-u bind -4\""
|
||||
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.
|
||||
sed -i "s/^}/\n\tlisten-on { 127.0.0.1; };\n}/" /etc/bind/named.conf.options
|
||||
fi
|
||||
if [ -f /etc/resolvconf/resolv.conf.d/original ]; then
|
||||
echo "Archiving old resolv.conf (was /etc/resolvconf/resolv.conf.d/original, now /etc/resolvconf/resolv.conf.original)." #NODOC
|
||||
mv /etc/resolvconf/resolv.conf.d/original /etc/resolvconf/resolv.conf.original #NODOC
|
||||
fi
|
||||
|
||||
# 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
|
||||
# systemd-resolved will read it for DNS servers to use. Put in 127.0.0.1,
|
||||
# which is where bind9 will be running. Obviously don't do this before
|
||||
# installing bind9 or else apt won't be able to resolve a server to
|
||||
# download bind9 from.
|
||||
rm -f /etc/resolv.conf
|
||||
tools/editconf.py /etc/systemd/resolved.conf DNSStubListener=no
|
||||
echo "nameserver 127.0.0.1" > /etc/resolv.conf
|
||||
|
||||
# Restart the DNS services.
|
||||
|
||||
restart_service bind9
|
||||
restart_service resolvconf
|
||||
systemctl restart systemd-resolved
|
||||
|
||||
# ### Fail2Ban Service
|
||||
|
||||
# Configure the Fail2Ban installation to prevent dumb bruce-force attacks against dovecot, postfix, ssh, etc.
|
||||
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
|
||||
cat conf/fail2ban/jails.conf \
|
||||
| sed "s/PUBLIC_IP/$PUBLIC_IP/g" \
|
||||
| sed "s#STORAGE_ROOT#$STORAGE_ROOT#" \
|
||||
> /etc/fail2ban/jail.d/mailinabox.conf
|
||||
cp -f conf/fail2ban/filter.d/* /etc/fail2ban/filter.d/
|
||||
|
||||
# On first installation, the log files that the jails look at don't all exist.
|
||||
# e.g., The roundcube error log isn't normally created until someone logs into
|
||||
# Roundcube for the first time. This causes fail2ban to fail to start. Later
|
||||
# scripts will ensure the files exist and then fail2ban is given another
|
||||
# restart at the very end of setup.
|
||||
restart_service fail2ban
|
||||
|
||||
57
setup/web.sh
57
setup/web.sh
@@ -17,23 +17,43 @@ fi
|
||||
#
|
||||
# Turn off nginx's default website.
|
||||
|
||||
apt_install nginx php5-fpm
|
||||
echo "Installing Nginx (web server)..."
|
||||
|
||||
apt_install nginx php-cli php-fpm
|
||||
|
||||
rm -f /etc/nginx/sites-enabled/default
|
||||
|
||||
# Copy in a nginx configuration file for common and best-practices
|
||||
# SSL settings from @konklone. Replace STORAGE_ROOT so it can find
|
||||
# the DH params.
|
||||
rm -f /etc/nginx/nginx-ssl.conf # we used to put it here
|
||||
sed "s#STORAGE_ROOT#$STORAGE_ROOT#" \
|
||||
conf/nginx-ssl.conf > /etc/nginx/nginx-ssl.conf
|
||||
conf/nginx-ssl.conf > /etc/nginx/conf.d/ssl.conf
|
||||
|
||||
# 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
|
||||
# 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
|
||||
# even at 64, a 58-character domain name won't work (#93), so now
|
||||
# we're going up to 128.
|
||||
tools/editconf.py /etc/nginx/nginx.conf -s \
|
||||
server_names_hash_bucket_size="64;"
|
||||
server_names_hash_bucket_size="128;"
|
||||
|
||||
# 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 ';' \
|
||||
expose_php=Off
|
||||
|
||||
# Set PHPs default charset to UTF-8, since we use it. See #367.
|
||||
tools/editconf.py /etc/php/7.2/fpm/php.ini -c ';' \
|
||||
default_charset="UTF-8"
|
||||
|
||||
# Switch from the dynamic process manager to the ondemand manager see #1216
|
||||
tools/editconf.py /etc/php/7.2/fpm/pool.d/www.conf -c ';' \
|
||||
pm=ondemand
|
||||
|
||||
# Bump up PHP's max_children to support more concurrent connections
|
||||
tools/editconf.py /etc/php5/fpm/pool.d/www.conf -c ';' \
|
||||
tools/editconf.py /etc/php/7.2/fpm/pool.d/www.conf -c ';' \
|
||||
pm.max_children=8
|
||||
|
||||
# Other nginx settings will be configured by the management service
|
||||
@@ -53,6 +73,16 @@ cat conf/ios-profile.xml \
|
||||
> /var/lib/mailinabox/mobileconfig.xml
|
||||
chmod a+r /var/lib/mailinabox/mobileconfig.xml
|
||||
|
||||
# Create the Mozilla Auto-configuration file which is exposed via the
|
||||
# nginx configuration at /.well-known/autoconfig/mail/config-v1.1.xml.
|
||||
# The format of the file is documented at:
|
||||
# https://wiki.mozilla.org/Thunderbird:Autoconfiguration:ConfigFileFormat
|
||||
# and https://developer.mozilla.org/en-US/docs/Mozilla/Thunderbird/Autoconfiguration/FileFormat/HowTo.
|
||||
cat conf/mozilla-autoconfig.xml \
|
||||
| sed "s/PRIMARY_HOSTNAME/$PRIMARY_HOSTNAME/" \
|
||||
> /var/lib/mailinabox/mozilla-autoconfig.xml
|
||||
chmod a+r /var/lib/mailinabox/mozilla-autoconfig.xml
|
||||
|
||||
# make a default homepage
|
||||
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
|
||||
@@ -61,24 +91,9 @@ if [ ! -f $STORAGE_ROOT/www/default/index.html ]; then
|
||||
fi
|
||||
chown -R $STORAGE_USER $STORAGE_ROOT/www
|
||||
|
||||
# We previously installed a custom init script to start the PHP FastCGI daemon. #NODOC
|
||||
# Remove it now that we're using php5-fpm. #NODOC
|
||||
if [ -L /etc/init.d/php-fastcgi ]; then
|
||||
echo "Removing /etc/init.d/php-fastcgi, php5-cgi..." #NODOC
|
||||
rm -f /etc/init.d/php-fastcgi #NODOC
|
||||
hide_output update-rc.d php-fastcgi remove #NODOC
|
||||
apt-get -y purge php5-cgi #NODOC
|
||||
fi
|
||||
|
||||
# Remove obsoleted scripts. #NODOC
|
||||
# exchange-autodiscover is now handled by Z-Push. #NODOC
|
||||
for f in webfinger exchange-autodiscover; do #NODOC
|
||||
rm -f /usr/local/bin/mailinabox-$f.php #NODOC
|
||||
done #NODOC
|
||||
|
||||
# Start services.
|
||||
restart_service nginx
|
||||
restart_service php5-fpm
|
||||
restart_service php7.2-fpm
|
||||
|
||||
# Open ports.
|
||||
ufw_allow http
|
||||
|
||||
137
setup/webmail.sh
137
setup/webmail.sh
@@ -19,86 +19,153 @@ source /etc/mailinabox.conf # load global vars
|
||||
# and then we'll manually install roundcube from source.
|
||||
|
||||
# These dependencies are from `apt-cache showpkg roundcube-core`.
|
||||
echo "Installing Roundcube (webmail)..."
|
||||
apt_install \
|
||||
dbconfig-common \
|
||||
php5 php5-sqlite php5-mcrypt php5-intl php5-json php5-common php-auth php-net-smtp php-net-socket php-net-sieve php-mail-mime php-crypt-gpg php5-gd php5-pspell \
|
||||
tinymce libjs-jquery libjs-jquery-mousewheel libmagic1
|
||||
|
||||
# We used to install Roundcube from Ubuntu, without triggering the dependencies #NODOC
|
||||
# on Apache and MySQL, by downloading the debs and installing them manually. #NODOC
|
||||
# Now that we're beyond that, get rid of those debs before installing from source. #NODOC
|
||||
apt-get purge -qq -y roundcube* #NODOC
|
||||
php-cli php-sqlite3 php-intl php-json php-common php-curl \
|
||||
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.
|
||||
VERSION=1.0.3
|
||||
# Combine the Roundcube version number with the commit hash of plugins to track
|
||||
# whether we have the latest version of everything.
|
||||
VERSION=1.3.9
|
||||
HASH=02850972b416bbfa1c13580f16d06fd7ae2774aa
|
||||
PERSISTENT_LOGIN_VERSION=dc5ca3d3f4415cc41edb2fde533c8a8628a94c76
|
||||
HTML5_NOTIFIER_VERSION=4b370e3cd60dabd2f428a26f45b677ad1b7118d5
|
||||
CARDDAV_VERSION=3.0.3
|
||||
CARDDAV_HASH=d1e3b0d851ffa2c6bd42bf0c04f70d0e1d0d78f8
|
||||
|
||||
UPDATE_KEY=$VERSION:$PERSISTENT_LOGIN_VERSION:$HTML5_NOTIFIER_VERSION:$CARDDAV_VERSION
|
||||
|
||||
# paths that are often reused.
|
||||
RCM_DIR=/usr/local/lib/roundcubemail
|
||||
RCM_PLUGIN_DIR=${RCM_DIR}/plugins
|
||||
RCM_CONFIG=${RCM_DIR}/config/config.inc.php
|
||||
|
||||
needs_update=0 #NODOC
|
||||
if [ ! -f /usr/local/lib/roundcubemail/version ]; then
|
||||
# not installed yet #NODOC
|
||||
needs_update=1 #NODOC
|
||||
elif [[ $VERSION != `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
|
||||
needs_update=1 #NODOC
|
||||
fi
|
||||
if [ $needs_update == 1 ]; then
|
||||
echo installing roudcube webmail $VERSION...
|
||||
rm -f /tmp/roundcube.tgz
|
||||
wget -qO /tmp/roundcube.tgz http://downloads.sourceforge.net/project/roundcubemail/roundcubemail/$VERSION/roundcubemail-$VERSION.tar.gz
|
||||
tar -C /usr/local/lib -zxf /tmp/roundcube.tgz
|
||||
# install roundcube
|
||||
wget_verify \
|
||||
https://github.com/roundcube/roundcubemail/releases/download/$VERSION/roundcubemail-$VERSION-complete.tar.gz \
|
||||
$HASH \
|
||||
/tmp/roundcube.tgz
|
||||
tar -C /usr/local/lib --no-same-owner -zxf /tmp/roundcube.tgz
|
||||
rm -rf /usr/local/lib/roundcubemail
|
||||
mv /usr/local/lib/roundcubemail-$VERSION/ /usr/local/lib/roundcubemail
|
||||
mv /usr/local/lib/roundcubemail-$VERSION/ $RCM_DIR
|
||||
rm -f /tmp/roundcube.tgz
|
||||
echo $VERSION > /usr/local/lib/roundcubemail/version
|
||||
|
||||
# install roundcube persistent_login plugin
|
||||
git_clone https://github.com/mfreiholz/Roundcube-Persistent-Login-Plugin.git $PERSISTENT_LOGIN_VERSION '' ${RCM_PLUGIN_DIR}/persistent_login
|
||||
|
||||
# install roundcube html5_notifier plugin
|
||||
git_clone https://github.com/kitist/html5_notifier.git $HTML5_NOTIFIER_VERSION '' ${RCM_PLUGIN_DIR}/html5_notifier
|
||||
|
||||
# download and verify the full release of the carddav plugin
|
||||
wget_verify \
|
||||
https://github.com/blind-coder/rcmcarddav/releases/download/v${CARDDAV_VERSION}/carddav-${CARDDAV_VERSION}.zip \
|
||||
$CARDDAV_HASH \
|
||||
/tmp/carddav.zip
|
||||
|
||||
# unzip and cleanup
|
||||
unzip -q /tmp/carddav.zip -d ${RCM_PLUGIN_DIR}
|
||||
rm -f /tmp/carddav.zip
|
||||
|
||||
# record the version we've installed
|
||||
echo $UPDATE_KEY > ${RCM_DIR}/version
|
||||
fi
|
||||
|
||||
# ### Configuring Roundcube
|
||||
|
||||
# Generate a safe 24-character secret key of safe characters.
|
||||
SECRET_KEY=$(dd if=/dev/random bs=1 count=18 2>/dev/null | base64 | fold -w 24 | head -n 1)
|
||||
SECRET_KEY=$(dd if=/dev/urandom bs=1 count=18 2>/dev/null | base64 | fold -w 24 | head -n 1)
|
||||
|
||||
# Create a configuration file.
|
||||
#
|
||||
# For security, temp and log files are not stored in the default locations
|
||||
# which are inside the roundcube sources directory. We put them instead
|
||||
# in normal places.
|
||||
cat > /usr/local/lib/roundcubemail/config/config.inc.php <<EOF;
|
||||
cat > $RCM_CONFIG <<EOF;
|
||||
<?php
|
||||
/*
|
||||
* Do not edit. Written by Mail-in-a-Box. Regenerated on updates.
|
||||
*/
|
||||
\$config = array();
|
||||
\$config['log_dir'] = '/var/log/roundcubemail/';
|
||||
\$config['temp_dir'] = '/tmp/roundcubemail/';
|
||||
\$config['temp_dir'] = '/var/tmp/roundcubemail/';
|
||||
\$config['db_dsnw'] = 'sqlite:///$STORAGE_ROOT/mail/roundcube/roundcube.sqlite?mode=0640';
|
||||
\$config['default_host'] = 'ssl://localhost';
|
||||
\$config['default_port'] = 993;
|
||||
\$config['imap_conn_options'] = array(
|
||||
'ssl' => array(
|
||||
'verify_peer' => false,
|
||||
'verify_peer_name' => false,
|
||||
),
|
||||
);
|
||||
\$config['imap_timeout'] = 15;
|
||||
\$config['smtp_server'] = 'tls://localhost';
|
||||
\$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(
|
||||
'ssl' => array(
|
||||
'verify_peer' => false,
|
||||
'verify_peer_name' => false,
|
||||
),
|
||||
);
|
||||
\$config['support_url'] = 'https://mailinabox.email/';
|
||||
\$config['product_name'] = 'Mail-in-a-Box/Roundcube Webmail';
|
||||
\$config['product_name'] = '$PRIMARY_HOSTNAME Webmail';
|
||||
\$config['des_key'] = '$SECRET_KEY';
|
||||
\$config['plugins'] = array('archive', 'zipdownload', 'password', 'managesieve');
|
||||
\$config['skin'] = 'classic';
|
||||
\$config['plugins'] = array('html5_notifier', 'archive', 'zipdownload', 'password', 'managesieve', 'jqueryui', 'persistent_login', 'carddav');
|
||||
\$config['skin'] = 'larry';
|
||||
\$config['login_autocomplete'] = 2;
|
||||
\$config['password_charset'] = 'UTF-8';
|
||||
\$config['junk_mbox'] = 'Spam';
|
||||
?>
|
||||
EOF
|
||||
|
||||
# Configure CardDav
|
||||
cat > ${RCM_PLUGIN_DIR}/carddav/config.inc.php <<EOF;
|
||||
<?php
|
||||
/* Do not edit. Written by Mail-in-a-Box. Regenerated on updates. */
|
||||
\$prefs['_GLOBAL']['hide_preferences'] = true;
|
||||
\$prefs['_GLOBAL']['suppress_version_warning'] = true;
|
||||
\$prefs['ownCloud'] = array(
|
||||
'name' => 'ownCloud',
|
||||
'username' => '%u', // login username
|
||||
'password' => '%p', // login password
|
||||
'url' => 'https://${PRIMARY_HOSTNAME}/cloud/remote.php/carddav/addressbooks/%u/contacts',
|
||||
'active' => true,
|
||||
'readonly' => false,
|
||||
'refresh_time' => '02:00:00',
|
||||
'fixed' => array('username','password'),
|
||||
'preemptive_auth' => '1',
|
||||
'hide' => false,
|
||||
);
|
||||
?>
|
||||
EOF
|
||||
|
||||
# Create writable directories.
|
||||
mkdir -p /var/log/roundcubemail /tmp/roundcubemail $STORAGE_ROOT/mail/roundcube
|
||||
chown -R www-data.www-data /var/log/roundcubemail /tmp/roundcubemail $STORAGE_ROOT/mail/roundcube
|
||||
mkdir -p /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.
|
||||
sudo -u www-data touch /var/log/roundcubemail/errors
|
||||
|
||||
# Password changing plugin settings
|
||||
# The config comes empty by default, so we need the settings
|
||||
# we're not planning to change in config.inc.dist...
|
||||
cp /usr/local/lib/roundcubemail/plugins/password/config.inc.php.dist \
|
||||
/usr/local/lib/roundcubemail/plugins/password/config.inc.php
|
||||
cp ${RCM_PLUGIN_DIR}/password/config.inc.php.dist \
|
||||
${RCM_PLUGIN_DIR}/password/config.inc.php
|
||||
|
||||
tools/editconf.py /usr/local/lib/roundcubemail/plugins/password/config.inc.php \
|
||||
"\$config['password_minimum_length']=6;" \
|
||||
tools/editconf.py ${RCM_PLUGIN_DIR}/password/config.inc.php \
|
||||
"\$config['password_minimum_length']=8;" \
|
||||
"\$config['password_db_dsn']='sqlite:///$STORAGE_ROOT/mail/users.sqlite';" \
|
||||
"\$config['password_query']='UPDATE users SET password=%D WHERE email=%u';" \
|
||||
"\$config['password_dovecotpw']='/usr/bin/doveadm pw';" \
|
||||
@@ -115,6 +182,16 @@ chmod 775 $STORAGE_ROOT/mail
|
||||
chown root.www-data $STORAGE_ROOT/mail/users.sqlite
|
||||
chmod 664 $STORAGE_ROOT/mail/users.sqlite
|
||||
|
||||
# Fix Carddav permissions:
|
||||
chown -f -R root.www-data ${RCM_PLUGIN_DIR}/carddav
|
||||
# root.www-data need all permissions, others only read
|
||||
chmod -R 774 ${RCM_PLUGIN_DIR}/carddav
|
||||
|
||||
# Run Roundcube database migration script (database is created if it does not exist)
|
||||
${RCM_DIR}/bin/updatedb.sh --dir ${RCM_DIR}/SQL --package roundcube
|
||||
chown www-data:www-data $STORAGE_ROOT/mail/roundcube/roundcube.sqlite
|
||||
chmod 664 $STORAGE_ROOT/mail/roundcube/roundcube.sqlite
|
||||
|
||||
# Enable PHP modules.
|
||||
php5enmod mcrypt
|
||||
restart_service php5-fpm
|
||||
phpenmod -v php mcrypt imap
|
||||
restart_service php7.2-fpm
|
||||
|
||||
@@ -15,39 +15,45 @@ source /etc/mailinabox.conf # load global vars
|
||||
|
||||
# Prereqs.
|
||||
|
||||
echo "Installing Z-Push (Exchange/ActiveSync server)..."
|
||||
apt_install \
|
||||
php-soap php5-imap libawl-php php5-xsl
|
||||
php-soap php-imap libawl-php php-xsl
|
||||
|
||||
php5enmod imap
|
||||
phpenmod -v php imap
|
||||
|
||||
# Copy Z-Push into place.
|
||||
TARGETHASH=d0cd5a47c53afac5c3b287006dc8a48a1c4ffcd5
|
||||
VERSION=2.5.0
|
||||
TARGETHASH=30ce5c1af3f10939036361b6032d1187651b621e
|
||||
needs_update=0 #NODOC
|
||||
if [ ! -f /usr/local/lib/z-push/version ]; then
|
||||
needs_update=1 #NODOC
|
||||
elif [[ $TARGETHASH != `cat /usr/local/lib/z-push/version` ]]; then
|
||||
elif [[ $VERSION != `cat /usr/local/lib/z-push/version` ]]; then
|
||||
# checks if the version
|
||||
needs_update=1 #NODOC
|
||||
fi
|
||||
if [ $needs_update == 1 ]; then
|
||||
rm -rf /usr/local/lib/z-push
|
||||
rm -f /tmp/zpush-repo
|
||||
echo installing z-push \(fmbiete fork\)...
|
||||
git clone -q https://github.com/fmbiete/Z-Push-contrib /tmp/zpush-repo
|
||||
(cd /tmp/zpush-repo/; git checkout -q $TARGETHASH;)
|
||||
rm -rf /tmp/zpush-repo/.git
|
||||
mv /tmp/zpush-repo /usr/local/lib/z-push
|
||||
# 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
|
||||
|
||||
# Extract into place.
|
||||
rm -rf /usr/local/lib/z-push /tmp/z-push
|
||||
unzip -q /tmp/z-push.zip -d /tmp/z-push
|
||||
mv /tmp/z-push/src /usr/local/lib/z-push
|
||||
rm -rf /tmp/z-push.zip /tmp/z-push
|
||||
|
||||
rm -f /usr/sbin/z-push-{admin,top}
|
||||
ln -s /usr/local/lib/z-push/z-push-admin.php /usr/sbin/z-push-admin
|
||||
ln -s /usr/local/lib/z-push/z-push-top.php /usr/sbin/z-push-top
|
||||
rm -f /tmp/zpush-repo
|
||||
echo $TARGETHASH > /usr/local/lib/z-push/version
|
||||
echo $VERSION > /usr/local/lib/z-push/version
|
||||
fi
|
||||
|
||||
# Configure default config.
|
||||
sed -i "s^define('TIMEZONE', .*^define('TIMEZONE', '$(cat /etc/timezone)');^" /usr/local/lib/z-push/config.php
|
||||
sed -i "s/define('BACKEND_PROVIDER', .*/define('BACKEND_PROVIDER', 'BackendCombined');/" /usr/local/lib/z-push/config.php
|
||||
sed -i "s/define('USE_FULLEMAIL_FOR_LOGIN', .*/define('USE_FULLEMAIL_FOR_LOGIN', true);/" /usr/local/lib/z-push/config.php
|
||||
sed -i "s/define('LOG_MEMORY_PROFILER', .*/define('LOG_MEMORY_PROFILER', false);/" /usr/local/lib/z-push/config.php
|
||||
sed -i "s/define('BUG68532FIXED', .*/define('BUG68532FIXED', false);/" /usr/local/lib/z-push/config.php
|
||||
sed -i "s/define('LOGLEVEL', .*/define('LOGLEVEL', LOGLEVEL_ERROR);/" /usr/local/lib/z-push/config.php
|
||||
|
||||
# Configure BACKEND
|
||||
rm -f /usr/local/lib/z-push/backend/combined/config.php
|
||||
@@ -56,6 +62,7 @@ cp conf/zpush/backend_combined.php /usr/local/lib/z-push/backend/combined/config
|
||||
# Configure IMAP
|
||||
rm -f /usr/local/lib/z-push/backend/imap/config.php
|
||||
cp conf/zpush/backend_imap.php /usr/local/lib/z-push/backend/imap/config.php
|
||||
sed -i "s%STORAGE_ROOT%$STORAGE_ROOT%" /usr/local/lib/z-push/backend/imap/config.php
|
||||
|
||||
# Configure CardDav
|
||||
rm -f /usr/local/lib/z-push/backend/carddav/config.php
|
||||
@@ -69,6 +76,7 @@ cp conf/zpush/backend_caldav.php /usr/local/lib/z-push/backend/caldav/config.php
|
||||
rm -f /usr/local/lib/z-push/autodiscover/config.php
|
||||
cp conf/zpush/autodiscover_config.php /usr/local/lib/z-push/autodiscover/config.php
|
||||
sed -i "s/PRIMARY_HOSTNAME/$PRIMARY_HOSTNAME/" /usr/local/lib/z-push/autodiscover/config.php
|
||||
sed -i "s^define('TIMEZONE', .*^define('TIMEZONE', '$(cat /etc/timezone)');^" /usr/local/lib/z-push/autodiscover/config.php
|
||||
|
||||
# Some directories it will use.
|
||||
|
||||
@@ -79,6 +87,23 @@ chmod 750 /var/lib/z-push
|
||||
chown www-data:www-data /var/log/z-push
|
||||
chown www-data:www-data /var/lib/z-push
|
||||
|
||||
# Add log rotation
|
||||
|
||||
cat > /etc/logrotate.d/z-push <<EOF;
|
||||
/var/log/z-push/*.log {
|
||||
weekly
|
||||
missingok
|
||||
rotate 52
|
||||
compress
|
||||
delaycompress
|
||||
notifempty
|
||||
}
|
||||
EOF
|
||||
|
||||
# Restart service.
|
||||
|
||||
restart_service php5-fpm
|
||||
restart_service php7.2-fpm
|
||||
|
||||
# Fix states after upgrade
|
||||
|
||||
hide_output z-push-admin -a fixstates
|
||||
|
||||
221
tests/fail2ban.py
Normal file
221
tests/fail2ban.py
Normal file
@@ -0,0 +1,221 @@
|
||||
# Test that a box's fail2ban setting are working
|
||||
# correctly by attempting a bunch of failed logins.
|
||||
#
|
||||
# Specify a SSH login command (which we use to reset
|
||||
# fail2ban after each test) and the hostname to
|
||||
# try to log in to.
|
||||
######################################################################
|
||||
|
||||
import sys, os, time, functools
|
||||
|
||||
# parse command line
|
||||
|
||||
if len(sys.argv) != 4:
|
||||
print("Usage: tests/fail2ban.py \"ssh user@hostname\" hostname owncloud_user")
|
||||
sys.exit(1)
|
||||
|
||||
ssh_command, hostname, owncloud_user = sys.argv[1:4]
|
||||
|
||||
# define some test types
|
||||
|
||||
import socket
|
||||
socket.setdefaulttimeout(10)
|
||||
|
||||
class IsBlocked(Exception):
|
||||
"""Tests raise this exception when it appears that a fail2ban
|
||||
jail is in effect, i.e. on a connection refused error."""
|
||||
pass
|
||||
|
||||
def smtp_test():
|
||||
import smtplib
|
||||
|
||||
try:
|
||||
server = smtplib.SMTP(hostname, 587)
|
||||
except ConnectionRefusedError:
|
||||
# looks like fail2ban worked
|
||||
raise IsBlocked()
|
||||
server.starttls()
|
||||
server.ehlo_or_helo_if_needed()
|
||||
|
||||
try:
|
||||
server.login("fakeuser", "fakepassword")
|
||||
raise Exception("authentication didn't fail")
|
||||
except smtplib.SMTPAuthenticationError:
|
||||
# athentication should fail
|
||||
pass
|
||||
|
||||
try:
|
||||
server.quit()
|
||||
except:
|
||||
# ignore errors here
|
||||
pass
|
||||
|
||||
def imap_test():
|
||||
import imaplib
|
||||
|
||||
try:
|
||||
M = imaplib.IMAP4_SSL(hostname)
|
||||
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 pop_test():
|
||||
import poplib
|
||||
try:
|
||||
M = poplib.POP3_SSL(hostname)
|
||||
except ConnectionRefusedError:
|
||||
# looks like fail2ban worked
|
||||
raise IsBlocked()
|
||||
try:
|
||||
M.user('fakeuser')
|
||||
try:
|
||||
M.pass_('fakepassword')
|
||||
except poplib.error_proto as e:
|
||||
# Authentication should fail.
|
||||
M = None # don't .quit()
|
||||
return
|
||||
M.list()
|
||||
raise Exception("authentication didn't fail")
|
||||
finally:
|
||||
if M:
|
||||
M.quit()
|
||||
|
||||
def http_test(url, expected_status, postdata=None, qsargs=None, auth=None):
|
||||
import urllib.parse
|
||||
import requests
|
||||
from requests.auth import HTTPBasicAuth
|
||||
|
||||
# form request
|
||||
url = urllib.parse.urljoin("https://" + hostname, url)
|
||||
if qsargs: url += "?" + urllib.parse.urlencode(qsargs)
|
||||
urlopen = requests.get if not postdata else requests.post
|
||||
|
||||
try:
|
||||
# issue request
|
||||
r = urlopen(
|
||||
url,
|
||||
auth=HTTPBasicAuth(*auth) if auth else None,
|
||||
data=postdata,
|
||||
headers={'User-Agent': 'Mail-in-a-Box fail2ban tester'},
|
||||
timeout=8,
|
||||
verify=False) # don't bother with HTTPS validation, it may not be configured yet
|
||||
except requests.exceptions.ConnectTimeout as e:
|
||||
raise IsBlocked()
|
||||
except requests.exceptions.ConnectionError as e:
|
||||
if "Connection refused" in str(e):
|
||||
raise IsBlocked()
|
||||
raise # some other unexpected condition
|
||||
|
||||
# return response status code
|
||||
if r.status_code != expected_status:
|
||||
r.raise_for_status() # anything but 200
|
||||
raise IOError("Got unexpected status code %s." % r.status_code)
|
||||
|
||||
# define how to run a test
|
||||
|
||||
def restart_fail2ban_service(final=False):
|
||||
# Log in over SSH to restart fail2ban.
|
||||
command = "sudo fail2ban-client reload"
|
||||
if not final:
|
||||
# Stop recidive jails during testing.
|
||||
command += " && sudo fail2ban-client stop recidive"
|
||||
os.system("%s \"%s\"" % (ssh_command, command))
|
||||
|
||||
def testfunc_runner(i, testfunc, *args):
|
||||
print(i+1, end=" ", flush=True)
|
||||
testfunc(*args)
|
||||
|
||||
def run_test(testfunc, args, count, within_seconds, parallel):
|
||||
# Run testfunc count times in within_seconds seconds (and actually
|
||||
# within a little less time so we're sure we're under the limit).
|
||||
#
|
||||
# Because some services are slow, like IMAP, we can't necessarily
|
||||
# run testfunc sequentially and still get to count requests within
|
||||
# the required time. So we split the requests across threads.
|
||||
|
||||
import requests.exceptions
|
||||
from multiprocessing import Pool
|
||||
|
||||
restart_fail2ban_service()
|
||||
|
||||
# Log.
|
||||
print(testfunc.__name__, " ".join(str(a) for a in args), "...")
|
||||
|
||||
# Record the start time so we can know how to evenly space our
|
||||
# calls to testfunc.
|
||||
start_time = time.time()
|
||||
|
||||
with Pool(parallel) as p:
|
||||
# Distribute the requests across the pool.
|
||||
asyncresults = []
|
||||
for i in range(count):
|
||||
ar = p.apply_async(testfunc_runner, [i, testfunc] + list(args))
|
||||
asyncresults.append(ar)
|
||||
|
||||
# Wait for all runs to finish.
|
||||
p.close()
|
||||
p.join()
|
||||
|
||||
# Check for errors.
|
||||
for ar in asyncresults:
|
||||
try:
|
||||
ar.get()
|
||||
except IsBlocked:
|
||||
print("Test machine prematurely blocked!")
|
||||
return False
|
||||
|
||||
# Did we make enough requests within the limit?
|
||||
if (time.time()-start_time) > within_seconds:
|
||||
raise Exception("Test failed to make %s requests in %d seconds." % (count, within_seconds))
|
||||
|
||||
# Wait a moment for the block to be put into place.
|
||||
time.sleep(4)
|
||||
|
||||
# The next call should fail.
|
||||
print("*", end=" ", flush=True)
|
||||
try:
|
||||
testfunc(*args)
|
||||
except IsBlocked:
|
||||
# Success -- this one is supposed to be refused.
|
||||
print("blocked [OK]")
|
||||
return True # OK
|
||||
|
||||
print("not blocked!")
|
||||
return False
|
||||
|
||||
######################################################################
|
||||
|
||||
if __name__ == "__main__":
|
||||
# run tests
|
||||
|
||||
# SMTP bans at 10 even though we say 20 in the config because we get
|
||||
# doubled-up warnings in the logs, we'll let that be for now
|
||||
run_test(smtp_test, [], 10, 30, 8)
|
||||
|
||||
# IMAP
|
||||
run_test(imap_test, [], 20, 30, 4)
|
||||
|
||||
# POP
|
||||
run_test(pop_test, [], 20, 30, 4)
|
||||
|
||||
# Mail-in-a-Box control panel
|
||||
run_test(http_test, ["/admin/me", 200], 20, 30, 1)
|
||||
|
||||
# Munin via the Mail-in-a-Box control panel
|
||||
run_test(http_test, ["/admin/munin/", 401], 20, 30, 1)
|
||||
|
||||
# ownCloud
|
||||
run_test(http_test, ["/cloud/remote.php/webdav", 401, None, None, [owncloud_user, "aa"]], 20, 120, 1)
|
||||
|
||||
# restart fail2ban so that this client machine is no longer blocked
|
||||
restart_fail2ban_service(final=True)
|
||||
164
tests/tls.py
Normal file
164
tests/tls.py
Normal file
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
# Runs SSLyze on the TLS endpoints of a box and outputs
|
||||
# the results so we can inspect the settings and compare
|
||||
# against a known good version in tls_results.txt.
|
||||
#
|
||||
# Make sure you have SSLyze available:
|
||||
# wget https://github.com/nabla-c0d3/sslyze/releases/download/release-0.11/sslyze-0_11-linux64.zip
|
||||
# unzip sslyze-0_11-linux64.zip
|
||||
#
|
||||
# Then run:
|
||||
#
|
||||
# python3 tls.py yourservername
|
||||
#
|
||||
# If you are on a residential network that blocks outbound
|
||||
# port 25 connections, then you can proxy the connections
|
||||
# through some other host you can ssh into (maybe the box
|
||||
# itself?):
|
||||
#
|
||||
# python3 tls.py --proxy user@ssh_host yourservername
|
||||
#
|
||||
# (This will launch "ssh -N -L10023:yourservername:testport user@ssh_host"
|
||||
# to create a tunnel.)
|
||||
|
||||
import sys, subprocess, re, time, json, csv, io, urllib.request
|
||||
|
||||
######################################################################
|
||||
|
||||
# PARSE COMMAND LINE
|
||||
|
||||
proxy = None
|
||||
args = list(sys.argv[1:])
|
||||
while len(args) > 0:
|
||||
if args[0] == "--proxy":
|
||||
args.pop(0)
|
||||
proxy = args.pop(0)
|
||||
break
|
||||
|
||||
if len(args) == 0:
|
||||
print("Usage: python3 tls.py [--proxy ssh_host] hostname")
|
||||
sys.exit(0)
|
||||
|
||||
host = args[0]
|
||||
|
||||
######################################################################
|
||||
|
||||
SSLYZE = "sslyze-0_11-linux64/sslyze/sslyze.py"
|
||||
|
||||
common_opts = ["--sslv2", "--sslv3", "--tlsv1", "--tlsv1_1", "--tlsv1_2", "--reneg", "--resum",
|
||||
"--hide_rejected_ciphers", "--compression", "--heartbleed"]
|
||||
|
||||
# Recommendations from Mozilla as of May 20, 2015 at
|
||||
# https://wiki.mozilla.org/Security/Server_Side_TLS.
|
||||
#
|
||||
# The 'modern' ciphers support Firefox 27, Chrome 22, IE 11,
|
||||
# Opera 14, Safari 7, Android 4.4, Java 8. Assumes TLSv1.1,
|
||||
# TLSv1.2 only, though we may also be allowing TLSv3.
|
||||
#
|
||||
# The 'intermediate' ciphers support Firefox 1, Chrome 1, IE 7,
|
||||
# Opera 5, Safari 1, Windows XP IE8, Android 2.3, Java 7.
|
||||
# Assumes TLSv1, TLSv1.1, TLSv1.2.
|
||||
#
|
||||
# The 'old' ciphers bring compatibility back to Win XP IE 6.
|
||||
MOZILLA_CIPHERS_MODERN = "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256"
|
||||
MOZILLA_CIPHERS_INTERMEDIATE = "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"
|
||||
MOZILLA_CIPHERS_OLD = "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:ECDHE-ECDSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP"
|
||||
|
||||
######################################################################
|
||||
|
||||
def sslyze(opts, port, ok_ciphers):
|
||||
# Print header.
|
||||
header = ("PORT %d" % port)
|
||||
print(header)
|
||||
print("-" * (len(header)))
|
||||
|
||||
# What ciphers should we expect?
|
||||
ok_ciphers = subprocess.check_output(["openssl", "ciphers", ok_ciphers]).decode("utf8").strip().split(":")
|
||||
|
||||
# Form the SSLyze connection string.
|
||||
connection_string = host + ":" + str(port)
|
||||
|
||||
# Proxy via SSH.
|
||||
proxy_proc = None
|
||||
if proxy:
|
||||
connection_string = "localhost:10023"
|
||||
proxy_proc = subprocess.Popen(["ssh", "-N", "-L10023:%s:%d" % (host, port), proxy])
|
||||
time.sleep(3)
|
||||
|
||||
try:
|
||||
# Execute SSLyze.
|
||||
out = subprocess.check_output([SSLYZE] + common_opts + opts + [connection_string])
|
||||
out = out.decode("utf8")
|
||||
|
||||
# Trim output to make better for storing in git.
|
||||
if "SCAN RESULTS FOR" not in out:
|
||||
# Failed. Just output the error.
|
||||
out = re.sub("[\w\W]*CHECKING HOST\(S\) AVAILABILITY\n\s*-+\n", "", out) # chop off header that shows the host we queried
|
||||
out = re.sub("[\w\W]*SCAN RESULTS FOR.*\n\s*-+\n", "", out) # chop off header that shows the host we queried
|
||||
out = re.sub("SCAN COMPLETED IN .*", "", out)
|
||||
out = out.rstrip(" \n-") + "\n"
|
||||
|
||||
# Print.
|
||||
print(out)
|
||||
|
||||
# Pull out the accepted ciphers list for each SSL/TLS protocol
|
||||
# version outputted.
|
||||
accepted_ciphers = set()
|
||||
for ciphers in re.findall(" Accepted:([\w\W]*?)\n *\n", out):
|
||||
accepted_ciphers |= set(re.findall("\n\s*(\S*)", ciphers))
|
||||
|
||||
# Compare to what Mozilla recommends, for a given modernness-level.
|
||||
print(" Should Not Offer: " + (", ".join(sorted(accepted_ciphers-set(ok_ciphers))) or "(none -- good)"))
|
||||
print(" Could Also Offer: " + (", ".join(sorted(set(ok_ciphers)-accepted_ciphers)) or "(none -- good)"))
|
||||
|
||||
# What clients does that mean we support on this protocol?
|
||||
supported_clients = { }
|
||||
for cipher in accepted_ciphers:
|
||||
if cipher in cipher_clients:
|
||||
for client in cipher_clients[cipher]:
|
||||
supported_clients[client] = supported_clients.get(client, 0) + 1
|
||||
print(" Supported Clients: " + (", ".join(sorted(supported_clients.keys(), key = lambda client : -supported_clients[client]))))
|
||||
|
||||
# Blank line.
|
||||
print()
|
||||
|
||||
finally:
|
||||
if proxy_proc:
|
||||
proxy_proc.terminate()
|
||||
try:
|
||||
proxy_proc.wait(5)
|
||||
except subprocess.TimeoutExpired:
|
||||
proxy_proc.kill()
|
||||
|
||||
# Get a list of OpenSSL cipher names.
|
||||
cipher_names = { }
|
||||
for cipher in csv.DictReader(io.StringIO(urllib.request.urlopen("https://raw.githubusercontent.com/mail-in-a-box/user-agent-tls-capabilities/master/cipher_names.csv").read().decode("utf8"))):
|
||||
# not sure why there are some multi-line values, use first line:
|
||||
cipher["OpenSSL"] = cipher["OpenSSL"].split("\n")[0]
|
||||
cipher_names[cipher["IANA"]] = cipher["OpenSSL"]
|
||||
|
||||
# Get a list of what clients support what ciphers, using OpenSSL cipher names.
|
||||
client_compatibility = json.loads(urllib.request.urlopen("https://raw.githubusercontent.com/mail-in-a-box/user-agent-tls-capabilities/master/clients.json").read().decode("utf8"))
|
||||
cipher_clients = { }
|
||||
for client in client_compatibility:
|
||||
if len(set(client['protocols']) & set(["TLS 1.0", "TLS 1.1", "TLS 1.2"])) == 0: continue # does not support TLS
|
||||
for cipher in client['ciphers']:
|
||||
cipher_clients.setdefault(cipher_names.get(cipher), set()).add("/".join(x for x in [client['client']['name'], client['client']['version'], client['client']['platform']] if x))
|
||||
|
||||
# Run SSLyze on various ports.
|
||||
|
||||
# SMTP
|
||||
sslyze(["--starttls=smtp"], 25, MOZILLA_CIPHERS_OLD)
|
||||
|
||||
# SMTP Submission
|
||||
sslyze(["--starttls=smtp"], 587, MOZILLA_CIPHERS_MODERN)
|
||||
|
||||
# HTTPS
|
||||
sslyze(["--http_get", "--chrome_sha1", "--hsts"], 443, MOZILLA_CIPHERS_INTERMEDIATE)
|
||||
|
||||
# IMAP
|
||||
sslyze([], 993, MOZILLA_CIPHERS_MODERN)
|
||||
|
||||
# POP3
|
||||
sslyze([], 995, MOZILLA_CIPHERS_MODERN)
|
||||
400
tests/tls_results.txt
Normal file
400
tests/tls_results.txt
Normal file
@@ -0,0 +1,400 @@
|
||||
PORT 25
|
||||
-------
|
||||
|
||||
* Deflate Compression:
|
||||
OK - Compression disabled
|
||||
|
||||
* Session Renegotiation:
|
||||
Client-initiated Renegotiations: VULNERABLE - Server honors client-initiated renegotiations
|
||||
Secure Renegotiation: OK - Supported
|
||||
|
||||
* OpenSSL Heartbleed:
|
||||
OK - Not vulnerable to Heartbleed
|
||||
|
||||
* Session Resumption:
|
||||
With Session IDs: OK - Supported (5 successful, 0 failed, 0 errors, 5 total attempts).
|
||||
With TLS Session Tickets: OK - Supported
|
||||
|
||||
* SSLV2 Cipher Suites:
|
||||
Server rejected all cipher suites.
|
||||
|
||||
* TLSV1_2 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES256-GCM-SHA384 ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA384 ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES256-SHA ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES256-GCM-SHA384 ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES256-SHA256 DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES256-GCM-SHA384 DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
CAMELLIA256-SHA - 256 bits 250 2.0.0 Ok
|
||||
AES256-SHA256 - 256 bits 250 2.0.0 Ok
|
||||
AES256-SHA - 256 bits 250 2.0.0 Ok
|
||||
AES256-GCM-SHA384 - 256 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES128-SHA256 ECDH-521 bits 128 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES128-SHA ECDH-521 bits 128 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES128-GCM-SHA256 ECDH-521 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-SEED-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES128-SHA256 DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES128-GCM-SHA256 DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
SEED-SHA - 128 bits 250 2.0.0 Ok
|
||||
CAMELLIA128-SHA - 128 bits 250 2.0.0 Ok
|
||||
AES128-SHA256 - 128 bits 250 2.0.0 Ok
|
||||
AES128-SHA - 128 bits 250 2.0.0 Ok
|
||||
AES128-GCM-SHA256 - 128 bits 250 2.0.0 Ok
|
||||
|
||||
* TLSV1_1 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES256-SHA ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
CAMELLIA256-SHA - 256 bits 250 2.0.0 Ok
|
||||
AES256-SHA - 256 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES128-SHA ECDH-521 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-SEED-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
SEED-SHA - 128 bits 250 2.0.0 Ok
|
||||
CAMELLIA128-SHA - 128 bits 250 2.0.0 Ok
|
||||
AES128-SHA - 128 bits 250 2.0.0 Ok
|
||||
|
||||
* SSLV3 Cipher Suites:
|
||||
Server rejected all cipher suites.
|
||||
|
||||
* TLSV1 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES256-SHA ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
CAMELLIA256-SHA - 256 bits 250 2.0.0 Ok
|
||||
AES256-SHA - 256 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES128-SHA ECDH-521 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-SEED-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
SEED-SHA - 128 bits 250 2.0.0 Ok
|
||||
CAMELLIA128-SHA - 128 bits 250 2.0.0 Ok
|
||||
AES128-SHA - 128 bits 250 2.0.0 Ok
|
||||
|
||||
Should Not Offer: (none -- good)
|
||||
Could Also Offer: AES128-CCM, AES128-CCM8, AES256-CCM, AES256-CCM8, CAMELLIA128-SHA256, CAMELLIA256-SHA256, DHE-DSS-AES128-GCM-SHA256, DHE-DSS-AES128-SHA, DHE-DSS-AES128-SHA256, DHE-DSS-AES256-GCM-SHA384, DHE-DSS-AES256-SHA, DHE-DSS-AES256-SHA256, DHE-DSS-CAMELLIA128-SHA, DHE-DSS-CAMELLIA128-SHA256, DHE-DSS-CAMELLIA256-SHA, DHE-DSS-CAMELLIA256-SHA256, DHE-DSS-SEED-SHA, DHE-RSA-AES128-CCM, DHE-RSA-AES128-CCM8, DHE-RSA-AES256-CCM, DHE-RSA-AES256-CCM8, DHE-RSA-CAMELLIA128-SHA256, DHE-RSA-CAMELLIA256-SHA256, DHE-RSA-CHACHA20-POLY1305, ECDHE-ECDSA-AES128-CCM, ECDHE-ECDSA-AES128-CCM8, ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA, ECDHE-ECDSA-AES128-SHA256, ECDHE-ECDSA-AES256-CCM, ECDHE-ECDSA-AES256-CCM8, ECDHE-ECDSA-AES256-GCM-SHA384, ECDHE-ECDSA-AES256-SHA, ECDHE-ECDSA-AES256-SHA384, ECDHE-ECDSA-CAMELLIA128-SHA256, ECDHE-ECDSA-CAMELLIA256-SHA384, ECDHE-ECDSA-CHACHA20-POLY1305, ECDHE-RSA-CAMELLIA128-SHA256, ECDHE-RSA-CAMELLIA256-SHA384, ECDHE-RSA-CHACHA20-POLY1305
|
||||
Supported Clients: Yahoo Slurp/Jan 2015, OpenSSL/1.0.2, BingPreview/Jan 2015, OpenSSL/1.0.1l, YandexBot/Jan 2015, Android/4.4.2, Safari/6/iOS 6.0.1, Safari/8/OS X 10.10, Safari/7/OS X 10.9, Safari/7/iOS 7.1, IE/11/Win 8.1, Safari/8/iOS 8.1.2, IE Mobile/11/Win Phone 8.1, IE/11/Win 7, Baidu/Jan 2015, Firefox/31.3.0 ESR/Win 7, Android/5.0.0, Chrome/42/OS X, Java/8u31, Googlebot/Feb 2015, Firefox/37/OS X, Android/4.3, Android/4.2.2, Safari/5.1.9/OS X 10.6.8, Android/4.0.4, Android/4.1.1, Safari/6.0.4/OS X 10.8.4, IE Mobile/10/Win Phone 8.0, IE/8-10/Win 7, IE/7/Vista, OpenSSL/0.9.8y, Java/7u25, Android/2.3.7, Java/6u45
|
||||
|
||||
PORT 587
|
||||
--------
|
||||
|
||||
* Deflate Compression:
|
||||
OK - Compression disabled
|
||||
|
||||
* Session Renegotiation:
|
||||
Client-initiated Renegotiations: VULNERABLE - Server honors client-initiated renegotiations
|
||||
Secure Renegotiation: OK - Supported
|
||||
|
||||
* OpenSSL Heartbleed:
|
||||
OK - Not vulnerable to Heartbleed
|
||||
|
||||
* Session Resumption:
|
||||
With Session IDs: OK - Supported (5 successful, 0 failed, 0 errors, 5 total attempts).
|
||||
With TLS Session Tickets: OK - Supported
|
||||
|
||||
* SSLV2 Cipher Suites:
|
||||
Server rejected all cipher suites.
|
||||
|
||||
* TLSV1_2 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES256-GCM-SHA384 ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA384 ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES256-SHA ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES256-GCM-SHA384 ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES256-SHA256 DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES256-GCM-SHA384 DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
CAMELLIA256-SHA - 256 bits 250 2.0.0 Ok
|
||||
AES256-SHA256 - 256 bits 250 2.0.0 Ok
|
||||
AES256-SHA - 256 bits 250 2.0.0 Ok
|
||||
AES256-GCM-SHA384 - 256 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES128-SHA256 ECDH-521 bits 128 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES128-SHA ECDH-521 bits 128 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES128-GCM-SHA256 ECDH-521 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-SEED-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES128-SHA256 DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES128-GCM-SHA256 DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
SEED-SHA - 128 bits 250 2.0.0 Ok
|
||||
CAMELLIA128-SHA - 128 bits 250 2.0.0 Ok
|
||||
AES128-SHA256 - 128 bits 250 2.0.0 Ok
|
||||
AES128-SHA - 128 bits 250 2.0.0 Ok
|
||||
AES128-GCM-SHA256 - 128 bits 250 2.0.0 Ok
|
||||
|
||||
* TLSV1_1 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES256-SHA ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
CAMELLIA256-SHA - 256 bits 250 2.0.0 Ok
|
||||
AES256-SHA - 256 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES128-SHA ECDH-521 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-SEED-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
SEED-SHA - 128 bits 250 2.0.0 Ok
|
||||
CAMELLIA128-SHA - 128 bits 250 2.0.0 Ok
|
||||
AES128-SHA - 128 bits 250 2.0.0 Ok
|
||||
|
||||
* SSLV3 Cipher Suites:
|
||||
Server rejected all cipher suites.
|
||||
|
||||
* TLSV1 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES256-SHA ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA ECDH-521 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits 250 2.0.0 Ok
|
||||
CAMELLIA256-SHA - 256 bits 250 2.0.0 Ok
|
||||
AES256-SHA - 256 bits 250 2.0.0 Ok
|
||||
ECDHE-RSA-AES128-SHA ECDH-521 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-SEED-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-CAMELLIA128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits 250 2.0.0 Ok
|
||||
SEED-SHA - 128 bits 250 2.0.0 Ok
|
||||
CAMELLIA128-SHA - 128 bits 250 2.0.0 Ok
|
||||
AES128-SHA - 128 bits 250 2.0.0 Ok
|
||||
|
||||
Should Not Offer: AES128-GCM-SHA256, AES128-SHA, AES128-SHA256, AES256-GCM-SHA384, AES256-SHA, AES256-SHA256, CAMELLIA128-SHA, CAMELLIA256-SHA, DHE-RSA-AES128-GCM-SHA256, DHE-RSA-AES128-SHA, DHE-RSA-AES128-SHA256, DHE-RSA-AES256-GCM-SHA384, DHE-RSA-AES256-SHA, DHE-RSA-AES256-SHA256, DHE-RSA-CAMELLIA128-SHA, DHE-RSA-CAMELLIA256-SHA, DHE-RSA-SEED-SHA, ECDHE-RSA-AES128-SHA, ECDHE-RSA-AES256-SHA, SEED-SHA
|
||||
Could Also Offer: ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-ECDSA-AES256-GCM-SHA384, ECDHE-ECDSA-AES256-SHA384, ECDHE-ECDSA-CHACHA20-POLY1305, ECDHE-RSA-CHACHA20-POLY1305
|
||||
Supported Clients: Yahoo Slurp/Jan 2015, OpenSSL/1.0.2, BingPreview/Jan 2015, OpenSSL/1.0.1l, YandexBot/Jan 2015, Android/4.4.2, Safari/6/iOS 6.0.1, Safari/8/OS X 10.10, Safari/7/OS X 10.9, Safari/7/iOS 7.1, IE/11/Win 8.1, Safari/8/iOS 8.1.2, IE Mobile/11/Win Phone 8.1, IE/11/Win 7, Baidu/Jan 2015, Firefox/31.3.0 ESR/Win 7, Android/5.0.0, Chrome/42/OS X, Java/8u31, Googlebot/Feb 2015, Firefox/37/OS X, Android/4.3, Android/4.2.2, Safari/5.1.9/OS X 10.6.8, Android/4.0.4, Android/4.1.1, Safari/6.0.4/OS X 10.8.4, IE Mobile/10/Win Phone 8.0, IE/8-10/Win 7, IE/7/Vista, OpenSSL/0.9.8y, Java/7u25, Android/2.3.7, Java/6u45
|
||||
|
||||
PORT 443
|
||||
--------
|
||||
|
||||
* Deflate Compression:
|
||||
OK - Compression disabled
|
||||
|
||||
* Session Renegotiation:
|
||||
Client-initiated Renegotiations: OK - Rejected
|
||||
Secure Renegotiation: OK - Supported
|
||||
|
||||
* HTTP Strict Transport Security:
|
||||
OK - HSTS header received: max-age=15768000
|
||||
|
||||
* Session Resumption:
|
||||
With Session IDs: OK - Supported (5 successful, 0 failed, 0 errors, 5 total attempts).
|
||||
With TLS Session Tickets: OK - Supported
|
||||
|
||||
* OpenSSL Heartbleed:
|
||||
OK - Not vulnerable to Heartbleed
|
||||
|
||||
Unhandled exception when processing --chrome_sha1:
|
||||
exceptions.TypeError - Incorrect padding
|
||||
|
||||
* SSLV2 Cipher Suites:
|
||||
Server rejected all cipher suites.
|
||||
|
||||
* TLSV1_2 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES128-GCM-SHA256 ECDH-256 bits 128 bits HTTP 200 OK
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA384 ECDH-256 bits 256 bits HTTP 200 OK
|
||||
ECDHE-RSA-AES256-SHA ECDH-256 bits 256 bits HTTP 200 OK
|
||||
ECDHE-RSA-AES256-GCM-SHA384 ECDH-256 bits 256 bits HTTP 200 OK
|
||||
DHE-RSA-AES256-SHA256 DH-2048 bits 256 bits HTTP 200 OK
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits HTTP 200 OK
|
||||
DHE-RSA-AES256-GCM-SHA384 DH-2048 bits 256 bits HTTP 200 OK
|
||||
AES256-SHA256 - 256 bits HTTP 200 OK
|
||||
AES256-SHA - 256 bits HTTP 200 OK
|
||||
AES256-GCM-SHA384 - 256 bits HTTP 200 OK
|
||||
ECDHE-RSA-AES128-SHA256 ECDH-256 bits 128 bits HTTP 200 OK
|
||||
ECDHE-RSA-AES128-SHA ECDH-256 bits 128 bits HTTP 200 OK
|
||||
ECDHE-RSA-AES128-GCM-SHA256 ECDH-256 bits 128 bits HTTP 200 OK
|
||||
DHE-RSA-AES128-SHA256 DH-2048 bits 128 bits HTTP 200 OK
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits HTTP 200 OK
|
||||
DHE-RSA-AES128-GCM-SHA256 DH-2048 bits 128 bits HTTP 200 OK
|
||||
AES128-SHA256 - 128 bits HTTP 200 OK
|
||||
AES128-SHA - 128 bits HTTP 200 OK
|
||||
AES128-GCM-SHA256 - 128 bits HTTP 200 OK
|
||||
|
||||
* TLSV1_1 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES128-SHA ECDH-256 bits 128 bits HTTP 200 OK
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA ECDH-256 bits 256 bits HTTP 200 OK
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits HTTP 200 OK
|
||||
AES256-SHA - 256 bits HTTP 200 OK
|
||||
ECDHE-RSA-AES128-SHA ECDH-256 bits 128 bits HTTP 200 OK
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits HTTP 200 OK
|
||||
AES128-SHA - 128 bits HTTP 200 OK
|
||||
|
||||
* SSLV3 Cipher Suites:
|
||||
Server rejected all cipher suites.
|
||||
|
||||
* TLSV1 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES128-SHA ECDH-256 bits 128 bits HTTP 200 OK
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA ECDH-256 bits 256 bits HTTP 200 OK
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits HTTP 200 OK
|
||||
AES256-SHA - 256 bits HTTP 200 OK
|
||||
ECDHE-RSA-AES128-SHA ECDH-256 bits 128 bits HTTP 200 OK
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits HTTP 200 OK
|
||||
AES128-SHA - 128 bits HTTP 200 OK
|
||||
|
||||
Should Not Offer: (none -- good)
|
||||
Could Also Offer: ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA, ECDHE-ECDSA-AES128-SHA256, ECDHE-ECDSA-AES256-GCM-SHA384, ECDHE-ECDSA-AES256-SHA, ECDHE-ECDSA-AES256-SHA384, ECDHE-ECDSA-CHACHA20-POLY1305, ECDHE-RSA-CHACHA20-POLY1305
|
||||
Supported Clients: Yahoo Slurp/Jan 2015, OpenSSL/1.0.2, YandexBot/Jan 2015, BingPreview/Jan 2015, OpenSSL/1.0.1l, Android/4.4.2, Safari/6/iOS 6.0.1, Safari/8/OS X 10.10, Safari/7/OS X 10.9, Safari/7/iOS 7.1, IE/11/Win 8.1, Safari/8/iOS 8.1.2, IE Mobile/11/Win Phone 8.1, IE/11/Win 7, Android/5.0.0, Chrome/42/OS X, Java/8u31, Googlebot/Feb 2015, Firefox/31.3.0 ESR/Win 7, Firefox/37/OS X, Android/4.3, Android/4.2.2, Baidu/Jan 2015, Safari/5.1.9/OS X 10.6.8, Android/4.0.4, Android/4.1.1, Safari/6.0.4/OS X 10.8.4, IE Mobile/10/Win Phone 8.0, IE/8-10/Win 7, IE/7/Vista, OpenSSL/0.9.8y, Java/7u25, Android/2.3.7, Java/6u45
|
||||
|
||||
PORT 993
|
||||
--------
|
||||
|
||||
* Deflate Compression:
|
||||
OK - Compression disabled
|
||||
|
||||
Unhandled exception when processing --reneg:
|
||||
_nassl.OpenSSLError - error:140940F5:SSL routines:ssl3_read_bytes:unexpected record
|
||||
|
||||
* OpenSSL Heartbleed:
|
||||
OK - Not vulnerable to Heartbleed
|
||||
|
||||
* Session Resumption:
|
||||
With Session IDs: NOT SUPPORTED (0 successful, 5 failed, 0 errors, 5 total attempts).
|
||||
With TLS Session Tickets: NOT SUPPORTED - TLS ticket assigned but not accepted.
|
||||
|
||||
* SSLV2 Cipher Suites:
|
||||
Server rejected all cipher suites.
|
||||
|
||||
* TLSV1_2 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES128-GCM-SHA256 ECDH-384 bits 128 bits
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA384 ECDH-384 bits 256 bits
|
||||
ECDHE-RSA-AES256-SHA ECDH-384 bits 256 bits
|
||||
ECDHE-RSA-AES256-GCM-SHA384 ECDH-384 bits 256 bits
|
||||
DHE-RSA-AES256-SHA256 DH-2048 bits 256 bits
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits
|
||||
DHE-RSA-AES256-GCM-SHA384 DH-2048 bits 256 bits
|
||||
AES256-SHA256 - 256 bits
|
||||
AES256-SHA - 256 bits
|
||||
AES256-GCM-SHA384 - 256 bits
|
||||
ECDHE-RSA-AES128-SHA256 ECDH-384 bits 128 bits
|
||||
ECDHE-RSA-AES128-SHA ECDH-384 bits 128 bits
|
||||
ECDHE-RSA-AES128-GCM-SHA256 ECDH-384 bits 128 bits
|
||||
DHE-RSA-AES128-SHA256 DH-2048 bits 128 bits
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits
|
||||
DHE-RSA-AES128-GCM-SHA256 DH-2048 bits 128 bits
|
||||
AES128-SHA256 - 128 bits
|
||||
AES128-SHA - 128 bits
|
||||
AES128-GCM-SHA256 - 128 bits
|
||||
|
||||
* TLSV1_1 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES128-SHA ECDH-384 bits 128 bits
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA ECDH-384 bits 256 bits
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits
|
||||
AES256-SHA - 256 bits
|
||||
ECDHE-RSA-AES128-SHA ECDH-384 bits 128 bits
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits
|
||||
AES128-SHA - 128 bits
|
||||
|
||||
* SSLV3 Cipher Suites:
|
||||
Server rejected all cipher suites.
|
||||
|
||||
* TLSV1 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES128-SHA ECDH-384 bits 128 bits
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA ECDH-384 bits 256 bits
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits
|
||||
AES256-SHA - 256 bits
|
||||
ECDHE-RSA-AES128-SHA ECDH-384 bits 128 bits
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits
|
||||
AES128-SHA - 128 bits
|
||||
|
||||
Should Not Offer: AES128-GCM-SHA256, AES128-SHA, AES128-SHA256, AES256-GCM-SHA384, AES256-SHA, AES256-SHA256, DHE-RSA-AES128-GCM-SHA256, DHE-RSA-AES128-SHA, DHE-RSA-AES128-SHA256, DHE-RSA-AES256-GCM-SHA384, DHE-RSA-AES256-SHA, DHE-RSA-AES256-SHA256, ECDHE-RSA-AES128-SHA, ECDHE-RSA-AES256-SHA
|
||||
Could Also Offer: ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-ECDSA-AES256-GCM-SHA384, ECDHE-ECDSA-AES256-SHA384, ECDHE-ECDSA-CHACHA20-POLY1305, ECDHE-RSA-CHACHA20-POLY1305
|
||||
Supported Clients: Yahoo Slurp/Jan 2015, OpenSSL/1.0.2, YandexBot/Jan 2015, BingPreview/Jan 2015, OpenSSL/1.0.1l, Android/4.4.2, Safari/6/iOS 6.0.1, Safari/8/OS X 10.10, Safari/7/OS X 10.9, Safari/7/iOS 7.1, IE/11/Win 8.1, Safari/8/iOS 8.1.2, IE Mobile/11/Win Phone 8.1, IE/11/Win 7, Android/5.0.0, Chrome/42/OS X, Java/8u31, Googlebot/Feb 2015, Firefox/31.3.0 ESR/Win 7, Firefox/37/OS X, Android/4.3, Android/4.2.2, Baidu/Jan 2015, Safari/5.1.9/OS X 10.6.8, Android/4.0.4, Android/4.1.1, Safari/6.0.4/OS X 10.8.4, IE Mobile/10/Win Phone 8.0, IE/8-10/Win 7, IE/7/Vista, OpenSSL/0.9.8y, Java/7u25, Android/2.3.7, Java/6u45
|
||||
|
||||
PORT 995
|
||||
--------
|
||||
|
||||
* Deflate Compression:
|
||||
OK - Compression disabled
|
||||
|
||||
Unhandled exception when processing --reneg:
|
||||
_nassl.OpenSSLError - error:140940F5:SSL routines:ssl3_read_bytes:unexpected record
|
||||
|
||||
* OpenSSL Heartbleed:
|
||||
OK - Not vulnerable to Heartbleed
|
||||
|
||||
* Session Resumption:
|
||||
With Session IDs: NOT SUPPORTED (0 successful, 5 failed, 0 errors, 5 total attempts).
|
||||
With TLS Session Tickets: NOT SUPPORTED - TLS ticket assigned but not accepted.
|
||||
|
||||
* SSLV2 Cipher Suites:
|
||||
Server rejected all cipher suites.
|
||||
|
||||
* TLSV1_2 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES128-GCM-SHA256 ECDH-384 bits 128 bits
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA384 ECDH-384 bits 256 bits
|
||||
ECDHE-RSA-AES256-SHA ECDH-384 bits 256 bits
|
||||
ECDHE-RSA-AES256-GCM-SHA384 ECDH-384 bits 256 bits
|
||||
DHE-RSA-AES256-SHA256 DH-2048 bits 256 bits
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits
|
||||
DHE-RSA-AES256-GCM-SHA384 DH-2048 bits 256 bits
|
||||
AES256-SHA256 - 256 bits
|
||||
AES256-SHA - 256 bits
|
||||
AES256-GCM-SHA384 - 256 bits
|
||||
ECDHE-RSA-AES128-SHA256 ECDH-384 bits 128 bits
|
||||
ECDHE-RSA-AES128-SHA ECDH-384 bits 128 bits
|
||||
ECDHE-RSA-AES128-GCM-SHA256 ECDH-384 bits 128 bits
|
||||
DHE-RSA-AES128-SHA256 DH-2048 bits 128 bits
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits
|
||||
DHE-RSA-AES128-GCM-SHA256 DH-2048 bits 128 bits
|
||||
AES128-SHA256 - 128 bits
|
||||
AES128-SHA - 128 bits
|
||||
AES128-GCM-SHA256 - 128 bits
|
||||
|
||||
* TLSV1_1 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES128-SHA ECDH-384 bits 128 bits
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA ECDH-384 bits 256 bits
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits
|
||||
AES256-SHA - 256 bits
|
||||
ECDHE-RSA-AES128-SHA ECDH-384 bits 128 bits
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits
|
||||
AES128-SHA - 128 bits
|
||||
|
||||
* SSLV3 Cipher Suites:
|
||||
Server rejected all cipher suites.
|
||||
|
||||
* TLSV1 Cipher Suites:
|
||||
Preferred:
|
||||
ECDHE-RSA-AES128-SHA ECDH-384 bits 128 bits
|
||||
Accepted:
|
||||
ECDHE-RSA-AES256-SHA ECDH-384 bits 256 bits
|
||||
DHE-RSA-AES256-SHA DH-2048 bits 256 bits
|
||||
AES256-SHA - 256 bits
|
||||
ECDHE-RSA-AES128-SHA ECDH-384 bits 128 bits
|
||||
DHE-RSA-AES128-SHA DH-2048 bits 128 bits
|
||||
AES128-SHA - 128 bits
|
||||
|
||||
Should Not Offer: AES128-GCM-SHA256, AES128-SHA, AES128-SHA256, AES256-GCM-SHA384, AES256-SHA, AES256-SHA256, DHE-RSA-AES128-GCM-SHA256, DHE-RSA-AES128-SHA, DHE-RSA-AES128-SHA256, DHE-RSA-AES256-GCM-SHA384, DHE-RSA-AES256-SHA, DHE-RSA-AES256-SHA256, ECDHE-RSA-AES128-SHA, ECDHE-RSA-AES256-SHA
|
||||
Could Also Offer: ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-ECDSA-AES256-GCM-SHA384, ECDHE-ECDSA-AES256-SHA384, ECDHE-ECDSA-CHACHA20-POLY1305, ECDHE-RSA-CHACHA20-POLY1305
|
||||
Supported Clients: Yahoo Slurp/Jan 2015, OpenSSL/1.0.2, YandexBot/Jan 2015, BingPreview/Jan 2015, OpenSSL/1.0.1l, Android/4.4.2, Safari/6/iOS 6.0.1, Safari/8/OS X 10.10, Safari/7/OS X 10.9, Safari/7/iOS 7.1, IE/11/Win 8.1, Safari/8/iOS 8.1.2, IE Mobile/11/Win Phone 8.1, IE/11/Win 7, Android/5.0.0, Chrome/42/OS X, Java/8u31, Googlebot/Feb 2015, Firefox/31.3.0 ESR/Win 7, Firefox/37/OS X, Android/4.3, Android/4.2.2, Baidu/Jan 2015, Safari/5.1.9/OS X 10.6.8, Android/4.0.4, Android/4.1.1, Safari/6.0.4/OS X 10.8.4, IE Mobile/10/Win Phone 8.0, IE/8-10/Win 7, IE/7/Vista, OpenSSL/0.9.8y, Java/7u25, Android/2.3.7, Java/6u45
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
#
|
||||
# NAME VALUE
|
||||
#
|
||||
# If the -c option is given, then the supplied character becomes the comment character
|
||||
#
|
||||
# If the -w option is given, then setting lines continue onto following
|
||||
# lines while the lines start with whitespace, e.g.:
|
||||
#
|
||||
@@ -24,7 +26,7 @@ import sys, re
|
||||
|
||||
# sanity check
|
||||
if len(sys.argv) < 3:
|
||||
print("usage: python3 editconf.py /etc/file.conf [-s] [-w] [-t] NAME=VAL [NAME=VAL ...]")
|
||||
print("usage: python3 editconf.py /etc/file.conf [-s] [-w] [-c <CHARACTER>] [-t] NAME=VAL [NAME=VAL ...]")
|
||||
sys.exit(1)
|
||||
|
||||
# parse command line arguments
|
||||
@@ -54,6 +56,14 @@ while settings[0][0] == "-" and settings[0] != "--":
|
||||
print("Invalid option.")
|
||||
sys.exit(1)
|
||||
|
||||
# sanity check command line
|
||||
for setting in settings:
|
||||
try:
|
||||
name, value = setting.split("=", 1)
|
||||
except:
|
||||
import subprocess
|
||||
print("Invalid command line: ", subprocess.list2cmdline(sys.argv))
|
||||
|
||||
# create the new config file in memory
|
||||
|
||||
found = set()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
import sys, getpass, urllib.request, urllib.error, json
|
||||
import sys, getpass, urllib.request, urllib.error, json, re
|
||||
|
||||
def mgmt(cmd, data=None, is_json=False):
|
||||
# The base URL for the management daemon. (Listens on IPv4 only.)
|
||||
@@ -28,12 +28,19 @@ def mgmt(cmd, data=None, is_json=False):
|
||||
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): ')
|
||||
while first != second:
|
||||
print('Passwords not the same. Try again.')
|
||||
first = getpass.getpass('password: ')
|
||||
second = getpass.getpass(' (again): ')
|
||||
if first != second:
|
||||
print("Passwords not the same. Try again.")
|
||||
continue
|
||||
break
|
||||
return first
|
||||
|
||||
def setup_key_auth(mgmt_uri):
|
||||
@@ -113,10 +120,10 @@ 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", { "source": sys.argv[3], "destination": sys.argv[4] }))
|
||||
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", { "source": sys.argv[3] }))
|
||||
print(mgmt("/mail/aliases/remove", { "address": sys.argv[3] }))
|
||||
|
||||
else:
|
||||
print("Invalid command-line arguments.")
|
||||
|
||||
49
tools/owncloud-restore.sh
Executable file
49
tools/owncloud-restore.sh
Executable file
@@ -0,0 +1,49 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# This script will restore the backup made during an installation
|
||||
source /etc/mailinabox.conf # load global vars
|
||||
|
||||
if [ -z "$1" ]; then
|
||||
echo "Usage: owncloud-restore.sh <backup directory>"
|
||||
echo
|
||||
echo "WARNING: This will restore the database to the point of the installation!"
|
||||
echo " This means that you will lose all changes made by users after that point"
|
||||
echo
|
||||
echo
|
||||
echo "Backups are stored here: $STORAGE_ROOT/owncloud-backup/"
|
||||
echo
|
||||
echo "Available backups:"
|
||||
echo
|
||||
find $STORAGE_ROOT/owncloud-backup/* -maxdepth 0 -type d
|
||||
echo
|
||||
echo "Supply the directory that was created during the last installation as the only commandline argument"
|
||||
exit
|
||||
fi
|
||||
|
||||
if [ ! -f $1/config.php ]; then
|
||||
echo "This isn't a valid backup location"
|
||||
exit
|
||||
fi
|
||||
|
||||
echo "Restoring backup from $1"
|
||||
service php7.2-fpm stop
|
||||
|
||||
# remove the current ownCloud/Nextcloud installation
|
||||
rm -rf /usr/local/lib/owncloud/
|
||||
# restore the current ownCloud/Nextcloud application
|
||||
cp -r "$1/owncloud-install" /usr/local/lib/owncloud
|
||||
|
||||
# restore access rights
|
||||
chmod 750 /usr/local/lib/owncloud/{apps,config}
|
||||
|
||||
cp "$1/owncloud.db" $STORAGE_ROOT/owncloud/
|
||||
cp "$1/config.php" $STORAGE_ROOT/owncloud/
|
||||
|
||||
ln -sf $STORAGE_ROOT/owncloud/config.php /usr/local/lib/owncloud/config/config.php
|
||||
chown -f -R www-data.www-data $STORAGE_ROOT/owncloud /usr/local/lib/owncloud
|
||||
chown www-data.www-data $STORAGE_ROOT/owncloud/config.php
|
||||
|
||||
sudo -u www-data php /usr/local/lib/owncloud/occ maintenance:mode --off
|
||||
|
||||
service php7.2-fpm start
|
||||
echo "Done"
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# This script will give you administrative access to the ownCloud
|
||||
# This script will give you administrative access to the Nextcloud
|
||||
# instance running here.
|
||||
#
|
||||
# Run this at your own risk. This is for testing & experimentation
|
||||
@@ -14,10 +14,10 @@ test -z "$1" || ADMIN=$1
|
||||
echo I am going to unlock admin features for $ADMIN.
|
||||
echo You can provide another user to unlock as the first argument of this script.
|
||||
echo
|
||||
echo WARNING: you could break mail-in-a-box when fiddling around with owncloud\'s admin interface
|
||||
echo WARNING: you could break mail-in-a-box when fiddling around with Nextcloud\'s admin interface
|
||||
echo If in doubt, press CTRL-C to cancel.
|
||||
echo
|
||||
echo Press enter to continue.
|
||||
read
|
||||
|
||||
sqlite3 $STORAGE_ROOT/owncloud/owncloud.db "INSERT OR IGNORE INTO oc_group_user VALUES ('admin', '$ADMIN')" && echo Done.
|
||||
sudo -u www-data php /usr/local/lib/owncloud/occ group:adduser admin $ADMIN && echo Done.
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
#
|
||||
# This is a tool Josh uses on his box serving mailinabox.email to parse the nginx
|
||||
# access log to see how many people are installing Mail-in-a-Box each day, by
|
||||
# looking at accesses to the bootstrap.sh script.
|
||||
# looking at accesses to the bootstrap.sh script (which is currently at the URL
|
||||
# .../setup.sh).
|
||||
|
||||
import re, glob, gzip, os.path, json
|
||||
import dateutil.parser
|
||||
@@ -24,8 +25,10 @@ for fn in glob.glob("/var/log/nginx/access.log*"):
|
||||
# Loop through the lines in the access log.
|
||||
with f:
|
||||
for line in f:
|
||||
# Find lines that are GETs on /bootstrap.sh by either curl or wget.
|
||||
m = re.match(rb"(?P<ip>\S+) - - \[(?P<date>.*?)\] \"GET /bootstrap.sh HTTP/.*\" 200 \d+ .* \"(?:curl|wget)", line, re.I)
|
||||
# Find lines that are GETs on the bootstrap script by either curl or wget.
|
||||
# (Note that we purposely skip ...?ping=1 requests which is the admin panel querying us for updates.)
|
||||
# (Also, the URL changed in January 2016, but we'll accept both.)
|
||||
m = re.match(rb"(?P<ip>\S+) - - \[(?P<date>.*?)\] \"GET /(bootstrap.sh|setup.sh) HTTP/.*\" 200 \d+ .* \"(?:curl|wget)", line, re.I)
|
||||
if m:
|
||||
date, time = m.group("date").decode("ascii").split(":", 1)
|
||||
date = dateutil.parser.parse(date).date().isoformat()
|
||||
|
||||
@@ -458,7 +458,6 @@ class BashScript(Grammar):
|
||||
|
||||
v = re.sub(r"(\$?)PRIMARY_HOSTNAME", r"<b>box.yourdomain.com</b>", v)
|
||||
v = re.sub(r"\$STORAGE_ROOT", r"<b>$STORE</b>", v)
|
||||
v = re.sub(r"\$CSR_COUNTRY", r"<b>US</b>", v)
|
||||
v = v.replace("`pwd`", "<code><b>/path/to/mailinabox</b></code>")
|
||||
|
||||
return v
|
||||
|
||||
Reference in New Issue
Block a user