emailwiz 2.0.0: Debian 13 fork of LukeSmithxyz/emailwiz

This commit is contained in:
ahp committed 2026-10-28 19:19:29 +03:30
commit 6b1c0f47de
52 files changed
+4213

No files matched your search

+1
View File
@@ -0,0 +1 @@
dist/
+4
View File
@@ -0,0 +1,4 @@
# Libraries are sourced by ./emailwiz, so variables cross files (SC2034).
# validate.sh uses `cond && pass || fail`; pass/fail/vwarn always return 0 (SC2015).
disable=SC2034,SC2015
shell=sh
+47
View File
@@ -0,0 +1,47 @@
# Changelog
## 2.0.0 (2026-10-28)
* **Renamed from `mailwiz` to `emailwiz`** (command, `/etc/emailwiz`,
`/var/backups/emailwiz`, `/var/lib/emailwiz`, `/var/log/emailwiz.log`,
`emailwiz-*` units, file names). Breaking for 1.x installs: see README
"Upgrading from mailwiz 1.x". `apply` retires the 1.x files (disabling old
timers first); the config must be copied once by hand.
* The fail2ban jail file is now `/etc/fail2ban/jail.d/emailwiz.local`, the same
name upstream used, and is replaced in place instead of retired.
* `migrate-emailwiz` is now `migrate-upstream`.
* Test fixtures use generic names (example.org); the configuration captured from
a real upstream install is kept as `tests/fixtures/upstream-install`.
Entries below describe releases published as `mailwiz`.
## 1.1.0 (2026-10-28, as mailwiz)
* New `emailwiz setup`: guided first install that reproduces the whole service on
a fresh Debian 13 host (config, packages, DNS pre-check, UFW, certificate,
plan/apply, first account, validation). It asks before each optional step;
`--non-interactive` takes values from the environment for automation. Safe to
rerun; it won't replace a different existing config without confirmation.
* New `emailwiz tls-obtain`: certbot `certonly` with `--nginx`/`--apache`
(temporary challenge, no vhost edits) or `--standalone`, depending on what
owns port 80; dry run first; real contact address.
* New `emailwiz firewall`: TCP-only UFW allow rules for the mail ports; never
touches SSH rules or policies; no-op if UFW is inactive. `plan` notes missing rules.
* `validate`: certbot timer + reload hook checks; `--renew-test`.
* `Makefile` (local, remote over SSH, lint/test/release) and `install.sh`
(atomic tool install with `.prev` copy).
* Portability: replaced `[ -nt ]` (not POSIX; flagged by Debian 13's shellcheck).
* Tests: new `setup` and `certbot` container scenarios (121 checks total).
## 1.0.1 (2026-10-28, as mailwiz)
* Fix: service reload/restart failures during `apply` were ignored (the action
runner executes inside `if !`, where `set -e` is inactive), so `apply`
could report success while a service ran its old configuration. Every step
is now checked; a failed reload falls back to a restart, and a failed
restart restores the previous files and exits 3. Found on a live server,
covered by a regression test.
* Retire the spamd `ExecReload=+` drop-in added in 1.0.0. Its rationale (Debian
tmpfiles ageing out PrivateTmp) was wrong: the PrivateTmp directories on the
affected host were deleted manually. The stock unit is fine.
* Backups no longer archive `DKIM_DIR` twice when it is inside `/etc/postfix`.
## 1.0.0 (2026-10-28, as mailwiz)
* Initial Debian 13 rewrite of emailwiz (reference `aefc7a8`).
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+120
View File
@@ -0,0 +1,120 @@
# emailwiz - Makefile
#
# On the server (needs `make`; or use `sudo sh install.sh && sudo emailwiz …`):
# sudo make install setup
# sudo make plan | apply | validate | dns | backup | audit
# sudo make user NAME=alice
#
# From your workstation over SSH (the server does not need make):
# make remote-install HOST=admin@mail.example.org
# make remote-setup HOST=admin@mail.example.org
# make remote-plan | remote-apply | remote-validate | remote-dns HOST=…
# make remote-user HOST=… NAME=alice
#
# Development:
# make lint | test | test-migration | test-clean | test-setup | test-certbot | release
#
# SPDX-License-Identifier: GPL-3.0-or-later
SHELL := /bin/sh
PREFIX ?= /usr/local
EMAILWIZ ?= $(PREFIX)/sbin/emailwiz
SSH ?= ssh
HOST ?=
NAME ?=
DOMAIN ?=
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || sed -n 's/^EMAILWIZ_VERSION=//p' emailwiz)
# Use sudo only when not already root.
SUDO := $(shell [ "$$(id -u)" -eq 0 ] || echo sudo)
SCRIPTS := emailwiz install.sh $(wildcard lib/*.sh) $(wildcard tests/*.sh) templates/certbot-deploy-hook
.DEFAULT_GOAL := help
.PHONY: help install uninstall setup plan apply validate dns backup audit user \
remote-install remote-setup remote-plan remote-apply remote-validate remote-dns remote-user \
lint test test-migration test-clean test-setup test-certbot release check-host check-name check-domain
help: ## list targets
@awk 'BEGIN {FS = ":.*## "} /^[a-z-]+:.*## / {printf " %-16s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
# ---- on the server ----------------------------------------------------------
install: ## install/upgrade the tool into $(PREFIX) (config untouched)
$(SUDO) sh ./install.sh $(PREFIX)
uninstall: ## remove the tool (keeps /etc/emailwiz, backups and mail config)
$(SUDO) rm -f $(PREFIX)/sbin/emailwiz
$(SUDO) rm -rf $(PREFIX)/lib/emailwiz $(PREFIX)/lib/emailwiz.prev
setup: check-domain install ## install, then run the interactive setup wizard
$(SUDO) env $(if $(DOMAIN),DOMAIN=$(DOMAIN)) $(EMAILWIZ) setup
plan: ## show pending changes (read-only)
$(SUDO) $(EMAILWIZ) plan
apply: ## back up, apply, validate, reload
$(SUDO) $(EMAILWIZ) apply
validate: ## full validation incl. local delivery test
$(SUDO) $(EMAILWIZ) validate --deliver-test
dns: ## print required DNS records
$(SUDO) $(EMAILWIZ) dns
backup: ## snapshot config + DKIM key + mailboxes
$(SUDO) $(EMAILWIZ) backup --with-mail
audit: ## read-only system report
$(SUDO) $(EMAILWIZ) audit
user: check-name ## create mail account NAME and set its password (prompts)
$(SUDO) $(EMAILWIZ) user add $(NAME)
$(SUDO) passwd $(NAME)
# ---- from a workstation -------------------------------------------------------
# The tree is sent with git archive (committed files only) and installed by
# install.sh; later targets call emailwiz directly. -t keeps prompts working.
remote-install: check-host ## copy this checkout to HOST and install it
git archive --format=tar HEAD | $(SSH) $(HOST) \
'set -e; t=$$(mktemp -d); trap "rm -rf $$t" EXIT; tar -C $$t -xf -; sudo sh $$t/install.sh $(PREFIX)'
remote-setup: check-host check-domain remote-install ## install on HOST and run the setup wizard there
$(SSH) -t $(HOST) 'sudo env $(if $(DOMAIN),DOMAIN=$(DOMAIN)) $(EMAILWIZ) setup'
remote-plan: check-host ## plan on HOST
$(SSH) -t $(HOST) 'sudo $(EMAILWIZ) plan'
remote-apply: check-host ## apply on HOST (asks for confirmation)
$(SSH) -t $(HOST) 'sudo $(EMAILWIZ) apply'
remote-validate: check-host ## validate on HOST
$(SSH) -t $(HOST) 'sudo $(EMAILWIZ) validate --deliver-test'
remote-dns: check-host ## DNS records for HOST
$(SSH) $(HOST) 'sudo $(EMAILWIZ) dns'
remote-user: check-host check-name ## create account NAME on HOST (password prompt)
$(SSH) -t $(HOST) 'sudo $(EMAILWIZ) user add $(NAME) && sudo passwd $(NAME)'
# ---- development --------------------------------------------------------------
lint: ## shellcheck + sh -n + dash -n
shellcheck -x -P lib $(SCRIPTS)
for f in $(SCRIPTS); do sh -n "$$f"; done
if command -v dash >/dev/null; then for f in emailwiz lib/*.sh; do dash -n "$$f"; done; fi
test: ## all container scenarios (docker)
sh tests/run.sh all
test-migration: ## migration scenario only
sh tests/run.sh migration
test-clean: ## clean-install scenario only
sh tests/run.sh clean
test-setup: ## setup wizard scenario only
sh tests/run.sh setup
test-certbot: ## certbot issuance scenario only (stubbed certbot)
sh tests/run.sh certbot
release: lint ## build dist/emailwiz-VERSION.tar.gz (+ .sha256) from a clean tag
@git diff --quiet HEAD || { echo "working tree is dirty"; exit 1; }
@git describe --tags --exact-match >/dev/null 2>&1 || { echo "HEAD is not tagged"; exit 1; }
mkdir -p dist
git archive --format=tar.gz --prefix=emailwiz-$(VERSION)/ -o dist/emailwiz-$(VERSION).tar.gz HEAD
cd dist && sha256sum emailwiz-$(VERSION).tar.gz > emailwiz-$(VERSION).tar.gz.sha256
@echo "dist/emailwiz-$(VERSION).tar.gz"
# ---- argument checks (values end up in shell commands) -------------------------
check-host:
@[ -n "$(HOST)" ] || { echo "set HOST=user@server"; exit 2; }
@printf '%s' '$(HOST)' | grep -Eq '^[A-Za-z0-9._@-]+$$' || { echo "invalid HOST"; exit 2; }
check-name:
@printf '%s' '$(NAME)' | grep -Eq '^[a-z][a-z0-9_-]{0,31}$$' || { echo "set NAME=<user> (a-z, 0-9, _ -)"; exit 2; }
check-domain:
@[ -z "$(DOMAIN)" ] || printf '%s' '$(DOMAIN)' | grep -Eq '^[A-Za-z0-9.-]+$$' || { echo "invalid DOMAIN"; exit 2; }
+270
View File
@@ -0,0 +1,270 @@
# emailwiz (Debian 13 fork)
Set up and maintain a single-domain Postfix + Dovecot + OpenDKIM +
SpamAssassin mail server on **Debian 13 (trixie)**.
This is a fork and rewrite of [Luke Smith's emailwiz](https://github.com/LukeSmithxyz/emailwiz)
(reference revision `aefc7a8`, 2026-10-17). It is **not** the upstream
project. It keeps upstream's architecture and mailbox layout, so servers
installed with upstream `emailwiz.sh` migrate in place. The one-shot script is
replaced by a tool you can rerun safely: guided setup, `plan`/`apply` with
backups, validation and rollback. Upstream's script does not work on Debian 13
(see `docs/UPSTREAM-REVIEW.md`). Licensed GPL-3.0-or-later, like the original
(see `LICENSE`).
* Version: 2.0.0
* Tested on: Debian 13.7, postfix 3.10.13, dovecot 2.4.1, opendkim 2.11.0~beta2,
spamd 4.0.1, fail2ban 1.1.0 (see `docs/COMPATIBILITY.md`)
* Differences from upstream: `docs/UPSTREAM-REVIEW.md`
## Quick start: a new server
Requirements: a Debian 13 server you can SSH into with sudo, a domain, and an
`A` record `mail.DOMAIN → server IP` (needed for the certbot certificate).
```sh
# from your workstation, in this repository
make remote-setup HOST=admin@203.0.113.10 DOMAIN=example.org
# or on the server itself
sudo apt install make # or skip make: sudo sh install.sh && sudo emailwiz setup
sudo make setup DOMAIN=example.org
```
`setup` walks through 8 steps and **asks** before each optional one:
| # | Step | Asks |
|---|---|---|
| 1 | configuration (`/etc/emailwiz/emailwiz.conf`) | domain, mail host name, postmaster user, certificate mode (`certbot` or existing files) |
| 2 | install missing packages (never removes any) | – |
| 3 | DNS pre-check (read-only, warns only) | – |
| 4 | UFW: allow 25, 465, 587, 993 (+995, +80 for certbot), TCP only; SSH rules and policies untouched; skipped if UFW is inactive | yes/no |
| 5 | certificate: certbot `certonly` (`--nginx`/`--apache` if a web server owns port 80, which only adds the challenge temporarily; `--standalone` otherwise), dry run first | – |
| 6 | `plan`, then `apply` (backup, validation, automatic restore on failure) | yes/no |
| 7 | first mail account, password typed into `passwd` | yes/no, name |
| 8 | validation incl. a local delivery test; DNS records saved to `/root/emailwiz-dns.txt` | – |
Then publish the DNS records, ask your provider for the PTR record, and run
`sudo emailwiz validate --external-test you@gmail.com`. Setup is safe to
rerun; an existing, different config is only replaced after confirmation.
Unattended (CI, provisioning):
```sh
sudo env DOMAIN=example.org ROOT_ALIAS=admin TLS_MODE=certbot \
SETUP_UFW=yes SETUP_USER=alice emailwiz setup --non-interactive
sudo passwd alice
```
### Makefile targets
| On the server (`sudo make …`) | From a workstation (`make … HOST=user@server`) | Development |
|---|---|---|
| `install`, `uninstall` | `remote-install` (sends committed files via `git archive`) | `lint` |
| `setup [DOMAIN=]` | `remote-setup [DOMAIN=]` | `test`, `test-migration`, `test-clean`, `test-setup`, `test-certbot` |
| `plan`, `apply`, `validate`, `dns`, `backup`, `audit` | `remote-plan`, `remote-apply`, `remote-validate`, `remote-dns` | `release` (tagged, clean tree → `dist/*.tar.gz` + `.sha256`) |
| `user NAME=` | `remote-user NAME=` | `help` |
Remote targets only need `ssh` + `sudo` on the server, not `make`.
## Architecture
| Function | Component | Notes |
|---|---|---|
| Inbound SMTP (MX) | Postfix :25 | STARTTLS optional (RFC 3207), **no AUTH** |
| Client submission | Postfix :587 (STARTTLS required) and :465 (implicit TLS) | SASL via Dovecot; sender must match login |
| Spam filtering | spamd via `spamc` pipe on :25 | spam is filed into `Junk` by a default Sieve script |
| DKIM | OpenDKIM on 127.0.0.1:12301 | signs `@DOMAIN`, verifies inbound |
| Mailbox access | Dovecot IMAP :993 (+ POP3 :995 optional) | TLS required; 143/110 only with STARTTLS |
| Accounts | local system users in group `mail`, passwords via PAM | Maildir in `~/Mail` |
| Brute force | fail2ban jails `postfix`, `postfix-sasl`, `dovecot` (+ `sshd` from Debian) | systemd journal backend |
There is no database, webmail, or virtual-user layer. One domain per install.
## Files emailwiz owns
| Path | How |
|---|---|
| `/etc/postfix/main.cf`, `master.cf` | edited only with `postconf -e/-M/-P/-X` on a **copy**, then swapped in atomically; unmanaged settings are preserved |
| `/etc/postfix/login_maps.pcre`, `emailwiz_outbound_header_checks` | rendered |
| `/etc/dovecot/dovecot.conf` | rendered from `templates/dovecot.conf.in` (whole file) |
| `/etc/opendkim.conf`, `$DKIM_DIR/{keytable,signingtable,trustedhosts}` | rendered |
| `$DKIM_DIR/$DOMAIN/$SELECTOR.private` | generated **only if missing**; never overwritten |
| `/etc/default/spamd` | only the `OPTIONS=` line |
| `/etc/fail2ban/jail.d/emailwiz.local` | rendered |
| `/etc/aliases` | only adds `postmaster:`/`root:` when missing |
| `/var/lib/dovecot/sieve/default.sieve` | rendered + compiled |
| `/etc/systemd/system/emailwiz-{certcheck,backup}.{service,timer}` | rendered |
emailwiz never purges packages, never touches mailboxes, SSH or DNS, and never
deletes a file without first copying it into the run's backup ("retire").
Firewall rules and certificates are only changed by `setup`, `firewall` and
`tls-obtain`, and only with your confirmation (or explicit `SETUP_*`
variables in non-interactive mode).
## Install or upgrade the tool only
```sh
sudo sh install.sh # or: sudo make install / make remote-install HOST=…
```
Installs to `/usr/local/lib/emailwiz` (previous version kept as `emailwiz.prev`)
with `/usr/local/sbin/emailwiz`. Mail configuration is not touched; run
`sudo emailwiz plan` afterwards.
## Usage
```sh
sudo emailwiz setup # guided first install (see Quick start)
sudo emailwiz audit # read-only report
sudo emailwiz init example.org # writes /etc/emailwiz/emailwiz.conf; review it
sudo emailwiz install-packages # clean installs only: apt-get install, never purge
sudo emailwiz plan # show exact diffs; changes nothing
sudo emailwiz apply # backup -> install -> validate -> reload (asks first)
sudo emailwiz validate # config, services, TLS, relay policy, DNS
sudo emailwiz validate --deliver-test # + local delivery & DKIM signing
sudo emailwiz validate --external-test you@gmail.com # + real outbound delivery (opt-in)
sudo emailwiz dns # DNS records this host needs
sudo emailwiz tls-obtain # (re)obtain the certbot certificate (TLS_MODE=certbot)
sudo emailwiz firewall # add missing UFW rules for mail ports (asks)
sudo emailwiz validate --renew-test # + certbot renew --dry-run
sudo emailwiz user add alice && sudo passwd alice
```
`plan` and `apply` share one code path: every component renders its desired
files into a temporary staging tree. `plan` diffs that tree against the live
system and deletes it. `apply` additionally:
1. creates a verified backup in `/var/backups/emailwiz/<timestamp>-apply/` (0700);
2. generates the DKIM key if it is missing;
3. installs changed files atomically (temp file + `rename`);
4. runs `postfix check`, `doveconf -n`, `opendkim -n`, `fail2ban-client -t`;
5. reloads/restarts only the services whose inputs changed (a failed reload
falls back to a restart; a failed restart fails the apply);
6. checks that every service is active.
If step 4, 5 or 6 fails, the files from this run are restored automatically
and the command exits 3.
### Configuration (`/etc/emailwiz/emailwiz.conf`)
Sourced by `/bin/sh`. Must be owned by root and not group/world writable.
| Variable | Default | Meaning |
|---|---|---|
| `DOMAIN` | required | mail domain (`user@DOMAIN`) |
| `MAIL_HOSTNAME` | `mail.$DOMAIN` | MX host name, HELO, certificate name |
| `ROOT_ALIAS` | – | local user receiving root/postmaster mail (strongly recommended) |
| `TLS_MODE` | `external` | `external`: cert managed elsewhere; `certbot`: obtained by `setup`/`tls-obtain` into `/etc/letsencrypt/live/$MAIL_HOSTNAME`, renewed by `certbot.timer`, reload hook installed |
| `TLS_CERT`, `TLS_KEY` | – | full chain / private key paths |
| `CERT_WARN_DAYS` | 21 | expiry warning threshold (daily timer mails postmaster) |
| `DKIM_SELECTOR` | `mail` | DKIM selector |
| `DKIM_DIR` | `/etc/postfix/dkim` | emailwiz-compatible key location |
| `DKIM_BITS` | 2048 | size of a newly generated key |
| `IMAP_PROTOCOLS` | `imap pop3` | set to `imap` to disable POP3 |
| `SPAM_FILTER` | `spamc` | `none` disables the SpamAssassin pipe |
| `SPAMD_MAX_CHILDREN` | 2 | spamd children (~80–100 MiB each) |
| `STRIP_OUTBOUND_RECEIVED` | `yes` | remove `Received:` on outbound SMTP (hides client IPs); inbound headers are kept |
| `SMTP_ADDRESS_PREFERENCE` | `auto` | `auto`: IPv4 unless the host has global IPv6 |
| `FAIL2BAN` | `yes` | manage mail jails |
| `EMAILWIZ_TIMERS` | `yes` | cert-expiry (daily) and config backup (weekly) timers |
### Exit codes
`0` ok · `1` error · `2` usage/config error · `3` validation failed (and was
rolled back during apply) · `4` unsupported OS · `10` `plan --detailed-exitcode`
found pending changes.
## Rerunning safely
* `plan`, `validate`, `audit`, `dns`, `cert-check`, `backups` are read-only:
run them any time.
* `apply` is idempotent: a second run reports "nothing to do". Run
`plan` first and read the diff.
* `backup` is safe to repeat. Scheduled backups are pruned to `BACKUP_KEEP`,
manual and apply backups are never pruned automatically.
* **One-time** operations: `migrate-upstream --fix-pam` (idempotent, but
changes authentication: test an IMAP login afterwards); the first `apply`
on a host installed by upstream emailwiz (replaces its leftovers); DKIM key generation
(happens once per selector; new selector = new DNS record).
* After `apt upgrade`, run `sudo emailwiz plan`. Package conffile prompts can
restore Debian defaults, which `plan` will show.
## Migrating a server installed by upstream emailwiz.sh
1. `sudo emailwiz audit` lists upstream leftovers.
2. `sudo emailwiz init DOMAIN`. It picks up the current cert paths from Postfix.
3. `sudo emailwiz plan` shows, among others, replacing upstream's
`/etc/fail2ban/jail.d/emailwiz.local` (drops `[sieve]`) and retiring the
OpenDKIM `override.conf`.
4. `sudo emailwiz apply`, then `sudo emailwiz validate --deliver-test`.
5. Optional: `sudo emailwiz migrate-upstream --fix-pam` (removes upstream's
`nullok` PAM line, which permits empty passwords).
The DKIM key, mailboxes, Sieve scripts, aliases and users stay as they are.
## Upgrading from mailwiz 1.x
Releases 1.x of this fork were called `mailwiz` (`/etc/mailwiz`,
`/usr/local/sbin/mailwiz`, `mailwiz-*` units). Upgrade path:
```sh
sudo install -D -m 0644 /etc/mailwiz/mailwiz.conf /etc/emailwiz/emailwiz.conf
sudo sh install.sh # installs /usr/local/sbin/emailwiz
sudo emailwiz plan # retires the mailwiz-* files, installs the emailwiz-* ones
sudo emailwiz apply
sudo emailwiz validate --deliver-test
# afterwards, remove the old tool (backups in /var/backups/mailwiz are kept):
sudo rm -rf /usr/local/lib/mailwiz /usr/local/lib/mailwiz.prev /usr/local/sbin/mailwiz /etc/mailwiz
```
`apply` disables the old `mailwiz-*` timers before retiring their unit
files. Old backups remain readable with `tar`, but `emailwiz rollback` only
lists `/var/backups/emailwiz`.
## Backup and rollback
See `docs/ROLLBACK.md`. In short:
```sh
sudo emailwiz backups # list
sudo emailwiz backup --with-mail # include ~/Mail of group-mail users
sudo emailwiz rollback 20261028-150102-apply # restore config from that snapshot
```
Backups stay on the server. Copy `/var/backups/emailwiz` off-host regularly;
it contains the DKIM private key, so keep the copy encrypted.
## Testing
```sh
tests/run.sh # shellcheck + sh -n + all container scenarios (needs docker)
tests/run.sh migration # reproduce an upstream emailwiz install, migrate, roll back
tests/run.sh clean # fresh Debian 13 install
tests/run.sh setup # make install + setup --non-interactive, UFW, first user, rerun, config protection
tests/run.sh certbot # certbot path with a stub certbot (authenticator choice, hook, renew check)
```
Real Let's Encrypt issuance cannot run in the offline test container: the
certbot scenario checks the exact certbot invocations instead.
The containers run systemd as PID 1 with the real Debian packages and a
test-only CA. They cover plan read-onlyness, refusal paths, apply,
idempotence, DKIM signing (verified with dkimpy), SASL submission on 587/465,
sender spoofing, unauthenticated submission, AUTH exposure on 25, IMAPS
login, rollback, and the PAM migration. They cannot test real DNS, PTR,
external delivery, or provider port filtering; run `emailwiz validate` with
`--external-test` on the server for those.
## Troubleshooting
| Symptom | Check |
|---|---|
| `apply` exits 3 | the message names the failing check; config was restored. `journalctl -u postfix -u dovecot -u opendkim -n 50` |
| mail to Gmail/Outlook rejected | `sudo emailwiz validate` (PTR, SPF, DKIM DNS match); `journalctl -t postfix/smtp -n 50` |
| no DKIM signature | `journalctl -t opendkim`; sender domain must be `@DOMAIN`; `ss -ltn sport = :12301` |
| client cannot log in | use port 993/465/587 with TLS and the **bare user name**; `journalctl -u dovecot -n 50`; `fail2ban-client status dovecot` |
| "Sender address rejected: not owned by user" | the From address local part must equal the login name (`alice` → `alice@` / `alice+tag@`) |
| local mail deferred "temporary failure" | `root` has no alias, so mail to it is written as `nobody`: set `ROOT_ALIAS`, `apply` |
| spam not filtered | `systemctl status spamd`; header `X-Spam-Status` on inbound mail |
| port 25 outbound blocked | `sudo emailwiz validate`: "Outbound SMTP reachability"; ask the provider |
+26
View File
@@ -0,0 +1,26 @@
# Compatibility matrix
Supported target: **Debian 13 (trixie)** only. emailwiz exits with code 4 on
other releases. Debian 12 ships Dovecot 2.3, whose syntax the template does
not use. Set `EMAILWIZ_ALLOW_UNSUPPORTED=yes` to override (not recommended).
| Package | Debian 13 version tested (13.7, container and a live server) | Notes |
|---|---|---|
| postfix / postfix-pcre | 3.10.13-0+deb13u1 | `>=TLSv1.2` protocol syntax, `smtpd_forbid_bare_newline` |
| dovecot-core/-imapd/-pop3d/-sieve | 1:2.4.1+dfsg1-6+deb13u7 | 2.4 config syntax (`dovecot_config_version = 2.4.1`) is required |
| opendkim / opendkim-tools | 2.11.0~beta2-9.1+b1 | Debian unit reads `Socket`/`PidFile` from `opendkim.conf` |
| spamd / spamc | 4.0.1-5 | `spamd.service`, `spamassassin-maintenance.timer` |
| fail2ban | 1.1.0-8 | `backend = systemd` from `defaults-debian.conf`; no rsyslog needed |
| openssl | 3.5.7-1~deb13u3 | |
| bind9-host | 1:9.20.30-1~deb13u1 | `host` used by validate/dns |
| dns-root-data | 2025080400~deb13u1 | `TrustAnchorFile` for OpenDKIM DNSSEC |
| certbot | 4.0.0-2+deb13u1 | only for `TLS_MODE=certbot` (issuance tested with a stub; see README) |
| systemd | 257.13-1~deb13u1 | |
Debian 13 facts the implementation relies on (each checked in the container):
* no `/var/log/mail.log`: rsyslog is not installed by default, so everything uses the journal;
* no `netstat` by default (net-tools not installed);
* `/usr/lib/dovecot/dovecot-lda` exists (`deliver` is a compatibility symlink);
* `spamassassin.service` does not exist; `/etc/default/spamd` has no `CRON=`;
* `doveconf -c FILE -n` and `opendkim -n -x FILE` validate an alternative config file.
+66
View File
@@ -0,0 +1,66 @@
# Backup and rollback
## What is backed up
`emailwiz backup` and every `emailwiz apply` write
`/var/backups/emailwiz/<YYYYmmdd-HHMMSS>-<label>/` (directory mode 0700, files 0600):
* `config.tar.gz`: `/etc/postfix` (includes the DKIM keys in `/etc/postfix/dkim`),
`/etc/dovecot`, `/etc/opendkim.conf`, `/etc/default/{opendkim,spamd}`,
`/etc/fail2ban/jail.d`, the opendkim/spamd systemd drop-ins, emailwiz timers,
`/etc/aliases`, `/etc/pam.d/dovecot`, `/etc/mailname`, `/etc/emailwiz`,
`/var/lib/dovecot/sieve`, and the certbot deploy hook;
* `MANIFEST`: file list; `SHA256SUMS`: archive checksum (verified at creation);
* `created`: files the corresponding `apply` created (removed on rollback);
* `retired/`: second copy of files an `apply` retired.
`--with-mail` also archives `~/Mail` of every member of group `mail`.
Mailboxes are **never** restored by `rollback`; restore them manually if ever needed:
`sudo tar -C / -xpzf …/config.tar.gz home/USER/Mail`.
## Automatic rollback
`apply` restores the files from its own backup if `postfix check`, `doveconf`,
`opendkim -n` or `fail2ban-client -t` fail, if a reload/restart fails, or if
a service is inactive afterwards. It then exits with status 3.
## Manual rollback
```sh
sudo emailwiz backups
sudo emailwiz rollback 20261028-150102-apply # the apply you want to undo
sudo emailwiz validate
```
`rollback` verifies the checksum, saves the current state as a
`pre-rollback` backup, removes files the original apply created, extracts
the archive, runs `newaliases`, restarts the mail services and checks they
are active.
## Without emailwiz (last resort)
```sh
B=/var/backups/emailwiz/<id>
sudo sh -c "cd $B && sha256sum -c SHA256SUMS"
sudo tar -C / --numeric-owner -xpzf $B/config.tar.gz
sudo xargs -r rm -f < $B/created
sudo systemctl daemon-reload
sudo newaliases
sudo systemctl restart opendkim postfix dovecot spamd fail2ban
```
## When to roll back
* `emailwiz validate` reports FAIL items that weren't present before the apply;
* mail stops arriving (`journalctl -u postfix -f` shows rejects) or clients cannot log in;
* outbound mail is no longer DKIM-signed (`journalctl -t opendkim`).
## Off-host copies
Backups live on the same disk as the server. Periodically copy them off the host,
encrypted, because they contain the DKIM private key:
```sh
# on your workstation
ssh admin@mail.example.org 'sudo tar -C /var/backups -czf - emailwiz' | gpg -c > emailwiz-backups-$(date +%F).tar.gz.gpg
```
+56
View File
@@ -0,0 +1,56 @@
# Review of upstream emailwiz against Debian 13
Upstream: https://github.com/LukeSmithxyz/emailwiz, HEAD `aefc7a88f95a049a7f6a1adb4050633b69869bc6`
(2026-10-17, "Fix bash-only syntax in adddomain.sh"). 218 commits. Before that,
the last functional change was in 2025-05. Upstream still writes Dovecot 2.3 syntax.
"Verified" means reproduced in a Debian 13.7 container (`tests/Containerfile`)
or observed on a real server installed with upstream emailwiz. "Static" means found by reading the code.
## Blocking on Debian 13
| # | Problem | Evidence | This fork |
|---|---|---|---|
| U1 | **Dovecot 2.4 rejects the generated `dovecot.conf`.** Missing `dovecot_config_version` (fatal at line 1), then `ssl_cert`/`ssl_key`/`ssl_dh`/`ssl_prefer_server_ciphers`, `mail_location`, `%n`, `protocols = $protocols`, `mail_plugins = $mail_plugins sieve`, `pop3_uidl_format %08Xu%08Xv`, `plugin { sieve… }` are all removed or renamed | verified: `doveconf: Fatal: … The first setting must be dovecot_config_version`, then `ssl_cert: Unknown setting` | 2.4 template validated with `doveconf -c` before install |
| U2 | Exits unless the domain has an **AAAA** record, *after* already purging/reinstalling packages and stopping services | static (l.22–61) | IPv6 optional; AAAA/SPF ip6 only when the host has global IPv6 |
| U3 | `service spamassassin …` / `/etc/default/spamassassin` path; Debian 13 has only `spamd.service` and `spamassassin-maintenance.timer`; `CRON=` is gone | verified: no `spamassassin.service`; `/etc/default/spamd` has no `CRON` | manages `spamd` only |
| U4 | `netstat` (net-tools) used to detect the web server; not installed on Debian 13 | verified: `no netstat` | not needed (certbot is optional and webserver-agnostic) |
## Destructive or unsafe behaviour
| # | Problem | This fork |
|---|---|---|
| U5 | `apt-get purge ?config-files -y $install_packages` **purges the mail packages' configs** on every run (the pattern also matches the explicit package list), after `systemctl stop postfix dovecot`: mail is down for the entire run and all config is lost | never purges; services keep running; reload only what changed |
| U6 | `mv dovecot.conf dovecot.backup.conf`: second run overwrites the only backup with emailwiz's own file | timestamped, checksummed backups in `/var/backups/emailwiz` |
| U7 | `sed -i '/^\s*-o/d;/^\s*submission/d;/^\s*smtp/d' master.cf` deletes **every** `-o` line of every service, then appends; the `spamassassin` service is appended again each run | `postconf -M/-P` per service; stale overrides removed deterministically |
| U8 | `>> header_checks`, `>> pam.d/dovecot`, `>> opendkim.conf`, `>> cli.ini`: duplicate lines on rerun | rendered files, compared before install |
| U9 | appends `auth required pam_unix.so nullok` to `/etc/pam.d/dovecot`: **empty passwords permitted** for IMAP/SMTP | not done; `migrate-upstream --fix-pam` removes it |
| U10 | `opendkim-genkey` on every run **replaces the DKIM key** (the published DNS key then no longer matches, so DMARC `p=reject` drops your mail) | key generated only if missing |
| U11 | `useradd vmail` + `chown -R vmail:vmail /var/lib/dovecot` changes ownership of Dovecot's state directory to an unused account | not done |
| U12 | `sed -i … /etc/fail2ban/jail.conf` edits a package conffile (Debian 13 already sets `backend = systemd` in `defaults-debian.conf`) | `jail.d/emailwiz.local` |
| U13 | `ufw allow` for 80 993 465 25 587 110 995 **TCP and UDP**, both families, unconditionally | firewall left to the admin (documented) |
## Functional and security defects
| # | Problem | Seen on a real install | This fork |
|---|---|---|---|
| U14 | `header_checks` removes `Received:` from **all** mail, including inbound, so SpamAssassin cannot score the relay path | yes | `smtp_header_checks`: outbound only |
| U15 | port 465 (`smtps`) has no `smtpd_client_restrictions`: unauthenticated clients can deliver to local users **bypassing SpamAssassin** (content_filter is on :25 only) | config yes; behaviour reproduced (`tests`) | 465/587 require SASL |
| U16 | `smtpd_sasl_auth_enable = yes` globally: AUTH offered on the MX port 25 | yes | AUTH only on 587/465 |
| U17 | `smtp_tls_CAfile = $certdir/cert.pem`: the server's **own leaf cert** used as the CA bundle for outbound TLS | n/a (that host used the system bundle) | system CA bundle |
| U18 | milter `inet:localhost:12301`: `localhost` resolves to `::1` first while OpenDKIM binds 127.0.0.1 only | yes (`getent ahosts localhost`) | `inet:127.0.0.1:12301` on both sides |
| U19 | `/lib/opendkim/opendkim.service.generate` + `ExecStart` override duplicates/overrides `Socket` from `opendkim.conf` | yes | override retired; socket set in `opendkim.conf` only |
| U20 | login map escapes only the first `.` of the domain (`sed 's/\./\\\./'`) | – | all dots escaped; `user+tag@` allowed |
| U21 | fail2ban `[sieve]` jail enabled though managesieve isn't installed; with the systemd backend it has no journal match | yes | not enabled |
| U22 | certbot `deploy-hook` written into `cli.ini` (global) with `grep -q` against an unanchored domain; HTTP-01 via `--register-unsafely-without-email` | – | per-hook script in `renewal-hooks/deploy`, exact domain match |
| U23 | 4096-bit self-signed cert valid for 100 years as a code path | – | removed |
| U24 | no `set -e`; every step prints "...done" regardless of result | – | `set -eu`, explicit validation, exit codes |
| U25 | `/etc/cron.weekly/postmaster-clean` deletes files matching `*.mail*` older than 30 d: matches only when the hostname contains "mail" | – | not installed (postmaster is aliased to a real user) |
## Kept from upstream (deliberately)
Postfix + Dovecot + OpenDKIM + SpamAssassin, system users with PAM, Maildir at
`~/Mail` with `LAYOUT=fs` folder names, `Junk` autoexpunge, the default Sieve
spam rule, `reject_sender_login_mismatch`, and the DKIM path
`/etc/postfix/dkim/<domain>/<selector>.private`. Existing emailwiz installs
therefore migrate without touching mail or DNS.
Executable
+106
View File
@@ -0,0 +1,106 @@
#!/bin/sh
# emailwiz - plan/apply/validate a Postfix + Dovecot + OpenDKIM mail server on Debian 13
#
# Copyright (C) 2026 contributors to this Debian 13 fork of emailwiz
# Derived from emailwiz by Luke Smith and contributors
# https://github.com/LukeSmithxyz/emailwiz (reference revision aefc7a8)
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version. See LICENSE.
# SPDX-License-Identifier: GPL-3.0-or-later
set -eu
umask 022
export LC_ALL=C PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
EMAILWIZ_VERSION=2.0.0
_self=$0
while [ -L "$_self" ]; do
_l=$(readlink "$_self")
case $_l in /*) _self=$_l ;; *) _self=$(dirname "$_self")/$_l ;; esac
done
EMAILWIZ_ROOT=$(cd "$(dirname "$_self")" && pwd)
for _lib in common config detect postfix dovecot opendkim services tls firewall engine validate ops setup; do
# shellcheck disable=SC1090
. "$EMAILWIZ_ROOT/lib/$_lib.sh"
done
usage() {
cat <<EOF
emailwiz $EMAILWIZ_VERSION - Debian 13 mail server management (emailwiz successor)
usage: emailwiz COMMAND [options]
Read-only:
audit report platform, packages, services, emailwiz leftovers
plan [--component C] [--detailed-exitcode] [--no-diff]
show the changes apply would make (changes nothing;
--detailed-exitcode exits 10 if changes are pending)
validate [--no-dns] [--deliver-test] [--external-test ADDR] [--renew-test]
check config, services, TLS, relay policy, DNS;
--deliver-test sends a local test message,
--external-test sends one to ADDR (explicit opt-in),
--renew-test runs certbot renew --dry-run
dns print the DNS records this host needs
cert-check [--notify] certificate expiry check (used by the timer)
backups list backups
Changes:
setup [--non-interactive] guided first install: config, packages, firewall,
certificate, apply, first account, validation
init [DOMAIN] write /etc/emailwiz/emailwiz.conf from detected values
install-packages install missing Debian packages (never purges)
apply [--component C] [--yes]
back up, install the desired config, validate, reload
backup [--with-mail] snapshot configuration + DKIM keys (+ ~/Mail)
rollback BACKUP_ID [--yes] restore a configuration snapshot
tls-obtain obtain the certbot certificate (TLS_MODE=certbot)
firewall [--yes] add UFW allow rules for the mail ports (TCP only)
migrate-upstream [--fix-pam]
one-time cleanup of upstream emailwiz leftovers
user add NAME | user list manage mail accounts (system users in group mail)
Components: $COMPONENTS
Exit codes: 0 ok, 1 error, 2 usage, 3 validation failed, 4 unsupported OS, 10 changes pending
Config: \$EMAILWIZ_CONF (default /etc/emailwiz/emailwiz.conf)
EOF
}
preflight() {
detect_os
config_load
config_validate
_m=$(missing_packages)
[ -z "$_m" ] || die "missing packages: $_m (run: sudo emailwiz install-packages)" "$EX_ERR"
detect_versions
[ -r "$TLS_CERT" ] || die "TLS_CERT $TLS_CERT not readable"
[ -r "$TLS_KEY" ] || die "TLS_KEY $TLS_KEY not readable"
}
cmd=${1:-help}
[ $# -gt 0 ] && shift
case $cmd in
audit) cmd_audit "$@" ;;
plan) cmd_plan "$@" ;;
apply) cmd_apply "$@" ;;
validate) cmd_validate "$@" ;;
dns) cmd_dns "$@" ;;
cert-check) cmd_cert_check "$@" ;;
backup) cmd_backup "$@" ;;
backups) cmd_backups "$@" ;;
rollback) cmd_rollback "$@" ;;
init) cmd_init "$@" ;;
setup) cmd_setup "$@" ;;
tls-obtain) cmd_tls_obtain "$@" ;;
firewall) cmd_firewall "$@" ;;
install-packages) cmd_install_packages "$@" ;;
migrate-upstream) cmd_migrate_upstream "$@" ;;
user) cmd_user "$@" ;;
version | --version) echo "emailwiz $EMAILWIZ_VERSION" ;;
help | -h | --help) usage ;;
*) usage >&2; exit "$EX_USAGE" ;;
esac
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
# Install (or upgrade) the emailwiz tool itself. Never touches mail configuration.
# usage: sudo sh install.sh [PREFIX] (default PREFIX=/usr/local)
# SPDX-License-Identifier: GPL-3.0-or-later
set -eu
PREFIX=${1:-/usr/local}
SRC=$(cd "$(dirname "$0")" && pwd)
DEST=$PREFIX/lib/emailwiz
[ "$(id -u)" -eq 0 ] || { echo "install.sh: run as root" >&2; exit 1; }
[ -x "$SRC/emailwiz" ] || { echo "install.sh: $SRC is not a emailwiz tree" >&2; exit 1; }
# Stage next to the destination, then swap with rename; keep one .prev copy.
rm -rf "$DEST.new"
install -d -m 0755 "$DEST.new"
for f in emailwiz install.sh Makefile LICENSE README.md CHANGELOG.md; do
[ -e "$SRC/$f" ] && cp -p "$SRC/$f" "$DEST.new/"
done
for d in lib templates docs; do
cp -R "$SRC/$d" "$DEST.new/"
done
chown -R root:root "$DEST.new"
chmod -R u=rwX,go=rX "$DEST.new"
chmod 0755 "$DEST.new/emailwiz"
sh -n "$DEST.new/emailwiz"
for f in "$DEST.new"/lib/*.sh; do sh -n "$f"; done
if [ -d "$DEST" ]; then
rm -rf "$DEST.prev"
mv "$DEST" "$DEST.prev"
fi
mv "$DEST.new" "$DEST"
install -d -m 0755 "$PREFIX/sbin"
ln -sfn "$DEST/emailwiz" "$PREFIX/sbin/emailwiz"
echo "installed $("$PREFIX/sbin/emailwiz" version) to $DEST (previous copy: $DEST.prev)"
+181
View File
@@ -0,0 +1,181 @@
# emailwiz - common helpers (logging, staging, atomic install, backups)
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
# Exit codes
EX_OK=0
EX_ERR=1
EX_USAGE=2
EX_VALIDATION=3
EX_UNSUPPORTED=4
EX_PENDING=10 # plan --detailed-exitcode: changes pending
EMAILWIZ_LOG=${EMAILWIZ_LOG:-/var/log/emailwiz.log}
EMAILWIZ_STATE=${EMAILWIZ_STATE:-/var/lib/emailwiz}
EMAILWIZ_BACKUPS=${EMAILWIZ_BACKUPS:-/var/backups/emailwiz}
if [ -t 2 ]; then
C_RED=$(printf '\033[31m'); C_YEL=$(printf '\033[33m')
C_GRN=$(printf '\033[32m'); C_BLU=$(printf '\033[34m'); C_OFF=$(printf '\033[0m')
else
C_RED=; C_YEL=; C_GRN=; C_BLU=; C_OFF=
fi
_logfile() {
# Only real (non-plan) runs as root write the persistent log.
[ "${MODE:-}" = apply ] || return 0
[ "$(id -u)" -eq 0 ] || return 0
printf '%s [%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" "$2" >>"$EMAILWIZ_LOG" 2>/dev/null || :
}
log() { printf '%s==>%s %s\n' "$C_BLU" "$C_OFF" "$*" >&2; _logfile INFO "$*"; }
info() { printf ' %s\n' "$*" >&2; _logfile INFO "$*"; }
ok() { printf '%s ok%s %s\n' "$C_GRN" "$C_OFF" "$*" >&2; _logfile OK "$*"; }
warn() { printf '%swarn%s %s\n' "$C_YEL" "$C_OFF" "$*" >&2; _logfile WARN "$*"; }
err() { printf '%serror%s %s\n' "$C_RED" "$C_OFF" "$*" >&2; _logfile ERROR "$*"; }
die() { err "$1"; exit "${2:-$EX_ERR}"; }
have() { command -v "$1" >/dev/null 2>&1; }
need_root() {
[ "$(id -u)" -eq 0 ] || die "this command must run as root (try: sudo emailwiz $*)" "$EX_ERR"
}
# --- staging -----------------------------------------------------------------
# Desired state is rendered under $STAGE, mirroring the filesystem, e.g.
# $STAGE/etc/dovecot/dovecot.conf. $STAGE/.meta lists "path mode owner group
# reload-unit" for every staged file; $STAGE/.retire lists files to retire.
stage_init() {
STAGE=$(mktemp -d "${TMPDIR:-/tmp}/emailwiz-stage.XXXXXX")
: >"$STAGE/.meta"
: >"$STAGE/.retire"
: >"$STAGE/.notes"
: >"$STAGE/.actions"
trap 'rm -rf "$STAGE"' EXIT INT TERM
}
# stage_file PATH MODE OWNER GROUP UNIT (content on stdin)
stage_file() {
_p=$1
mkdir -p "$STAGE$(dirname "$_p")"
cat >"$STAGE$_p"
printf '%s %s %s %s %s\n' "$_p" "$2" "$3" "$4" "${5:--}" >>"$STAGE/.meta"
}
# stage_retire PATH UNIT REASON - move an obsolete file into the backup.
stage_retire() {
[ -e "$1" ] || return 0
printf '%s %s %s\n' "$1" "${2:--}" "$3" >>"$STAGE/.retire"
}
note() { printf '%s\n' "$*" >>"$STAGE/.notes"; }
# stage_action UNIT REASON - a service action needed even if no file changes.
stage_action() { printf '%s %s\n' "$1" "$2" >>"$STAGE/.actions"; }
# file_state PATH MODE OWNER GROUP -> prints "new", "changed", "meta" or "same"
file_state() {
if [ ! -e "$1" ]; then echo new; return; fi
if ! cmp -s "$STAGE$1" "$1"; then echo changed; return; fi
_cur=$(stat -c '%a %U %G' "$1")
[ "$_cur" = "$2 $3 $4" ] && echo same || echo meta
}
# install_atomic SRC DEST MODE OWNER GROUP - write via temp file + rename.
install_atomic() {
_dir=$(dirname "$2")
[ -d "$_dir" ] || install -d -m 0755 "$_dir"
_tmp=$(mktemp "$_dir/.emailwiz.XXXXXX")
cat "$1" >"$_tmp"
chown "$4:$5" "$_tmp"
chmod "$3" "$_tmp"
mv -f "$_tmp" "$2"
}
# --- backups -------------------------------------------------------------------
# Paths captured by every backup. Missing paths are skipped.
BACKUP_PATHS="/etc/postfix /etc/dovecot /etc/opendkim.conf /etc/default/opendkim
/etc/default/spamd /etc/fail2ban/jail.d /etc/systemd/system/opendkim.service.d
/etc/systemd/system/spamd.service.d /etc/systemd/system/emailwiz-certcheck.service
/etc/systemd/system/emailwiz-certcheck.timer /etc/systemd/system/emailwiz-backup.service
/etc/systemd/system/emailwiz-backup.timer /etc/aliases /etc/pam.d/dovecot
/etc/mailname /etc/emailwiz /var/lib/dovecot/sieve
/etc/letsencrypt/renewal-hooks/deploy/emailwiz-reload"
# backup_create LABEL [extra paths...] -> prints backup dir
backup_create() {
_label=$1; shift
_id="$(date +%Y%m%d-%H%M%S)-$_label"
_dir="$EMAILWIZ_BACKUPS/$_id"
install -d -m 0700 -o root -g root "$EMAILWIZ_BACKUPS"
install -d -m 0700 -o root -g root "$_dir"
_list=
for _p in $BACKUP_PATHS "$@"; do
[ -e "$_p" ] || continue
# Skip paths already covered by an earlier entry (e.g. DKIM_DIR in /etc/postfix).
_dup=no
for _q in $_list; do
case "${_p#/}/" in "$_q"/*) _dup=yes ;; esac
done
[ "$_dup" = yes ] || _list="$_list ${_p#/}"
done
# shellcheck disable=SC2086
tar -C / --numeric-owner -cpzf "$_dir/config.tar.gz" $_list
# shellcheck disable=SC2086
(cd / && find $_list -xdev \( -type f -o -type l \) -print) | sort >"$_dir/MANIFEST"
(cd "$_dir" && sha256sum config.tar.gz >SHA256SUMS)
: >"$_dir/created"
chmod 0600 "$_dir"/*
# A backup that cannot be read back is not a backup.
tar -tzf "$_dir/config.tar.gz" >/dev/null || die "backup verification failed: $_dir"
(cd "$_dir" && sha256sum -c --quiet SHA256SUMS) || die "backup checksum failed: $_dir"
printf '%s\n' "$_dir"
}
backup_prune() {
_keep=${1:-20}
[ -d "$EMAILWIZ_BACKUPS" ] || return 0
# Only prune automatic backups; manual/apply backups are kept.
find "$EMAILWIZ_BACKUPS" -mindepth 1 -maxdepth 1 -type d -name '*-scheduled' |
sort -r | tail -n +"$((_keep + 1))" | while read -r _d; do
rm -rf -- "$_d"
done
}
# shell-quote a value for single-quoted config output
squote() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
# --- prompts -------------------------------------------------------------------
# NONINTERACTIVE=yes (setup --non-interactive): never prompt; values come from
# the environment/config, yes/no answers from the named variable (default no).
NONINTERACTIVE=${NONINTERACTIVE:-no}
# ask VAR QUESTION [DEFAULT] - current value of VAR wins over DEFAULT.
ask() {
eval "_cur=\${$1:-}"
_def=${_cur:-${3:-}}
if [ "$NONINTERACTIVE" = yes ]; then
eval "$1=\$_def"
return 0
fi
[ -t 0 ] || die "cannot prompt for '$2' without a terminal (use --non-interactive)" "$EX_USAGE"
printf '%s [%s]: ' "$2" "$_def" >&2
read -r _ans || _ans=
[ -n "$_ans" ] || _ans=$_def
eval "$1=\$_ans"
}
# confirm QUESTION [VAR] - 0 for yes. Non-interactive: value of VAR (yes/no).
confirm() {
if [ "$NONINTERACTIVE" = yes ]; then
[ -n "${2:-}" ] || return 1
_v=no
eval "_v=\${$2:-no}"
[ "$_v" = yes ]
return
fi
[ -t 0 ] || return 1
printf '%s [y/N] ' "$1" >&2
read -r _ans || _ans=
case $_ans in y | Y | yes | YES) return 0 ;; *) return 1 ;; esac
}
+131
View File
@@ -0,0 +1,131 @@
# emailwiz - configuration loading, defaults and validation
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
EMAILWIZ_CONF=${EMAILWIZ_CONF:-/etc/emailwiz/emailwiz.conf}
config_defaults() {
DOMAIN=${DOMAIN:-}
MAIL_HOSTNAME=${MAIL_HOSTNAME:-}
ROOT_ALIAS=${ROOT_ALIAS:-}
TLS_CERT=${TLS_CERT:-}
TLS_KEY=${TLS_KEY:-}
TLS_MODE=${TLS_MODE:-external} # external | certbot
CERT_WARN_DAYS=${CERT_WARN_DAYS:-21}
DKIM_SELECTOR=${DKIM_SELECTOR:-mail}
DKIM_DIR=${DKIM_DIR:-/etc/postfix/dkim}
DKIM_BITS=${DKIM_BITS:-2048}
DKIM_PORT=${DKIM_PORT:-12301}
DKIM_INTERNAL_HOSTS=${DKIM_INTERNAL_HOSTS:-127.0.0.1 ::1}
IMAP_PROTOCOLS=${IMAP_PROTOCOLS:-imap pop3}
SPAM_FILTER=${SPAM_FILTER:-spamc} # spamc | none
SPAMD_MAX_CHILDREN=${SPAMD_MAX_CHILDREN:-2}
STRIP_OUTBOUND_RECEIVED=${STRIP_OUTBOUND_RECEIVED:-yes}
SMTP_ADDRESS_PREFERENCE=${SMTP_ADDRESS_PREFERENCE:-auto} # auto | any | ipv4 | ipv6
FAIL2BAN=${FAIL2BAN:-yes}
JUNK_AUTOEXPUNGE=${JUNK_AUTOEXPUNGE:-30d}
BACKUP_KEEP=${BACKUP_KEEP:-12}
EMAILWIZ_TIMERS=${EMAILWIZ_TIMERS:-yes}
}
config_load() {
if [ ! -f "$EMAILWIZ_CONF" ] && [ -f /etc/mailwiz/mailwiz.conf ]; then
warn "found /etc/mailwiz/mailwiz.conf from mailwiz 1.x; to upgrade, copy it:"
warn " sudo install -D -m 0644 /etc/mailwiz/mailwiz.conf $EMAILWIZ_CONF (see README: Upgrading from mailwiz 1.x)"
fi
if [ -f "$EMAILWIZ_CONF" ]; then
# Refuse to source a config that someone other than root could edit.
_st=$(stat -c '%u %a' "$EMAILWIZ_CONF")
_uid=${_st% *}; _mode=${_st#* }
[ "$_uid" -eq 0 ] || die "$EMAILWIZ_CONF must be owned by root" "$EX_USAGE"
case $_mode in
*[2367]? | *[2367]) die "$EMAILWIZ_CONF must not be group/world writable" "$EX_USAGE" ;;
esac
# shellcheck disable=SC1090
. "$EMAILWIZ_CONF"
fi
config_defaults
}
is_hostname() {
printf '%s' "$1" | grep -Eq '^([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$'
}
config_validate() {
_bad=0
[ -n "$DOMAIN" ] || { err "DOMAIN is not set (see $EMAILWIZ_CONF)"; _bad=1; }
[ -n "$DOMAIN" ] && ! is_hostname "$DOMAIN" && { err "DOMAIN '$DOMAIN' is not a valid domain"; _bad=1; }
[ -n "$MAIL_HOSTNAME" ] || MAIL_HOSTNAME="mail.$DOMAIN"
is_hostname "$MAIL_HOSTNAME" || { err "MAIL_HOSTNAME '$MAIL_HOSTNAME' is invalid"; _bad=1; }
printf '%s' "$DKIM_SELECTOR" | grep -Eq '^[a-z0-9][a-z0-9-]*$' ||
{ err "DKIM_SELECTOR must match [a-z0-9-]+"; _bad=1; }
case $TLS_MODE in external | certbot) ;; *) err "TLS_MODE must be external or certbot"; _bad=1 ;; esac
case $SPAM_FILTER in spamc | none) ;; *) err "SPAM_FILTER must be spamc or none"; _bad=1 ;; esac
case $SMTP_ADDRESS_PREFERENCE in auto | any | ipv4 | ipv6) ;; *) err "bad SMTP_ADDRESS_PREFERENCE"; _bad=1 ;; esac
case $STRIP_OUTBOUND_RECEIVED in yes | no) ;; *) err "STRIP_OUTBOUND_RECEIVED must be yes/no"; _bad=1 ;; esac
case $DKIM_BITS in 1024 | 2048 | 3072 | 4096) ;; *) err "DKIM_BITS must be 1024..4096"; _bad=1 ;; esac
for _p in $IMAP_PROTOCOLS; do
case $_p in imap | pop3) ;; *) err "IMAP_PROTOCOLS: unsupported '$_p'"; _bad=1 ;; esac
done
if [ "$TLS_MODE" = certbot ]; then
: "${TLS_CERT:=/etc/letsencrypt/live/$MAIL_HOSTNAME/fullchain.pem}"
: "${TLS_KEY:=/etc/letsencrypt/live/$MAIL_HOSTNAME/privkey.pem}"
fi
[ -n "$TLS_CERT" ] && [ -n "$TLS_KEY" ] || { err "TLS_CERT and TLS_KEY must be set"; _bad=1; }
if [ -n "$ROOT_ALIAS" ] && ! getent passwd "$ROOT_ALIAS" >/dev/null; then
err "ROOT_ALIAS user '$ROOT_ALIAS' does not exist"; _bad=1
fi
[ "$_bad" -eq 0 ] || exit "$EX_USAGE"
}
# Fill unset core values from the live system (used by `emailwiz init`).
config_detect() {
: "${DOMAIN:=${1:-$(postconf -h mydomain 2>/dev/null || cat /etc/mailname 2>/dev/null || :)}}"
: "${MAIL_HOSTNAME:=mail.$DOMAIN}"
: "${ROOT_ALIAS:=${SUDO_USER:-}}"
: "${TLS_CERT:=$(postconf -h smtpd_tls_cert_file 2>/dev/null || :)}"
: "${TLS_KEY:=$(postconf -h smtpd_tls_key_file 2>/dev/null || :)}"
}
# Print a config file from the current variables.
config_render() {
config_defaults
cat <<EOF
# emailwiz configuration - sourced by /bin/sh. Owned by root, mode 0644 or stricter.
# Generated by emailwiz $EMAILWIZ_VERSION. See README.md for every option.
DOMAIN=$(squote "$DOMAIN")
MAIL_HOSTNAME=$(squote "$MAIL_HOSTNAME")
# Local user that receives root/postmaster mail (DMARC reports, cert warnings).
ROOT_ALIAS=$(squote "$ROOT_ALIAS")
# external: certificate managed outside emailwiz (only checked + monitored).
# certbot: /etc/letsencrypt/live/\$MAIL_HOSTNAME, obtained by emailwiz, reload hook installed.
TLS_MODE=$(squote "$TLS_MODE")
TLS_CERT=$(squote "$TLS_CERT")
TLS_KEY=$(squote "$TLS_KEY")
CERT_WARN_DAYS=$(squote "$CERT_WARN_DAYS")
DKIM_SELECTOR=$(squote "$DKIM_SELECTOR")
DKIM_DIR=$(squote "$DKIM_DIR")
DKIM_BITS=$(squote "$DKIM_BITS")
IMAP_PROTOCOLS=$(squote "$IMAP_PROTOCOLS")
SPAM_FILTER=$(squote "$SPAM_FILTER")
SPAMD_MAX_CHILDREN=$(squote "$SPAMD_MAX_CHILDREN")
STRIP_OUTBOUND_RECEIVED=$(squote "$STRIP_OUTBOUND_RECEIVED")
# auto: prefer IPv4 for outbound SMTP unless a global IPv6 address exists.
SMTP_ADDRESS_PREFERENCE=$(squote "$SMTP_ADDRESS_PREFERENCE")
FAIL2BAN=$(squote "$FAIL2BAN")
EMAILWIZ_TIMERS=$(squote "$EMAILWIZ_TIMERS")
EOF
}
# config_write - atomically write $EMAILWIZ_CONF from the current variables.
config_write() {
install -d -m 0755 "$(dirname "$EMAILWIZ_CONF")"
_t=$(mktemp)
config_render >"$_t"
install_atomic "$_t" "$EMAILWIZ_CONF" 644 root root
rm -f "$_t"
}
+62
View File
@@ -0,0 +1,62 @@
# emailwiz - platform and package detection
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
MAIL_PACKAGES="postfix postfix-pcre dovecot-core dovecot-imapd dovecot-pop3d dovecot-sieve
opendkim opendkim-tools spamd spamc fail2ban bind9-host openssl ca-certificates dns-root-data"
pkg_version() {
dpkg-query -W -f='${db:Status-Abbrev} ${Version}\n' "$1" 2>/dev/null |
awk '$1 ~ /^ii/ {print $2}'
}
pkg_installed() { [ -n "$(pkg_version "$1")" ]; }
# Fails with EX_UNSUPPORTED on anything but Debian 13. The Dovecot template
# uses 2.4 syntax, which Debian 12 (Dovecot 2.3) cannot parse.
detect_os() {
[ -r /etc/os-release ] || die "/etc/os-release missing" "$EX_UNSUPPORTED"
OS_ID=$(. /etc/os-release && echo "${ID:-}")
OS_VERSION=$(. /etc/os-release && echo "${VERSION_ID:-}")
OS_CODENAME=$(. /etc/os-release && echo "${VERSION_CODENAME:-}")
if [ "$OS_ID" != debian ] || [ "$OS_VERSION" != 13 ]; then
[ "${EMAILWIZ_ALLOW_UNSUPPORTED:-no}" = yes ] ||
die "unsupported OS: $OS_ID $OS_VERSION ($OS_CODENAME); only Debian 13 is supported" "$EX_UNSUPPORTED"
warn "running on unsupported OS $OS_ID $OS_VERSION (EMAILWIZ_ALLOW_UNSUPPORTED=yes)"
fi
}
detect_versions() {
V_DOVECOT=$(pkg_version dovecot-core)
case $V_DOVECOT in
'' ) ;;
1:2.4.* | 2.4.*) ;;
*) die "Dovecot $V_DOVECOT found; the template requires Dovecot 2.4" "$EX_UNSUPPORTED" ;;
esac
DOVECOT_CONFIG_VERSION=$(dovecot --version 2>/dev/null | awk '{print $1}' | sed 's/-.*//')
}
missing_packages() {
_m=
for _p in $MAIL_PACKAGES; do
[ "$SPAM_FILTER" = none ] && case $_p in spamd | spamc) continue ;; esac
[ "$FAIL2BAN" = no ] && [ "$_p" = fail2ban ] && continue
pkg_installed "$_p" || _m="$_m $_p"
done
[ "$TLS_MODE" = certbot ] && ! pkg_installed certbot && _m="$_m certbot"
printf '%s\n' "${_m# }"
}
# 0 if the host has a global-scope IPv6 address.
has_global_ipv6() {
[ -n "$(ip -6 -o addr show scope global 2>/dev/null)" ]
}
primary_ipv4() {
ip -4 -o route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p'
}
primary_ipv6() {
has_global_ipv6 || return 0
ip -6 -o route get 2001:4860:4860::8888 2>/dev/null | sed -n 's/.* src \([0-9a-f:]*\).*/\1/p'
}
+39
View File
@@ -0,0 +1,39 @@
# emailwiz - Dovecot 2.4
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
SIEVE_DIR=/var/lib/dovecot/sieve
# render_template FILE - substitute @VARS@ (values must not contain '|').
render_template() {
sed -e "s|@DOVECOT_CONFIG_VERSION@|$DOVECOT_CONFIG_VERSION|g" \
-e "s|@IMAP_PROTOCOLS@|$IMAP_PROTOCOLS|g" \
-e "s|@TLS_CERT@|$TLS_CERT|g" \
-e "s|@TLS_KEY@|$TLS_KEY|g" \
-e "s|@JUNK_AUTOEXPUNGE@|$JUNK_AUTOEXPUNGE|g" \
-e "s|@DOMAIN@|$DOMAIN|g" \
-e "s|@MAIL_HOSTNAME@|$MAIL_HOSTNAME|g" \
-e "s|@DKIM_DIR@|$DKIM_DIR|g" \
-e "s|@DKIM_PORT@|$DKIM_PORT|g" \
-e "s|@SPAMD_MAX_CHILDREN@|$SPAMD_MAX_CHILDREN|g" \
-e "s|@CERT_WARN_DAYS@|$CERT_WARN_DAYS|g" \
"$EMAILWIZ_ROOT/templates/$1"
}
dovecot_render() {
[ -n "$DOVECOT_CONFIG_VERSION" ] || die "cannot determine Dovecot version (is dovecot-core installed?)"
render_template dovecot.conf.in | stage_file /etc/dovecot/dovecot.conf 644 root root dovecot
# Validate the rendered file with the installed doveconf before anything
# touches the live config. doveconf resolves cert paths, so this also
# catches a missing certificate.
if ! _out=$(doveconf -c "$STAGE/etc/dovecot/dovecot.conf" -n 2>&1 >/dev/null); then
die "rendered dovecot.conf is invalid: $_out" "$EX_VALIDATION"
fi
render_template default.sieve | stage_file "$SIEVE_DIR/default.sieve" 644 root root sieve
}
# Compile the default sieve script after install (the .svbin is derived state).
dovecot_post_sieve() {
sievec "$SIEVE_DIR/default.sieve" || die "sievec failed for $SIEVE_DIR/default.sieve"
}
+255
View File
@@ -0,0 +1,255 @@
# emailwiz - plan/apply engine
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
#
# plan and apply share one code path: every component renders its desired
# files into $STAGE. plan only compares; apply backs up, installs atomically,
# validates the live result and reloads only the units whose inputs changed.
# If live validation fails, the files from this run are restored.
COMPONENTS="postfix dovecot opendkim spamd fail2ban tls timers legacy"
render_all() {
_only=$1
for _c in $COMPONENTS; do
[ -z "$_only" ] || [ "$_only" = "$_c" ] || continue
"${_c}_render"
done
}
# Prints "STATE PATH" lines for staged files and "retire PATH" lines.
compute_changes() {
while read -r _p _m _o _g _u; do
_s=$(file_state "$_p" "$_m" "$_o" "$_g")
[ "$_s" = same ] || printf '%s %s\n' "$_s" "$_p"
done <"$STAGE/.meta"
while read -r _p _u _why; do
printf 'retire %s\n' "$_p"
done <"$STAGE/.retire"
while read -r _u _why; do
printf 'action %s\n' "$_u"
done <"$STAGE/.actions"
}
cmd_plan() {
_only=; _detail=no; _diff=yes
while [ $# -gt 0 ]; do
case $1 in
--component) _only=$2; shift ;;
--detailed-exitcode) _detail=yes ;;
--no-diff) _diff=no ;;
*) die "plan: unknown option $1" "$EX_USAGE" ;;
esac
shift
done
need_root plan
MODE=plan
preflight
stage_init
render_all "$_only"
firewall_note
_changes=$(compute_changes)
if [ -z "$_changes" ]; then
ok "no changes: live configuration matches desired state"
else
log "pending changes (nothing has been modified):"
printf '%s\n' "$_changes" | while read -r _s _p; do
case $_s in
action)
_why=$(awk -v u="$_p" '$1 == u { $1 = ""; sub(/^ +/, ""); print }' "$STAGE/.actions")
printf ' %-8s %s (%s)\n' "$_s" "$_p" "$_why"
;;
retire)
_why=$(awk -v p="$_p" '$1 == p { $1 = $2 = ""; sub(/^ +/, ""); print }' "$STAGE/.retire")
printf ' %-8s %s (%s)\n' "$_s" "$_p" "$_why"
;;
*) printf ' %-8s %s\n' "$_s" "$_p" ;;
esac
if [ "$_diff" = yes ] && [ "$_s" = changed ]; then
diff -u --label "live:$_p" --label "desired:$_p" "$_p" "$STAGE$_p" |
grep -v '^\(-\|+\)\s*#' | sed 's/^/ /' || :
elif [ "$_diff" = yes ] && [ "$_s" = meta ]; then
_want=$(awk -v p="$_p" '$1 == p {print $2, $3, $4}' "$STAGE/.meta")
printf ' mode/owner %s -> %s\n' "$(stat -c '%a %U %G' "$_p")" "$_want"
fi
done
fi
[ -s "$STAGE/.notes" ] && { log "notes:"; sed 's/^/ - /' "$STAGE/.notes" >&2; }
if [ -n "$_changes" ] && [ "$_detail" = yes ]; then exit "$EX_PENDING"; fi
return 0
}
# Map changed files to the service actions they require.
_actions_for() {
_acts=
for _p in $1; do
_u=$(awk -v p="$_p" '$1 == p {print $5}' "$STAGE/.meta")
[ -n "$_u" ] || _u=$(awk -v p="$_p" '$1 == p {print $2}' "$STAGE/.retire")
[ -n "$_u" ] || _u=$(awk -v p="$_p" '$1 == p {print $1}' "$STAGE/.actions")
case " $_acts " in *" $_u "*) ;; *) _acts="$_acts $_u" ;; esac
done
printf '%s\n' "$_acts"
}
# _reload UNIT - reload; if the reload itself fails (e.g. the unit's
# PrivateTmp was deleted, 226/NAMESPACE), restart. Config is already validated.
_reload() {
systemctl reload "$1" && return 0
warn "reload of $1 failed; restarting it instead"
systemctl restart "$1"
}
# Every step is checked explicitly: this runs inside `if !`, where set -e
# does not apply.
_run_actions() {
_acts=" $1 "
case $_acts in *" spamd-restart "* | *" opendkim "* | *" timers "*)
systemctl daemon-reload || return 1 ;;
esac
case $_acts in *" newaliases "*) newaliases || return 1 ;; esac
case $_acts in *" sieve "*) dovecot_post_sieve || return 1 ;; esac
case $_acts in *" opendkim "*)
systemctl restart opendkim || return 1
_wait_port "127.0.0.1" "$DKIM_PORT" || return 1 ;;
esac
case $_acts in
*" postfix-restart "*) systemctl restart postfix || return 1 ;;
*" postfix "*) _reload postfix || return 1 ;;
esac
case $_acts in *" dovecot "*) _reload dovecot || return 1 ;; esac
case $_acts in *" spamd"*) systemctl restart spamd || return 1 ;; esac
case $_acts in *" fail2ban "*) fail2ban-client reload >/dev/null || return 1 ;; esac
case $_acts in *" timers "*)
systemctl enable --now emailwiz-certcheck.timer emailwiz-backup.timer >/dev/null 2>&1 || return 1 ;;
esac
return 0
}
_wait_port() {
_i=0
while [ $_i -lt 20 ]; do
ss -Hltn "sport = :$2" 2>/dev/null | grep -q "$1:$2" && return 0
_i=$((_i + 1)); sleep 0.5
done
err "nothing listening on $1:$2"
return 1
}
# Live checks run after files are in place, before services are touched.
_validate_installed() {
_rc=0
if ! _o=$(postfix_validate_live); then err "postfix check: $_o"; _rc=1; fi
if ! _o=$(doveconf -n 2>&1 >/dev/null); then err "doveconf: $_o"; _rc=1; fi
if ! _o=$(opendkim -n 2>&1); then err "opendkim -n: $_o"; _rc=1; fi
if [ "$FAIL2BAN" = yes ] && ! _o=$(fail2ban-client -t 2>&1); then err "fail2ban -t: $_o"; _rc=1; fi
return $_rc
}
_restore_from() {
_bk=$1
warn "restoring files from $_bk"
# Remove files this run created, then restore the pre-run snapshot.
while read -r _f; do [ -n "$_f" ] && rm -f -- "$_f"; done <"$_bk/created"
tar -C / --numeric-owner -xpzf "$_bk/config.tar.gz"
systemctl daemon-reload
}
cmd_apply() {
_only=; _yes=no
while [ $# -gt 0 ]; do
case $1 in
--component) _only=$2; shift ;;
--yes) _yes=yes ;;
*) die "apply: unknown option $1" "$EX_USAGE" ;;
esac
shift
done
need_root apply
MODE=apply
preflight
stage_init
render_all "$_only"
_changes=$(compute_changes)
_key_missing=no
if [ ! -f "$(dkim_key_path)" ] && { [ -z "$_only" ] || [ "$_only" = opendkim ]; }; then
_key_missing=yes
fi
if [ -z "$_changes" ] && [ "$_key_missing" = no ]; then
ok "nothing to do: live configuration matches desired state"
return 0
fi
printf '%s\n' "$_changes" | sed '/^$/d; s/^/ /' >&2
if [ "$_yes" != yes ]; then
[ -t 0 ] || die "refusing to apply non-interactively without --yes" "$EX_USAGE"
printf 'Apply these changes? [y/N] ' >&2
read -r _ans
case $_ans in y | Y | yes) ;; *) die "aborted by user" "$EX_ERR" ;; esac
fi
_bk=$(backup_create apply)
CREATED_LIST=$_bk/created
log "backup: $_bk"
[ "$_key_missing" = yes ] && opendkim_ensure_key
printf '%s\n' "$_changes" | while read -r _s _p; do
[ -n "$_p" ] || continue
case $_s in
action) ;;
retire)
# The backup already holds a copy; keep a second one next to it.
install -d -m 0700 "$_bk/retired"
case $_p in
/etc/systemd/system/*.timer | /etc/systemd/system/*.service)
systemctl disable --now "$(basename "$_p")" >/dev/null 2>&1 || : ;;
esac
cp -p -- "$_p" "$_bk/retired/$(printf '%s' "$_p" | tr / _)"
rm -f -- "$_p"
info "retired $_p"
;;
*)
_meta=$(awk -v p="$_p" '$1 == p {print $2, $3, $4}' "$STAGE/.meta")
# shellcheck disable=SC2086
set -- $_meta
[ -e "$_p" ] || echo "$_p" >>"$CREATED_LIST"
install_atomic "$STAGE$_p" "$_p" "$1" "$2" "$3"
info "installed $_p ($_s)"
;;
esac
done
_paths=$(printf '%s\n' "$_changes" | awk '{print $2}')
if [ -f "$(dkim_key_path)" ]; then
chown root:opendkim "$(dkim_key_path)"; chmod 0640 "$(dkim_key_path)"
fi
if ! _validate_installed; then
_restore_from "$_bk"
die "live validation failed; previous configuration restored (backup: $_bk)" "$EX_VALIDATION"
fi
_acts=$(_actions_for "$_paths")
[ "$_key_missing" = yes ] && case " $_acts " in *" opendkim "*) ;; *) _acts="$_acts opendkim" ;; esac
log "service actions:${_acts}"
if ! _run_actions "$_acts"; then
_restore_from "$_bk"
_run_actions "$_acts" || :
die "service reload failed; previous configuration restored (backup: $_bk)" "$EX_VALIDATION"
fi
sleep 1
_down=
for _svc in postfix dovecot opendkim $( [ "$SPAM_FILTER" = spamc ] && echo spamd ) \
$( [ "$FAIL2BAN" = yes ] && echo fail2ban ); do
systemctl is-active -q "$_svc" || _down="$_down $_svc"
done
if [ -n "$_down" ]; then
err "inactive after apply:$_down"
_restore_from "$_bk"
_run_actions "$_acts" || :
die "services failed; previous configuration restored (backup: $_bk)" "$EX_VALIDATION"
fi
ok "applied; backup $_bk"
[ "$_key_missing" = yes ] && warn "new DKIM key generated: publish it (emailwiz dns) before relying on DKIM"
info "next: sudo emailwiz validate"
}
+58
View File
@@ -0,0 +1,58 @@
# emailwiz - optional UFW rules for the mail ports (TCP only, never SSH)
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
firewall_ports() {
_ports="25 465 587 993"
case " $IMAP_PROTOCOLS " in *" pop3 "*) _ports="$_ports 995" ;; esac
[ "$TLS_MODE" = certbot ] && _ports="$_ports 80"
printf '%s\n' "$_ports"
}
ufw_active() {
have ufw && ufw status 2>/dev/null | head -1 | grep -q '^Status: active'
}
# Ports without an IPv4 ALLOW rule (a "25" any-protocol rule counts as covering 25/tcp).
firewall_missing() {
_st=$(ufw status 2>/dev/null | grep -v '(v6)')
_miss=
for _p in $(firewall_ports); do
printf '%s\n' "$_st" | grep -Eq "^$_p(/tcp)?[[:space:]]+ALLOW" || _miss="$_miss $_p"
done
printf '%s\n' "${_miss# }"
}
# Add a plan note when UFW would block mail ports (read-only).
firewall_note() {
ufw_active || return 0
_m=$(firewall_missing)
[ -z "$_m" ] || note "UFW is active and does not allow tcp port(s): $_m (run: sudo emailwiz firewall)"
}
cmd_firewall() {
need_root firewall
MODE=apply
_yes=no
[ "${1:-}" = --yes ] && _yes=yes
detect_os
config_load
config_validate
if ! ufw_active; then
info "UFW is not active; nothing to do. Mail needs these TCP ports open in any"
info "firewall in front of this host: $(firewall_ports)"
return 0
fi
_m=$(firewall_missing)
[ -n "$_m" ] || { ok "UFW already allows tcp: $(firewall_ports)"; return 0; }
log "UFW will allow tcp: $_m (SSH rules and default policies are not touched)"
if [ "$_yes" != yes ] && ! confirm "Add these UFW rules?" SETUP_UFW; then
warn "skipped; mail ports stay closed in UFW"
return 0
fi
for _p in $_m; do
ufw allow "$_p/tcp" comment emailwiz >/dev/null
info "allowed $_p/tcp"
done
ok "UFW rules added"
}
+53
View File
@@ -0,0 +1,53 @@
# emailwiz - OpenDKIM signing/verification milter
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
dkim_key_path() { printf '%s/%s/%s.private\n' "$DKIM_DIR" "$DOMAIN" "$DKIM_SELECTOR"; }
opendkim_render() {
_key=$(dkim_key_path)
if [ ! -f "$_key" ]; then
note "DKIM key $_key does not exist: apply will generate a new $DKIM_BITS-bit key (publish it with 'emailwiz dns')."
fi
render_template opendkim.conf.in | stage_file /etc/opendkim.conf 644 root root opendkim
stage_file "$DKIM_DIR/keytable" 644 root root opendkim <<EOF
$DKIM_SELECTOR._domainkey.$DOMAIN $DOMAIN:$DKIM_SELECTOR:$_key
EOF
stage_file "$DKIM_DIR/signingtable" 644 root root opendkim <<EOF
*@$DOMAIN $DKIM_SELECTOR._domainkey.$DOMAIN
EOF
# shellcheck disable=SC2086 # one host per line
printf '%s\n' $DKIM_INTERNAL_HOSTS | stage_file "$DKIM_DIR/trustedhosts" 644 root root opendkim
# emailwiz pinned the socket with an ExecStart override; the Debian unit
# reads Socket/PidFile from opendkim.conf, so the override is retired.
stage_retire /etc/systemd/system/opendkim.service.d/override.conf opendkim \
"emailwiz ExecStart override; socket now set in /etc/opendkim.conf"
# Validate against the staged tables (they may not exist yet on a clean host).
sed "s|$DKIM_DIR/|$STAGE$DKIM_DIR/|g" "$STAGE/etc/opendkim.conf" >"$STAGE/.opendkim-validate.conf"
_out=$(opendkim -n -x "$STAGE/.opendkim-validate.conf" 2>&1) ||
die "rendered opendkim.conf is invalid: $_out" "$EX_VALIDATION"
}
# Generate the key only if it is missing; never overwrite an existing key.
opendkim_ensure_key() {
_key=$(dkim_key_path)
_d=$(dirname "$_key")
install -d -m 0750 -o root -g opendkim "$_d"
if [ ! -f "$_key" ]; then
log "generating $DKIM_BITS-bit DKIM key, selector '$DKIM_SELECTOR'"
opendkim-genkey -b "$DKIM_BITS" -h sha256 -D "$_d" -d "$DOMAIN" -s "$DKIM_SELECTOR"
echo "$_key" >>"$CREATED_LIST"
echo "$_d/$DKIM_SELECTOR.txt" >>"$CREATED_LIST"
fi
chown root:opendkim "$_key" "$_d/$DKIM_SELECTOR.txt" 2>/dev/null || chown root:opendkim "$_key"
chmod 0640 "$_key"
}
# Public key (base64 DER) derived from the private key - the authoritative
# value for DNS, independent of the .txt file opendkim-genkey wrote.
dkim_public_b64() {
openssl rsa -in "$(dkim_key_path)" -pubout -outform DER 2>/dev/null | base64 -w0
}
+254
View File
@@ -0,0 +1,254 @@
# emailwiz - dns, cert-check, backup/rollback, audit, init, packages, migration, users
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
cmd_dns() {
MODE=dns
preflight
_ip4=$(primary_ipv4); _ip6=$(primary_ipv6)
_spf="v=spf1 mx -all"
if [ ! -r "$(dkim_key_path)" ]; then
[ "$(id -u)" -eq 0 ] || die "run as root to read the DKIM key"
_dkim="(no key yet: run 'emailwiz apply' first)"
else
_dkim="v=DKIM1; k=rsa; p=$(dkim_public_b64)"
fi
cat <<EOF
# Desired DNS records for $DOMAIN (zone-relative names in brackets).
# Values are derived from this host; nothing here was invented.
$DOMAIN. MX 10 $MAIL_HOSTNAME. [@]
$MAIL_HOSTNAME. A $_ip4 [${MAIL_HOSTNAME%".$DOMAIN"}]
EOF
if [ -n "$_ip6" ]; then
printf '%s.\t\tAAAA\t%s\t[%s] # only if IPv6 is routed and PTR is set\n' \
"$MAIL_HOSTNAME" "$_ip6" "${MAIL_HOSTNAME%".$DOMAIN"}"
else
printf '# no AAAA: this host has no global IPv6 address - do not publish one.\n'
fi
cat <<EOF
$DOMAIN. TXT "$_spf" [@]
$DKIM_SELECTOR._domainkey.$DOMAIN. TXT "$_dkim" [$DKIM_SELECTOR._domainkey]
_dmarc.$DOMAIN. TXT "v=DMARC1; p=reject; rua=mailto:postmaster@$DOMAIN; fo=1" [_dmarc]
# Optional: TLS reporting
_smtp._tls.$DOMAIN. TXT "v=TLSRPTv1; rua=mailto:postmaster@$DOMAIN" [_smtp._tls]
# Reverse DNS (set at the hosting provider, not in the zone):
# $_ip4 PTR $MAIL_HOSTNAME.
EOF
[ -n "$_ip6" ] && printf '# %s PTR %s.\n' "$_ip6" "$MAIL_HOSTNAME"
cat <<EOF
# Long TXT values (DKIM) may need to be split into <=255-char strings by
# your DNS provider. Verify with:
# host -t MX $DOMAIN
# host -t TXT $DOMAIN
# host -t TXT $DKIM_SELECTOR._domainkey.$DOMAIN
# host -t TXT _dmarc.$DOMAIN
# host $_ip4
# sudo emailwiz validate
EOF
}
cmd_cert_check() {
_notify=no
[ "${1:-}" = --notify ] && _notify=yes
MODE=validate
preflight
_d=$(cert_days_left)
_subj=$(openssl x509 -in "$TLS_CERT" -noout -subject 2>/dev/null | sed 's/^subject=//')
if [ "$_d" -ge "$CERT_WARN_DAYS" ]; then
ok "certificate $TLS_CERT ($_subj) valid for $_d more days"
return 0
fi
_msg="TLS certificate $TLS_CERT ($_subj) used by Postfix/Dovecot expires in $_d days."
warn "$_msg"
logger -t emailwiz -p mail.warning "$_msg" 2>/dev/null || :
if [ "$_notify" = yes ]; then
printf 'Subject: [emailwiz] certificate expires in %s days on %s\n\n%s\n\nRenew it, then run: sudo emailwiz validate\n' \
"$_d" "$MAIL_HOSTNAME" "$_msg" | /usr/sbin/sendmail -oi postmaster
fi
return 1
}
cmd_backup() {
need_root backup
MODE=apply
_label=manual; _mail=
while [ $# -gt 0 ]; do
case $1 in
--scheduled) _label=scheduled ;;
--with-mail) _mail=yes ;;
*) die "backup: unknown option $1" "$EX_USAGE" ;;
esac
shift
done
config_load
_extra=
[ -d "$DKIM_DIR" ] && _extra=$DKIM_DIR
if [ -n "$_mail" ]; then
for _h in $(getent group mail | cut -d: -f4 | tr , ' '); do
_home=$(getent passwd "$_h" | cut -d: -f6)
[ -d "$_home/Mail" ] && _extra="$_extra $_home/Mail"
done
fi
# shellcheck disable=SC2086
_bk=$(backup_create "$_label" $_extra)
ok "backup created: $_bk ($(du -sh "$_bk" | cut -f1))"
[ "$_label" = scheduled ] && backup_prune "$BACKUP_KEEP"
return 0
}
cmd_backups() {
need_root backups
[ -d "$EMAILWIZ_BACKUPS" ] || { info "no backups"; return 0; }
for _d in "$EMAILWIZ_BACKUPS"/*/; do
[ -d "$_d" ] || continue
printf '%s %s files %s\n' "$(basename "$_d")" "$(wc -l <"$_d/MANIFEST")" "$(du -sh "$_d" | cut -f1)"
done
}
cmd_rollback() {
need_root rollback
MODE=apply
_id=${1:-}; _yes=${2:-}
[ -n "$_id" ] || die "usage: emailwiz rollback BACKUP_ID [--yes] (see: emailwiz backups)" "$EX_USAGE"
_bk=$EMAILWIZ_BACKUPS/$_id
[ -f "$_bk/config.tar.gz" ] || die "no such backup: $_bk"
(cd "$_bk" && sha256sum -c --quiet SHA256SUMS) || die "checksum mismatch in $_bk"
log "rollback to $_id restores configuration files only (never mailboxes)"
[ -s "$_bk/created" ] && { info "files created by that run will be removed:"; sed 's/^/ /' "$_bk/created" >&2; }
if [ "$_yes" != --yes ]; then
[ -t 0 ] || die "refusing to roll back non-interactively without --yes" "$EX_USAGE"
printf 'Roll back? [y/N] ' >&2; read -r _a
case $_a in y | Y | yes) ;; *) die "aborted" ;; esac
fi
_safety=$(backup_create pre-rollback)
log "safety backup of current state: $_safety"
_restore_from "$_bk"
newaliases
for _s in opendkim postfix dovecot spamd fail2ban; do
systemctl is-enabled -q "$_s" 2>/dev/null && systemctl restart "$_s"
done
_bad=
for _s in postfix dovecot opendkim; do systemctl is-active -q "$_s" || _bad="$_bad $_s"; done
[ -z "$_bad" ] || die "after rollback, inactive:$_bad (current state saved in $_safety)"
ok "rolled back to $_id; run: sudo emailwiz validate"
}
# Read-only audit. Prints facts; never changes anything.
cmd_audit() {
need_root audit
MODE=audit
detect_os
config_load
section "Platform"
printf ' %s %s (%s), kernel %s, %s\n' "$OS_ID" "$OS_VERSION" "$OS_CODENAME" "$(uname -r)" "$(uname -m)"
printf ' memory: %s\n' "$(free -h | awk '/^Mem:/ {print $2" total, "$7" available"}')"
printf ' disk /: %s\n' "$(df -h / | awk 'NR==2 {print $5" used of "$2}')"
printf ' IPv4 %s, global IPv6: %s\n' "$(primary_ipv4)" "$(primary_ipv6 | grep . || echo none)"
section "Packages"
for _p in $MAIL_PACKAGES certbot nginx ufw; do
printf ' %-16s %s\n' "$_p" "$(pkg_version "$_p" | grep . || echo '-')"
done
section "Services"
for _s in postfix dovecot opendkim spamd fail2ban nginx; do
printf ' %-10s %s/%s\n' "$_s" "$(systemctl is-enabled "$_s" 2>/dev/null || :)" "$(systemctl is-active "$_s" 2>/dev/null || :)"
done
printf ' failed units: %s\n' "$(systemctl --failed --no-legend --plain | awk '{print $1}' | tr '\n' ' ' | grep . || echo none)"
section "Mail"
printf ' queue: %s\n' "$(postqueue -p 2>/dev/null | tail -1)"
printf ' mail users (group mail): %s\n' "$(getent group mail | cut -d: -f4)"
section "upstream emailwiz artifacts"
grep -q '^\[sieve\]' /etc/fail2ban/jail.d/emailwiz.local 2>/dev/null &&
printf ' present: upstream fail2ban jail /etc/fail2ban/jail.d/emailwiz.local (replaced by apply)\n'
for _f in /etc/systemd/system/opendkim.service.d/override.conf \
/etc/dovecot/dovecot.backup.conf /etc/cron.weekly/postmaster-clean /etc/ssl/emailwiz; do
[ -e "$_f" ] && printf ' present: %s\n' "$_f"
done
grep -q 'pam_unix.so nullok' /etc/pam.d/dovecot 2>/dev/null &&
printf ' present: nullok line appended to /etc/pam.d/dovecot (see: emailwiz migrate-upstream --fix-pam)\n'
[ -n "$(postconf -h header_checks 2>/dev/null)" ] &&
printf ' present: header_checks=%s (strips inbound Received:)\n' "$(postconf -h header_checks)"
section "SSH"
sshd -T 2>/dev/null | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication) ' | sed 's/^/ /'
return 0
}
cmd_init() {
need_root init
_dom=${1:-}
[ -e "$EMAILWIZ_CONF" ] && die "$EMAILWIZ_CONF exists; edit it instead" "$EX_USAGE"
config_detect "$_dom"
config_write
ok "wrote $EMAILWIZ_CONF - review it, then run: sudo emailwiz plan"
}
# Clean-install path. Never purges anything.
cmd_install_packages() {
need_root install-packages
MODE=apply
detect_os
config_load
config_validate
_m=$(missing_packages)
[ -n "$_m" ] || { ok "all required packages are installed"; return 0; }
log "installing: $_m"
if ! pkg_installed postfix; then
printf 'postfix postfix/main_mailer_type select Internet Site\npostfix postfix/mailname string %s\n' \
"$DOMAIN" | debconf-set-selections
fi
# shellcheck disable=SC2086
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends $_m
ok "packages installed; next: sudo emailwiz plan"
}
# One-time migration helpers for hosts set up by upstream emailwiz.
cmd_migrate_upstream() {
need_root migrate-upstream
MODE=apply
detect_os
config_load
config_validate
[ "${1:-}" = --fix-pam ] || {
info "managed emailwiz leftovers (fail2ban jail, opendkim override, header_checks) are"
info "retired automatically by 'emailwiz apply'. This command only offers:"
info " --fix-pam remove the 'auth required pam_unix.so nullok' / 'account required"
info " pam_unix.so' lines emailwiz appended to /etc/pam.d/dovecot"
return 0
}
_f=/etc/pam.d/dovecot
grep -Eq '^auth[[:space:]]+required[[:space:]]+pam_unix\.so nullok$' "$_f" ||
{ ok "no emailwiz PAM lines in $_f"; return 0; }
_bk=$(backup_create migrate-pam)
_t=$(mktemp)
grep -Ev '^(auth[[:space:]]+required[[:space:]]+pam_unix\.so nullok|account[[:space:]]+required[[:space:]]+pam_unix\.so)$' "$_f" >"$_t"
grep -q '^@include common-auth' "$_t" || { rm -f "$_t"; die "$_f lacks @include common-auth; not touching it"; }
install_atomic "$_t" "$_f" 644 root root
rm -f "$_t"
ok "removed emailwiz lines from $_f (backup $_bk). Test an IMAP login now."
}
cmd_user() {
need_root user
MODE=apply
config_load
_sub=${1:-}; _name=${2:-}
case $_sub in
list)
getent group mail | cut -d: -f4 | tr , '\n' | sed '/^$/d'
;;
add)
printf '%s' "$_name" | grep -Eq '^[a-z][a-z0-9_-]{0,31}$' || die "invalid user name '$_name'" "$EX_USAGE"
if getent passwd "$_name" >/dev/null; then
usermod -aG mail "$_name"
ok "$_name exists; added to group mail"
else
useradd -m -G mail -s /usr/sbin/nologin "$_name"
ok "created $_name (no shell login). Set its mail password with: sudo passwd $_name"
fi
info "address: $_name@$DOMAIN IMAP: $MAIL_HOSTNAME:993 SMTP: $MAIL_HOSTNAME:465 or :587"
;;
*) die "usage: emailwiz user add NAME | emailwiz user list" "$EX_USAGE" ;;
esac
}
+146
View File
@@ -0,0 +1,146 @@
# emailwiz - Postfix (rendered by running postconf against a copy of /etc/postfix)
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
PF_HDR_CHECKS=/etc/postfix/emailwiz_outbound_header_checks
PF_LOGIN_MAPS=/etc/postfix/login_maps.pcre
# pf_service NAME TYPE "MASTER.CF LINE" "param=value" ...
# Replaces the service entry and all of its -o overrides with exactly the
# given ones, so stale overrides (e.g. emailwiz's smtpd_enforce_tls) go away.
pf_service() {
_n=$1 _t=$2 _line=$3; shift 3
postconf -c "$PFDIR" -M "$_n/$_t=$_line"
postconf -c "$PFDIR" -P 2>/dev/null | sed -n "s|^$_n/$_t/\([^=]*\)=.*|\1|p" |
while read -r _param; do
postconf -c "$PFDIR" -PX "$_n/$_t/$_param"
done
for _kv in "$@"; do
postconf -c "$PFDIR" -P "$_n/$_t/$_kv"
done
}
postfix_render() {
PFDIR=$(mktemp -d "$STAGE/.postfix.XXXXXX")
cp -p /etc/postfix/main.cf /etc/postfix/master.cf "$PFDIR/"
_pref=$SMTP_ADDRESS_PREFERENCE
if [ "$_pref" = auto ]; then
if has_global_ipv6; then _pref=any; else _pref=ipv4; fi
fi
_milter="inet:127.0.0.1:$DKIM_PORT"
postconf -c "$PFDIR" -e \
"myhostname = $MAIL_HOSTNAME" \
"mydomain = $DOMAIN" \
"mydestination = \$myhostname, \$mydomain, localhost.\$mydomain, localhost" \
"smtpd_banner = \$myhostname ESMTP" \
"smtp_address_preference = $_pref" \
"smtpd_tls_cert_file = $TLS_CERT" \
"smtpd_tls_key_file = $TLS_KEY" \
"smtpd_tls_security_level = may" \
"smtp_tls_security_level = may" \
"smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt" \
"smtpd_tls_protocols = >=TLSv1.2" \
"smtpd_tls_mandatory_protocols = >=TLSv1.2" \
"smtp_tls_protocols = >=TLSv1.2" \
"smtp_tls_mandatory_protocols = >=TLSv1.2" \
"smtpd_tls_auth_only = yes" \
"smtpd_sasl_type = dovecot" \
"smtpd_sasl_path = private/auth" \
"smtpd_sasl_auth_enable = no" \
"smtpd_sasl_security_options = noanonymous, noplaintext" \
"smtpd_sasl_tls_security_options = noanonymous" \
"smtpd_sender_login_maps = pcre:$PF_LOGIN_MAPS" \
"smtpd_helo_required = yes" \
"smtpd_helo_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, reject_unknown_helo_hostname" \
"smtpd_sender_restrictions = permit_mynetworks, reject_sender_login_mismatch, permit_sasl_authenticated, reject_unknown_reverse_client_hostname, reject_unknown_sender_domain" \
"smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination" \
"smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, reject_unknown_recipient_domain" \
"smtpd_forbid_bare_newline = normalize" \
"smtpd_forbid_bare_newline_exclusions = \$mynetworks" \
"milter_default_action = accept" \
"milter_protocol = 6" \
"smtpd_milters = $_milter" \
"non_smtpd_milters = $_milter" \
"home_mailbox = Mail/Inbox/" \
"mailbox_command = /usr/lib/dovecot/dovecot-lda -f \"\$SENDER\" -a \"\$RECIPIENT\"" \
"recipient_delimiter = +"
# emailwiz stripped Received: from *all* mail in cleanup (inbound too).
# Strip only on outbound SMTP so inbound trace headers reach SpamAssassin.
postconf -c "$PFDIR" -X header_checks
if [ "$STRIP_OUTBOUND_RECEIVED" = yes ]; then
postconf -c "$PFDIR" -e "smtp_header_checks = regexp:$PF_HDR_CHECKS"
stage_file "$PF_HDR_CHECKS" 644 root root postfix <<'EOF'
# Managed by emailwiz. Applied by the SMTP client to outbound mail only, to
# avoid leaking submitting clients' IP addresses.
/^Received:/ IGNORE
/^X-Originating-IP:/ IGNORE
EOF
else
postconf -c "$PFDIR" -X smtp_header_checks
fi
# Senders @DOMAIN must be logged in as the matching local user.
_re=$(printf '%s' "$DOMAIN" | sed 's/\./\\./g')
stage_file "$PF_LOGIN_MAPS" 644 root root postfix <<EOF
# Managed by emailwiz: localpart@$DOMAIN may only be used by SASL user localpart.
/^([^@+]+)(\+[^@]*)?@$_re\$/ \${1}
EOF
_sub="smtpd_tls_auth_only=yes smtpd_sasl_auth_enable=yes
smtpd_client_restrictions=permit_sasl_authenticated,reject
smtpd_sender_restrictions=reject_sender_login_mismatch,permit_sasl_authenticated,reject
smtpd_relay_restrictions=permit_sasl_authenticated,reject
smtpd_recipient_restrictions=permit_sasl_authenticated,reject
milter_macro_daemon_name=ORIGINATING"
if [ "$SPAM_FILTER" = spamc ]; then
pf_service smtp inet "smtp inet n - y - - smtpd" "content_filter=spamassassin"
pf_service spamassassin unix \
"spamassassin unix - n n - - pipe user=debian-spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f \${sender} \${recipient}"
else
pf_service smtp inet "smtp inet n - y - - smtpd"
postconf -c "$PFDIR" -MX spamassassin/unix 2>/dev/null || :
fi
# shellcheck disable=SC2086
pf_service submission inet "submission inet n - y - - smtpd" \
"syslog_name=postfix/submission" "smtpd_tls_security_level=encrypt" $_sub
# shellcheck disable=SC2086
pf_service smtps inet "smtps inet n - y - - smtpd" \
"syslog_name=postfix/smtps" "smtpd_tls_wrappermode=yes" $_sub
# Postfix warns about unknown/obsolete parameters; treat that as fatal.
_w=$(postconf -c "$PFDIR" -n 2>&1 >/dev/null | grep -i warning || :)
[ -z "$_w" ] || die "postconf warnings in rendered config: $_w" "$EX_VALIDATION"
stage_file /etc/postfix/main.cf 644 root root postfix <"$PFDIR/main.cf"
stage_file /etc/postfix/master.cf 644 root root postfix-restart <"$PFDIR/master.cf"
postfix_render_aliases
}
postfix_render_aliases() {
_al=/etc/aliases
_tmp=$STAGE/.aliases
if [ -f "$_al" ]; then cp "$_al" "$_tmp"; else : >"$_tmp"; fi
grep -Eq '^postmaster:' "$_tmp" || printf 'postmaster:\troot\n' >>"$_tmp"
if [ -n "$ROOT_ALIAS" ] && ! grep -Eq '^root:' "$_tmp"; then
printf 'root:\t%s\n' "$ROOT_ALIAS" >>"$_tmp"
fi
stage_file "$_al" 644 root root newaliases <"$_tmp"
if [ ! -f "$_al.db" ] || [ -n "$(find "$_al" -newer "$_al.db" 2>/dev/null)" ]; then
stage_action newaliases "$_al.db is missing or older than $_al"
fi
# Postfix delivers root's mail with default_privs (nobody), which cannot
# write a mailbox; root must be aliased to a real user.
grep -Eq '^root:' "$_tmp" ||
note "root has no alias in $_al: set ROOT_ALIAS so postmaster/DMARC mail is deliverable"
}
postfix_validate_live() {
postfix check 2>&1 | grep -v 'not owned by root: /var/spool/postfix/etc/resolv.conf' |
grep -iE 'warning|fatal|error' && return 1
return 0
}
+42
View File
@@ -0,0 +1,42 @@
# emailwiz - SpamAssassin (spamd), fail2ban, TLS hooks and maintenance timers
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
spamd_render() {
[ "$SPAM_FILTER" = spamc ] || return 0
# /etc/default/spamd is a Debian conffile: change only the OPTIONS line.
_f=/etc/default/spamd
[ -f "$_f" ] || die "$_f missing (is spamd installed?)"
_opts="--create-prefs --max-children $SPAMD_MAX_CHILDREN --helper-home-dir"
awk -v o="OPTIONS=\"$_opts\"" '
/^OPTIONS=/ { if (!done) print o; done = 1; next }
{ print }
END { if (!done) print o }' "$_f" | stage_file "$_f" 644 root root spamd
}
fail2ban_render() {
[ "$FAIL2BAN" = yes ] || return 0
# Same file name as upstream emailwiz's jail, which it replaces: that one
# also enabled [sieve], which matches no journal entries on Debian 13.
render_template fail2ban-jail.local | stage_file /etc/fail2ban/jail.d/emailwiz.local 644 root root fail2ban
}
timers_render() {
[ "$EMAILWIZ_TIMERS" = yes ] || return 0
for _u in emailwiz-certcheck.service emailwiz-certcheck.timer \
emailwiz-backup.service emailwiz-backup.timer; do
render_template "$_u" | stage_file "/etc/systemd/system/$_u" 644 root root timers
done
}
# Files from releases 1.x, published under the name "mailwiz". Retiring them
# (with a backup copy) is what upgrades such a host to the emailwiz names.
legacy_render() {
stage_retire /etc/fail2ban/jail.d/mailwiz.local fail2ban "mailwiz 1.x name; now emailwiz.local"
stage_retire /etc/postfix/mailwiz_outbound_header_checks postfix "mailwiz 1.x name; now emailwiz_outbound_header_checks"
stage_retire /etc/letsencrypt/renewal-hooks/deploy/mailwiz-reload - "mailwiz 1.x name; now emailwiz-reload"
stage_retire /etc/systemd/system/spamd.service.d/mailwiz.conf spamd-restart "mailwiz 1.0.0 drop-in; stock unit is used"
for _u in mailwiz-certcheck.timer mailwiz-certcheck.service mailwiz-backup.timer mailwiz-backup.service; do
stage_retire "/etc/systemd/system/$_u" timers "mailwiz 1.x unit; now e$_u"
done
}
+166
View File
@@ -0,0 +1,166 @@
# emailwiz - `setup`: guided first install (the emailwiz.sh experience, done safely)
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
#
# Every step reuses a regular command and is safe to rerun: an interrupted
# setup can simply be started again. Nothing is purged or overwritten silently.
setup_usage() {
cat <<'EOF'
usage: emailwiz setup [--non-interactive]
Interactive by default. --non-interactive takes everything from the existing
config file and these environment variables, and never prompts:
DOMAIN MAIL_HOSTNAME ROOT_ALIAS TLS_MODE TLS_CERT TLS_KEY CERTBOT_EMAIL
SETUP_UFW=yes|no add UFW allow rules for the mail ports
SETUP_USER=name create this mail account (set its password later with passwd)
SETUP_OVERWRITE_CONFIG=yes replace an existing, different /etc/emailwiz/emailwiz.conf
EOF
}
setup_step() { printf '\n%s[%s/8]%s %s\n' "$C_BLU" "$1" "$C_OFF" "$2" >&2; }
# Warn (never fail) when DNS does not point at this host yet.
setup_dns_hint() {
_ip=$(primary_ipv4)
_a=$(dns_q A "$MAIL_HOSTNAME" | awk '/has address/ {print $NF}')
if printf '%s\n' "$_a" | grep -qx "$_ip"; then
ok "$MAIL_HOSTNAME resolves to this host ($_ip)"
else
warn "$MAIL_HOSTNAME resolves to '${_a:-nothing}', this host is $_ip"
warn "add: $MAIL_HOSTNAME. A $_ip (certbot needs it; mail delivery needs it plus MX)"
fi
}
setup_config() {
if [ -f "$EMAILWIZ_CONF" ]; then
# Values given in the environment override the file.
_envset=
for _v in DOMAIN MAIL_HOSTNAME ROOT_ALIAS TLS_MODE TLS_CERT TLS_KEY; do
eval "_val=\${$_v:-}"
[ -n "$_val" ] && _envset="$_envset $_v=$(squote "$_val")"
done
config_load
[ -z "$_envset" ] || eval "$_envset"
info "existing configuration: $EMAILWIZ_CONF"
else
config_detect "${DOMAIN:-}"
config_defaults
fi
ask DOMAIN "Mail domain (addresses will be user@DOMAIN)" "$DOMAIN"
is_hostname "$DOMAIN" || die "'$DOMAIN' is not a valid domain" "$EX_USAGE"
[ "$MAIL_HOSTNAME" = "mail." ] && MAIL_HOSTNAME=
ask MAIL_HOSTNAME "Mail server host name (MX)" "${MAIL_HOSTNAME:-mail.$DOMAIN}"
ask ROOT_ALIAS "Local user who receives postmaster/root mail" "${ROOT_ALIAS:-${SUDO_USER:-}}"
[ -z "$ROOT_ALIAS" ] || getent passwd "$ROOT_ALIAS" >/dev/null ||
die "user '$ROOT_ALIAS' does not exist; create it first or choose another" "$EX_USAGE"
if [ "$NONINTERACTIVE" != yes ]; then
# Default: keep a usable existing certificate, otherwise obtain one.
_d=certbot
[ "$TLS_MODE" = external ] && [ -r "${TLS_CERT:-/nonexistent}" ] && _d=external
TLS_MODE=
ask TLS_MODE "TLS certificate: 'certbot' (obtain for $MAIL_HOSTNAME) or 'external' (existing files)" "$_d"
fi
case $TLS_MODE in
certbot)
TLS_CERT="$(tls_live_dir)/fullchain.pem"
TLS_KEY="$(tls_live_dir)/privkey.pem"
;;
external)
ask TLS_CERT "Certificate (full chain) file" "$TLS_CERT"
ask TLS_KEY "Private key file" "$TLS_KEY"
[ -r "$TLS_CERT" ] && [ -r "$TLS_KEY" ] || die "certificate or key not readable" "$EX_USAGE"
;;
*) die "TLS_MODE must be certbot or external" "$EX_USAGE" ;;
esac
_t=$(mktemp)
config_render >"$_t"
if [ -f "$EMAILWIZ_CONF" ] && ! diff -q -I '^# Generated' "$EMAILWIZ_CONF" "$_t" >/dev/null; then
diff -u --label current --label new "$EMAILWIZ_CONF" "$_t" | grep '^[-+][A-Z]' >&2 || :
if ! confirm "Update $EMAILWIZ_CONF with these values?" SETUP_OVERWRITE_CONFIG; then
rm -f "$_t"
die "configuration not changed; edit $EMAILWIZ_CONF or rerun setup" "$EX_USAGE"
fi
cp -p "$EMAILWIZ_CONF" "$EMAILWIZ_CONF.bak"
info "previous config saved as $EMAILWIZ_CONF.bak"
fi
rm -f "$_t"
config_write
config_load
config_validate
ok "configuration: $EMAILWIZ_CONF"
}
cmd_setup() {
case ${1:-} in
--non-interactive) NONINTERACTIVE=yes ;;
'') ;;
-h | --help) setup_usage; return 0 ;;
*) setup_usage >&2; exit "$EX_USAGE" ;;
esac
need_root setup
MODE=apply
detect_os
setup_step 1 "Configuration"
setup_config
setup_step 2 "Packages (installs what is missing, never removes anything)"
( cmd_install_packages )
setup_step 3 "DNS pre-check (read-only)"
setup_dns_hint
setup_step 4 "Firewall"
( cmd_firewall )
setup_step 5 "TLS certificate"
if [ "$TLS_MODE" = certbot ]; then
tls_obtain
else
ok "using existing certificate $TLS_CERT"
fi
setup_step 6 "Mail configuration (plan, then apply with backup and validation)"
( cmd_plan --no-diff )
if [ "$NONINTERACTIVE" != yes ] && ! confirm "Apply this configuration now?"; then
die "stopped before apply; rerun 'sudo emailwiz setup' or 'sudo emailwiz apply' later" "$EX_ERR"
fi
( cmd_apply --yes )
setup_step 7 "First mail account"
_u=${SETUP_USER:-}
if [ "$NONINTERACTIVE" != yes ] && confirm "Create a mail account now?"; then
ask _u "Account name (letters, digits, - and _)" ""
fi
if [ -n "$_u" ]; then
( cmd_user add "$_u" )
if [ "$NONINTERACTIVE" != yes ]; then
info "set the password for $_u (used for IMAP and SMTP login):"
passwd "$_u"
else
info "set its password with: sudo passwd $_u"
fi
else
info "skipped; later: sudo emailwiz user add NAME && sudo passwd NAME"
fi
setup_step 8 "Validation"
_vrc=0
( cmd_validate --no-dns --deliver-test ) || _vrc=$?
( umask 077; cmd_dns >/root/emailwiz-dns.txt ) && info "DNS records saved to /root/emailwiz-dns.txt"
( validate_dns ) || :
printf '\n' >&2
if [ "$_vrc" -eq 0 ]; then
ok "setup complete. Remaining manual steps (outside this server):"
else
warn "setup finished with validation failures (see above). Also required:"
fi
info "1. publish the DNS records in /root/emailwiz-dns.txt at your DNS provider"
info "2. ask your hosting provider to set reverse DNS (PTR) of $(primary_ipv4) to $MAIL_HOSTNAME"
info "3. then: sudo emailwiz validate && sudo emailwiz validate --external-test you@example.com"
return "$_vrc"
}
+63
View File
@@ -0,0 +1,63 @@
# emailwiz - TLS certificates: certbot issuance (TLS_MODE=certbot) and reload hook
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
tls_live_dir() { printf '/etc/letsencrypt/live/%s\n' "$MAIL_HOSTNAME"; }
tls_render() {
[ "$TLS_MODE" = certbot ] || return 0
render_template certbot-deploy-hook | stage_file \
/etc/letsencrypt/renewal-hooks/deploy/emailwiz-reload 755 root root -
}
# Print which program listens on TCP port 80: nginx, apache, none or other:NAME.
tls_port80_owner() {
_l=$(ss -Hltnp 'sport = :80' 2>/dev/null || :)
[ -n "$_l" ] || { echo none; return; }
case $_l in
*'"nginx"'*) echo nginx ;;
*'"apache2"'* | *'"httpd"'*) echo apache ;;
*) echo "other:$(printf '%s' "$_l" | sed -n 's/.*users:(("\([^"]*\)".*/\1/p' | head -1)" ;;
esac
}
# certbot certonly with the authenticator that fits port 80. nginx/apache
# authenticators only add the challenge temporarily and revert it, so no
# vhost is edited. A --dry-run against staging runs first.
tls_obtain() {
_live=$(tls_live_dir)
if [ -f "$_live/fullchain.pem" ] && [ -f "$_live/privkey.pem" ]; then
ok "certbot certificate for $MAIL_HOSTNAME already exists ($_live)"
return 0
fi
have certbot || die "certbot is not installed (run: sudo emailwiz install-packages)"
_owner=$(tls_port80_owner)
case $_owner in
nginx) _auth=--nginx; _plugin=python3-certbot-nginx ;;
apache) _auth=--apache; _plugin=python3-certbot-apache ;;
none) _auth=--standalone; _plugin= ;;
*) die "port 80 is used by ${_owner#other:}; stop it or obtain the certificate yourself and use TLS_MODE=external" ;;
esac
if [ -n "$_plugin" ] && ! pkg_installed "$_plugin"; then
log "installing $_plugin"
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$_plugin"
fi
_email=${CERTBOT_EMAIL:-postmaster@$DOMAIN}
log "requesting a certificate for $MAIL_HOSTNAME ($_auth, contact $_email)"
set -- certonly "$_auth" --non-interactive --agree-tos -m "$_email" \
--cert-name "$MAIL_HOSTNAME" -d "$MAIL_HOSTNAME"
certbot "$@" --dry-run || die "certbot dry run failed: check that $MAIL_HOSTNAME resolves here and port 80 is reachable"
certbot "$@" || die "certbot failed to obtain the certificate"
[ -f "$_live/fullchain.pem" ] || die "certbot reported success but $_live/fullchain.pem is missing"
ok "certificate obtained: $_live"
}
cmd_tls_obtain() {
need_root tls-obtain
MODE=apply
detect_os
config_load
config_validate
[ "$TLS_MODE" = certbot ] || die "TLS_MODE is '$TLS_MODE'; tls-obtain only applies to TLS_MODE=certbot" "$EX_USAGE"
tls_obtain
}
+289
View File
@@ -0,0 +1,289 @@
# emailwiz - validation (local config, TLS, SMTP policy, DNS, delivery tests)
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
V_FAIL=0; V_WARN=0
pass() { printf ' %sPASS%s %s\n' "$C_GRN" "$C_OFF" "$*"; }
fail() { printf ' %sFAIL%s %s\n' "$C_RED" "$C_OFF" "$*"; V_FAIL=$((V_FAIL + 1)); }
vwarn() { printf ' %sWARN%s %s\n' "$C_YEL" "$C_OFF" "$*"; V_WARN=$((V_WARN + 1)); }
skip() { printf ' SKIP %s\n' "$*"; }
section() { printf '\n%s\n' "$*"; }
dns_q() { host -W 5 -t "$1" "$2" 2>/dev/null || :; }
dns_txt() { dns_q TXT "$1" | sed -n 's/.*descriptive text //p' | sed 's/" "//g; s/"//g'; }
# smtp_dialog HOST PORT MODE - MODE plain|starttls|tls; feeds an EHLO.
smtp_ehlo() {
case $3 in
plain) (sleep 2; printf 'EHLO validate.invalid\r\n'; sleep 2; printf 'QUIT\r\n') |
timeout 15 nc -w 8 "$1" "$2" 2>/dev/null | tr -d '\r' ;;
starttls) (sleep 2; printf 'EHLO validate.invalid\r\n'; sleep 2; printf 'QUIT\r\n') |
timeout 15 openssl s_client -quiet -connect "$1:$2" -starttls smtp 2>/dev/null | tr -d '\r' ;;
tls) (sleep 2; printf 'EHLO validate.invalid\r\n'; sleep 2; printf 'QUIT\r\n') |
timeout 15 openssl s_client -quiet -connect "$1:$2" 2>/dev/null | tr -d '\r' ;;
esac
}
tls_verify() { # HOST PORT [starttls-proto]
_st=; [ -n "${3:-}" ] && _st="-starttls $3"
# shellcheck disable=SC2086
echo Q | timeout 15 openssl s_client -connect "$1:$2" $_st -servername "$MAIL_HOSTNAME" \
-verify_hostname "$MAIL_HOSTNAME" -verify_return_error -brief 2>&1 |
grep -q '^Verification: OK'
}
cert_days_left() {
_end=$(openssl x509 -in "$TLS_CERT" -noout -enddate 2>/dev/null | cut -d= -f2)
[ -n "$_end" ] || { echo -1; return; }
echo $(( ($(date -d "$_end" +%s) - $(date +%s)) / 86400 ))
}
validate_local() {
section "Services"
for _s in postfix dovecot opendkim $( [ "$SPAM_FILTER" = spamc ] && echo spamd ) \
$( [ "$FAIL2BAN" = yes ] && echo fail2ban ); do
systemctl is-active -q "$_s" && pass "$_s active" || fail "$_s not active"
done
if [ "$EMAILWIZ_TIMERS" = yes ]; then
for _t in emailwiz-certcheck.timer emailwiz-backup.timer; do
systemctl is-active -q "$_t" && pass "$_t active" || vwarn "$_t not active"
done
fi
section "Configuration syntax"
_o=$(postfix_validate_live) && pass "postfix check" || fail "postfix check: $_o"
_o=$(postconf -n 2>&1 >/dev/null | grep -i warning) && fail "postconf: $_o" || pass "postconf: no warnings"
_o=$(doveconf -n 2>&1 >/dev/null) && pass "doveconf -n" || fail "doveconf: $_o"
_o=$(opendkim -n 2>&1) && pass "opendkim -n" || fail "opendkim: $_o"
if [ "$FAIL2BAN" = yes ]; then
_o=$(fail2ban-client -t 2>&1) && pass "fail2ban-client -t" || fail "fail2ban: $_o"
for _j in postfix postfix-sasl dovecot; do
fail2ban-client status "$_j" >/dev/null 2>&1 && pass "fail2ban jail $_j" || fail "fail2ban jail $_j missing"
done
fi
section "Listening ports"
_ports="25 465 587 993"
case " $IMAP_PROTOCOLS " in *" pop3 "*) _ports="$_ports 995" ;; esac
for _p in $_ports; do
ss -Hltn "sport = :$_p" | grep -q . && pass "tcp/$_p listening" || fail "tcp/$_p not listening"
done
ss -Hltn "sport = :$DKIM_PORT" | grep -q "127.0.0.1:$DKIM_PORT" &&
pass "opendkim on 127.0.0.1:$DKIM_PORT" || fail "opendkim not on 127.0.0.1:$DKIM_PORT"
ss -Hltn "sport = :$DKIM_PORT" | grep -vq "127.0.0.1:$DKIM_PORT" &&
fail "opendkim listening beyond loopback" || :
section "TLS"
_kp=$(openssl pkey -in "$TLS_KEY" -pubout 2>/dev/null | sha256sum)
_cp=$(openssl x509 -in "$TLS_CERT" -noout -pubkey 2>/dev/null | sha256sum)
[ "$_kp" = "$_cp" ] && pass "certificate matches key" || fail "certificate/key mismatch"
openssl x509 -in "$TLS_CERT" -noout -checkhost "$MAIL_HOSTNAME" 2>/dev/null | grep -q 'does match' &&
pass "certificate valid for $MAIL_HOSTNAME" || fail "certificate does not cover $MAIL_HOSTNAME"
_d=$(cert_days_left)
if [ "$_d" -lt 0 ]; then fail "certificate expired or unreadable"
elif [ "$_d" -lt "$CERT_WARN_DAYS" ]; then vwarn "certificate expires in $_d days"
else pass "certificate valid for $_d more days"; fi
if [ "$TLS_MODE" = certbot ]; then
systemctl is-active -q certbot.timer && pass "certbot.timer active (automatic renewal)" ||
fail "certbot.timer not active: certificate will not renew"
[ -x /etc/letsencrypt/renewal-hooks/deploy/emailwiz-reload ] && pass "renewal reload hook installed" ||
fail "renewal hook /etc/letsencrypt/renewal-hooks/deploy/emailwiz-reload missing"
fi
_ko=$(stat -c '%a' "$TLS_KEY")
case $_ko in ?[0-7]0 | ?00) pass "private key not world-readable ($_ko)" ;; *) fail "private key mode $_ko" ;; esac
tls_verify 127.0.0.1 465 && pass "smtps/465 TLS verifies" || fail "smtps/465 TLS"
tls_verify 127.0.0.1 587 smtp && pass "submission/587 STARTTLS verifies" || fail "submission/587 STARTTLS"
tls_verify 127.0.0.1 25 smtp && pass "smtp/25 STARTTLS verifies" || fail "smtp/25 STARTTLS"
tls_verify 127.0.0.1 993 && pass "imaps/993 TLS verifies" || fail "imaps/993 TLS"
if echo Q | timeout 10 openssl s_client -connect 127.0.0.1:993 -tls1_1 2>&1 | grep -q '^Protocol *: TLSv1.1'; then
fail "imaps accepts TLS 1.1"
else
pass "imaps refuses TLS 1.1"
fi
section "SMTP policy"
if have nc; then
smtp_ehlo 127.0.0.1 25 plain | grep -q '^250.AUTH' && fail "AUTH offered on port 25 (plaintext)" ||
pass "no AUTH on port 25 before TLS"
smtp_ehlo 127.0.0.1 587 plain | grep -q '^250.AUTH' && fail "AUTH offered on 587 before STARTTLS" ||
pass "no AUTH on 587 before STARTTLS"
else
skip "nc not installed: plaintext EHLO checks"
fi
smtp_ehlo 127.0.0.1 25 starttls | grep -q '^250.AUTH' && fail "AUTH offered on port 25 after STARTTLS" ||
pass "no AUTH on port 25 after STARTTLS"
smtp_ehlo 127.0.0.1 587 starttls | grep -q '^250.AUTH' && pass "AUTH offered on 587 after STARTTLS" ||
fail "no AUTH on 587 after STARTTLS"
smtp_ehlo 127.0.0.1 465 tls | grep -q '^250.AUTH' && pass "AUTH offered on 465" || fail "no AUTH on 465"
validate_relay
section "DKIM key"
_k=$(dkim_key_path)
if [ -f "$_k" ]; then
[ "$(stat -c '%a %U %G' "$_k")" = "640 root opendkim" ] && pass "key $_k is 0640 root:opendkim" ||
fail "key permissions: $(stat -c '%a %U %G' "$_k")"
_o=$(su -s /bin/sh opendkim -c "test -r '$_k'" 2>&1) && pass "opendkim user can read key" ||
fail "opendkim cannot read key"
else
fail "DKIM key missing: $_k"
fi
}
# Probe relaying from the public address so the client is not in mynetworks.
validate_relay() {
have nc || { skip "nc not installed: open-relay probe"; return; }
_ip=$(primary_ipv4)
[ -n "$_ip" ] || { skip "no IPv4 address for relay probe"; return; }
_r=$( (sleep 2; printf 'EHLO %s\r\n' "$MAIL_HOSTNAME"; sleep 1
printf 'MAIL FROM:<relay-probe@gmail.com>\r\n'; sleep 1
printf 'RCPT TO:<relay-probe@outlook.com>\r\n'; sleep 2; printf 'QUIT\r\n') |
timeout 20 nc -w 8 "$_ip" 25 2>/dev/null | tr -d '\r')
if printf '%s\n' "$_r" | grep -Eq '^(554|454) .*Relay access denied'; then
pass "unauthenticated relay refused on $_ip:25"
elif printf '%s\n' "$_r" | grep -Eq '^250 2\.1\.5'; then
fail "OPEN RELAY: $_ip:25 accepted an external recipient without auth"
else
vwarn "relay probe inconclusive: $(printf '%s\n' "$_r" | tail -2 | tr '\n' ' ')"
fi
}
validate_dns() {
section "DNS (as seen by this host's resolver)"
have host || { skip "host(1) missing (bind9-host)"; return; }
_ip4=$(primary_ipv4); _ip6=$(primary_ipv6)
_mx=$(dns_q MX "$DOMAIN" | awk '/mail is handled by/ {print $NF}' | sed 's/\.$//')
printf '%s\n' "$_mx" | grep -qx "$MAIL_HOSTNAME" && pass "MX $DOMAIN -> $MAIL_HOSTNAME" ||
fail "MX for $DOMAIN does not point to $MAIL_HOSTNAME (got: ${_mx:-none})"
_a=$(dns_q A "$MAIL_HOSTNAME" | awk '/has address/ {print $NF}')
printf '%s\n' "$_a" | grep -qx "$_ip4" && pass "A $MAIL_HOSTNAME -> $_ip4" ||
fail "A $MAIL_HOSTNAME is '${_a:-none}', host IPv4 is $_ip4"
_aaaa=$(dns_q AAAA "$MAIL_HOSTNAME" | awk '/has IPv6 address/ {print $NF}')
if [ -n "$_aaaa" ] && [ -z "$_ip6" ]; then
fail "AAAA $MAIL_HOSTNAME published ($_aaaa) but host has no global IPv6"
elif [ -n "$_ip6" ] && [ -z "$_aaaa" ]; then
vwarn "host has IPv6 $_ip6 but no AAAA for $MAIL_HOSTNAME (IPv4-only mail is fine)"
elif [ -n "$_aaaa" ]; then
[ "$_aaaa" = "$_ip6" ] && pass "AAAA $MAIL_HOSTNAME -> $_ip6" || fail "AAAA $_aaaa != host $_ip6"
else
pass "no AAAA and no global IPv6 (consistent)"
fi
_ptr=$(dns_q PTR "$_ip4" | awk '/domain name pointer/ {print $NF}' | sed 's/\.$//')
[ "$_ptr" = "$MAIL_HOSTNAME" ] && pass "PTR $_ip4 -> $MAIL_HOSTNAME (forward-confirmed above)" ||
fail "PTR $_ip4 is '${_ptr:-none}', expected $MAIL_HOSTNAME (ask your hosting provider)"
if [ -n "$_ip6" ]; then
_ptr6=$(dns_q PTR "$_ip6" | awk '/domain name pointer/ {print $NF}' | sed 's/\.$//')
[ "$_ptr6" = "$MAIL_HOSTNAME" ] && pass "PTR $_ip6 -> $MAIL_HOSTNAME" ||
vwarn "IPv6 PTR is '${_ptr6:-none}' (outbound prefers IPv4 if SMTP_ADDRESS_PREFERENCE=auto)"
fi
_spf=$(dns_txt "$DOMAIN" | grep '^v=spf1' || :)
if [ -z "$_spf" ]; then fail "no SPF record on $DOMAIN"
elif [ "$(printf '%s\n' "$_spf" | wc -l)" -gt 1 ]; then fail "multiple SPF records on $DOMAIN"
else
case " $_spf " in
*" ip4:$_ip4 "* | *" mx "* | *" a:$MAIL_HOSTNAME "*) pass "SPF authorises this host: $_spf" ;;
*) fail "SPF does not cover $_ip4: $_spf" ;;
esac
case " $_spf " in *" ip6:"*) [ -z "$_ip6" ] && vwarn "SPF lists ip6: but host has no global IPv6" ;; esac
fi
_dk=$(dns_txt "$DKIM_SELECTOR._domainkey.$DOMAIN" | sed -n 's/.*p=\([A-Za-z0-9+/=]*\).*/\1/p')
if [ -z "$_dk" ]; then fail "no DKIM record at $DKIM_SELECTOR._domainkey.$DOMAIN"
elif [ -f "$(dkim_key_path)" ] && [ "$_dk" = "$(dkim_public_b64)" ]; then pass "DKIM DNS key matches local private key"
else fail "DKIM DNS key does NOT match $(dkim_key_path)"; fi
_dm=$(dns_txt "_dmarc.$DOMAIN" | grep '^v=DMARC1' || :)
[ -n "$_dm" ] && pass "DMARC: $_dm" || fail "no DMARC record at _dmarc.$DOMAIN"
}
validate_outbound_port() {
section "Outbound SMTP reachability"
have nc || { skip "nc not installed"; return; }
if timeout 10 nc -4 -z -w 6 gmail-smtp-in.l.google.com 25 2>/dev/null; then
pass "TCP 25 outbound to gmail-smtp-in.l.google.com (IPv4)"
else
fail "cannot reach port 25 outbound over IPv4 (provider block?)"
fi
}
# Wait for a message (by Message-ID) to reach a final status; print status line.
_await_delivery() {
_mid=$1; _since=$2; _i=0
while [ $_i -lt 60 ]; do
_qid=$(journalctl --since "$_since" -o cat -t postfix/cleanup 2>/dev/null |
awk -v m="message-id=<$_mid>" 'index($0, m) {sub(":", "", $1); print $1}' | tail -1)
if [ -n "$_qid" ]; then
_st=$(journalctl --since "$_since" -o cat 2>/dev/null | grep "^$_qid: " | grep -E 'status=(sent|bounced|deferred)' | tail -1)
[ -n "$_st" ] && { printf '%s\n%s\n' "$_qid" "$_st"; return 0; }
fi
_i=$((_i + 1)); sleep 2
done
return 1
}
_send_test() { # TO
_mid="emailwiz-test.$(date +%s).$$@$MAIL_HOSTNAME"
{
printf 'From: emailwiz test <postmaster@%s>\n' "$DOMAIN"
printf 'To: <%s>\nSubject: emailwiz delivery test %s\n' "$1" "$(date -u +%FT%TZ)"
printf 'Message-ID: <%s>\nDate: %s\nMIME-Version: 1.0\n' "$_mid" "$(date -R)"
printf 'Content-Type: text/plain; charset=us-ascii\n\n'
printf 'Automated test from emailwiz on %s. No action needed.\n' "$MAIL_HOSTNAME"
} | /usr/sbin/sendmail -oi -f "postmaster@$DOMAIN" -- "$1"
printf '%s\n' "$_mid"
}
validate_delivery() { # TO LABEL
section "Delivery test: $2"
_since=$(date '+%Y-%m-%d %H:%M:%S')
_mid=$(_send_test "$1")
if ! _r=$(_await_delivery "$_mid" "$_since"); then
fail "no final delivery status after 120s (Message-ID $_mid)"; return
fi
_qid=$(printf '%s\n' "$_r" | head -1); _st=$(printf '%s\n' "$_r" | tail -1)
_st=$(printf '%s\n' "$_st" | sed -E 's/to=<[^>]*>/to=<...>/')
case $_st in
*status=sent*) pass "delivered: $(printf '%s' "$_st" | sed 's/^[^ ]* //' | cut -c1-160)" ;;
*) fail "$(printf '%s' "$_st" | cut -c1-200)" ;;
esac
if journalctl --since "$_since" -o cat -t opendkim 2>/dev/null |
grep -q "^$_qid: DKIM-Signature field added (s=$DKIM_SELECTOR, d=$DOMAIN)"; then
pass "DKIM signature added (s=$DKIM_SELECTOR d=$DOMAIN)"
else
fail "no DKIM signature logged for $_qid"
fi
}
cmd_validate() {
_dns=yes; _local_deliver=no; _ext=; _renew=no
while [ $# -gt 0 ]; do
case $1 in
--no-dns) _dns=no ;;
--deliver-test) _local_deliver=yes ;;
--external-test) _ext=$2; shift ;;
--renew-test) _renew=yes ;;
*) die "validate: unknown option $1" "$EX_USAGE" ;;
esac
shift
done
need_root validate
MODE=validate
preflight
validate_local
if [ "$_dns" = yes ]; then validate_dns; validate_outbound_port; fi
if [ "$_renew" = yes ]; then
section "Certificate renewal"
if [ "$TLS_MODE" != certbot ]; then
skip "TLS_MODE=$TLS_MODE: renewal is managed outside emailwiz"
elif certbot renew --dry-run --cert-name "$MAIL_HOSTNAME" >/dev/null 2>&1; then
pass "certbot renew --dry-run succeeded"
else
fail "certbot renew --dry-run failed (run it by hand to see why)"
fi
fi
[ "$_local_deliver" = yes ] && validate_delivery "postmaster@$DOMAIN" "local (postmaster@$DOMAIN)"
if [ -n "$_ext" ]; then
printf '%s' "$_ext" | grep -q '@' || die "--external-test needs an email address" "$EX_USAGE"
validate_delivery "$_ext" "external ($_ext)"
info "check the received message headers for dkim=pass spf=pass dmarc=pass"
fi
printf '\n%s failure(s), %s warning(s)\n' "$V_FAIL" "$V_WARN"
[ "$V_FAIL" -eq 0 ] || exit "$EX_VALIDATION"
}
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# Managed by emailwiz: reload mail services after certbot renews @MAIL_HOSTNAME@.
set -eu
case " ${RENEWED_DOMAINS:-} " in
*" @MAIL_HOSTNAME@ "*) ;;
*) exit 0 ;;
esac
postfix check && systemctl reload postfix
doveconf -n >/dev/null && systemctl reload dovecot
+5
View File
@@ -0,0 +1,5 @@
require ["fileinto", "mailbox"];
# Managed by emailwiz: file SpamAssassin-flagged mail into Junk.
if header :contains "X-Spam-Flag" "YES" {
fileinto :create "Junk";
}
+90
View File
@@ -0,0 +1,90 @@
# Managed by emailwiz - do not edit; change /etc/emailwiz/emailwiz.conf and rerun.
# Dovecot 2.4 configuration (Debian 13). conf.d/ is intentionally not included.
# Derived from emailwiz by Luke Smith (GPL-3.0); rewritten for Dovecot 2.4.
dovecot_config_version = @DOVECOT_CONFIG_VERSION@
dovecot_storage_version = 2.4.0
protocols = @IMAP_PROTOCOLS@
ssl = required
ssl_server_cert_file = @TLS_CERT@
ssl_server_key_file = @TLS_KEY@
ssl_min_protocol = TLSv1.2
auth_mechanisms = plain login
auth_allow_cleartext = no
# Log in with the bare local user name; strip any @domain the client sends.
auth_username_format = %{user | username | lower}
# Accounts are local system users; passwords come from PAM.
userdb users {
driver = passwd
}
passdb pam {
driver = pam
}
# Maildir in ~/Mail; folders are Mail/Sent, not Mail/.Sent
mail_driver = maildir
mail_path = ~/Mail
mail_inbox_path = ~/Mail/Inbox
mailbox_list_layout = fs
namespace inbox {
inbox = yes
mailbox Drafts {
special_use = \Drafts
auto = subscribe
}
mailbox Junk {
special_use = \Junk
auto = subscribe
autoexpunge = @JUNK_AUTOEXPUNGE@
}
mailbox Sent {
special_use = \Sent
auto = subscribe
}
mailbox Trash {
special_use = \Trash
}
mailbox Archive {
special_use = \Archive
}
}
# SASL for Postfix submission.
service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}
}
# Postfix delivers through dovecot-lda; create Junk on first spam delivery.
lda_mailbox_autocreate = yes
lda_mailbox_autosubscribe = yes
protocol lda {
mail_plugins {
sieve = yes
}
}
protocol pop3 {
pop3_uidl_format = %{uid | hex(8)}%{uidvalidity | hex(8)}
pop3_no_flag_updates = yes
}
sieve_script personal {
driver = file
type = personal
path = ~/.sieve
active_path = ~/.dovecot.sieve
}
sieve_script default {
type = default
driver = file
path = /var/lib/dovecot/sieve/default.sieve
}
+7
View File
@@ -0,0 +1,7 @@
# Managed by emailwiz
[Unit]
Description=emailwiz: back up mail configuration and DKIM keys
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/emailwiz backup --scheduled
+11
View File
@@ -0,0 +1,11 @@
# Managed by emailwiz
[Unit]
Description=emailwiz: weekly mail configuration backup
[Timer]
OnCalendar=weekly
RandomizedDelaySec=2h
Persistent=true
[Install]
WantedBy=timers.target
+8
View File
@@ -0,0 +1,8 @@
# Managed by emailwiz
[Unit]
Description=emailwiz: warn postmaster when the mail TLS certificate nears expiry
After=network-online.target postfix.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/emailwiz cert-check --notify
+11
View File
@@ -0,0 +1,11 @@
# Managed by emailwiz
[Unit]
Description=emailwiz: daily mail certificate expiry check
[Timer]
OnCalendar=daily
RandomizedDelaySec=1h
Persistent=true
[Install]
WantedBy=timers.target
+10
View File
@@ -0,0 +1,10 @@
# Managed by emailwiz. Debian 13 logs to the journal only (no rsyslog), and
# /etc/fail2ban/jail.d/defaults-debian.conf already sets backend = systemd.
[postfix]
enabled = true
[postfix-sasl]
enabled = true
[dovecot]
enabled = true
+18
View File
@@ -0,0 +1,18 @@
# Managed by emailwiz - do not edit; change /etc/emailwiz/emailwiz.conf and rerun.
Syslog yes
SyslogSuccess yes
UMask 007
UserID opendkim
PidFile /run/opendkim/opendkim.pid
Mode sv
Canonicalization relaxed/simple
OversignHeaders From
TrustAnchorFile /usr/share/dns/root.key
KeyTable file:@DKIM_DIR@/keytable
SigningTable refile:@DKIM_DIR@/signingtable
InternalHosts refile:@DKIM_DIR@/trustedhosts
ExternalIgnoreList refile:@DKIM_DIR@/trustedhosts
# TCP on loopback only (Postfix smtpd is chrooted; avoids a socket in the spool).
Socket inet:@DKIM_PORT@@127.0.0.1
+15
View File
@@ -0,0 +1,15 @@
# Debian 13 test environment with systemd as PID 1 and the full package set.
FROM docker.io/library/debian:trixie
ENV DEBIAN_FRONTEND=noninteractive
RUN printf 'postfix postfix/main_mailer_type select Internet Site\npostfix postfix/mailname string example.org\n' | debconf-set-selections \
&& apt-get update \
&& apt-get install -y --no-install-recommends systemd systemd-sysv dbus iproute2 procps \
netcat-openbsd openssl ca-certificates bind9-host swaks libnet-ssleay-perl libauthen-sasl-perl \
postfix postfix-pcre dovecot-core dovecot-imapd dovecot-pop3d dovecot-sieve \
opendkim opendkim-tools spamd spamc fail2ban dns-root-data python3-dkim shellcheck \
make ufw iptables nginx-light certbot python3-certbot-nginx \
&& rm -rf /var/lib/apt/lists/*
# Mailbox owner of the upstream-install fixture
RUN useradd -m -G mail -s /bin/bash alice && useradd -m -s /bin/sh postmaster
STOPSIGNAL SIGRTMIN+3
CMD ["/sbin/init"]
+3
View File
@@ -0,0 +1,3 @@
# See man 5 aliases for format
postmaster: root
root: alice
+30
View File
@@ -0,0 +1,30 @@
# NOTE: This is a legacy configuration file. It is not used by the opendkim
# systemd service. Please use the corresponding configuration parameters in
# /etc/opendkim.conf instead.
#
# Previously, one would edit the default settings here, and then execute
# /usr/lib/opendkim/opendkim.service.generate to generate systemd override
# files at /etc/systemd/system/opendkim.service.d/override.conf and
# /etc/tmpfiles.d/opendkim.conf. While this is still possible, it is now
# recommended to adjust the settings directly in /etc/opendkim.conf.
#
#DAEMON_OPTS=""
# Change to /var/spool/postfix/run/opendkim to use a Unix socket with
# postfix in a chroot:
#RUNDIR=/var/spool/postfix/run/opendkim
RUNDIR=/run/opendkim
#
# Uncomment to specify an alternate socket
# Note that setting this will override any Socket value in opendkim.conf
# default:
# listen on all interfaces on port 54321:
#SOCKET=inet:54321
# listen on loopback on port 12345:
#SOCKET=inet:12345@localhost
# listen on 192.0.2.1 on port 12345:
#SOCKET=inet:12345@192.0.2.1
USER=opendkim
GROUP=opendkim
PIDFILE=$RUNDIR/$NAME.pid
EXTRAAFTER=
SOCKET="inet:12301@localhost"
+23
View File
@@ -0,0 +1,23 @@
# /etc/default/spamd
# Duncan Findlay
# WARNING: please read README.spamd before using.
# There may be security risks.
# Options
# See man spamd for possible options. The -d option is automatically added.
# SpamAssassin uses a preforking model, so be careful! You need to
# make sure --max-children is not set to anything higher than 5,
# unless you know what you're doing.
OPTIONS="--create-prefs --max-children 5 --helper-home-dir"
# Pid file
# Where should spamd write its PID to file? If you use the -u or
# --username option above, this needs to be writable by that user.
# Note that this setting is not used when spamd is managed by systemd
PIDFILE="/run/spamd.pid"
# Set nice level of spamd
#NICE="--nicelevel 15"
@@ -0,0 +1,93 @@
dovecot_config_version = 2.4.1
dovecot_storage_version = 2.4.0
# Dovecot 2.4 config. conf.d is not included.
ssl = required
ssl_server_cert_file = /etc/ssl/example.org/fullchain.pem
ssl_server_key_file = /etc/ssl/example.org/privkey.pem
ssl_min_protocol = TLSv1.2
ssl_cipher_list = EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA256:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA384:EDH+aRSA+AESGCM:EDH+aRSA+SHA256:EDH+aRSA:EECDH:!aNULL:!eNULL:!MEDIUM:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!RC4:!SEED
ssl_server_prefer_ciphers = server
ssl_server_dh_file = /usr/share/dovecot/dh.pem
auth_mechanisms = plain login
auth_username_format = %{user | username }
protocols = imap pop3
# Search for valid users in /etc/passwd
userdb users {
driver = passwd
}
# Fallback: Use PAM to find user passwords
passdb pam {
driver = pam
}
# ~/Mail with LAYOUT=fs, so folders are Sent rather than .Sent.
mailbox_list_layout = fs
mail_driver = maildir
mail_path = ~/Mail
mail_inbox_path = ~/Mail/Inbox
namespace inbox {
inbox = yes
mailbox Drafts {
special_use = \Drafts
auto = subscribe
}
mailbox Junk {
special_use = \Junk
auto = subscribe
autoexpunge = 30d
}
mailbox Sent {
special_use = \Sent
auto = subscribe
}
mailbox Trash {
special_use = \Trash
}
mailbox Archive {
special_use = \Archive
}
}
# Here we let Postfix use Dovecot's authentication system.
service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}
}
protocol lda {
mail_plugins = sieve
}
protocol lmtp {
mail_plugins = sieve
}
protocol pop3 {
pop3_uidl_format = %{uid | hex(8)}%{uidvalidity | hex(8)}
pop3_no_flag_updates = yes
}
sieve_script personal {
driver = file
type = personal
path = ~/.sieve
active_path = ~/.dovecot.sieve
}
sieve_script default {
type = default
driver = file
path = /var/lib/dovecot/sieve/default.sieve
}
sieve_script global {
type = global
path = /var/lib/dovecot/sieve/
}
@@ -0,0 +1,8 @@
[postfix]
enabled = true
[postfix-sasl]
enabled = true
[sieve]
enabled = true
[dovecot]
enabled = true
+55
View File
@@ -0,0 +1,55 @@
# This is a basic configuration for signing and verifying. It can easily be
# adapted to suit a basic installation. See opendkim.conf(5) and
# /usr/share/doc/opendkim/examples/opendkim.conf.sample for complete
# documentation of available configuration parameters.
Syslog yes
SyslogSuccess yes
#LogWhy no
# Common signing and verification parameters. In Debian, the "From" header is
# oversigned, because it is often the identity key used by reputation systems
# and thus somewhat security sensitive.
Canonicalization relaxed/simple
#Mode sv
#SubDomains no
OversignHeaders From
# Signing domain, selector, and key (required). For example, perform signing
# for domain "example.com" with selector "2020" (2020._domainkey.example.com),
# using the private key stored in /etc/dkimkeys/example.private. More granular
# setup options can be found in /usr/share/doc/opendkim/README.opendkim.
#Domain example.com
#Selector 2020
#KeyFile /etc/dkimkeys/example.private
# In Debian, opendkim runs as user "opendkim". A umask of 007 is required when
# using a local socket with MTAs that access the socket as a non-privileged
# user (for example, Postfix). You may need to add user "postfix" to group
# "opendkim" in that case.
UserID opendkim
UMask 007
# Socket for the MTA connection (required). If the MTA is inside a chroot jail,
# it must be ensured that the socket is accessible. In Debian, Postfix runs in
# a chroot in /var/spool/postfix, therefore a Unix socket would have to be
# configured as shown on the last line below.
#Socket local:/run/opendkim/opendkim.sock
#Socket inet:8891@localhost
#Socket inet:8891
#Socket local:/var/spool/postfix/opendkim/opendkim.sock
PidFile /run/opendkim/opendkim.pid
# Hosts for which to sign rather than verify, default is 127.0.0.1. See the
# OPERATION section of opendkim(8) for more information.
#InternalHosts 192.168.0.0/16, 10.0.0.0/8, 172.16.0.0/12
# The trust anchor enables DNSSEC. In Debian, the trust anchor file is provided
# by the package dns-root-data.
TrustAnchorFile /usr/share/dns/root.key
#Nameservers 127.0.0.1
KeyTable file:/etc/postfix/dkim/keytable
SigningTable refile:/etc/postfix/dkim/signingtable
InternalHosts refile:/etc/postfix/dkim/trustedhosts
Socket inet:12301@localhost
+8
View File
@@ -0,0 +1,8 @@
#%PAM-1.0
@include common-auth
@include common-account
@include common-session
auth required pam_unix.so nullok
account required pam_unix.so
@@ -0,0 +1 @@
mail._domainkey.example.org example.org:mail:/etc/postfix/dkim/example.org/mail.private
@@ -0,0 +1 @@
*@example.org mail._domainkey.example.org
@@ -0,0 +1,2 @@
127.0.0.1
10.1.0.0/16
@@ -0,0 +1,2 @@
/^Received:.*/ IGNORE
/^X-Originating-IP:/ IGNORE
@@ -0,0 +1 @@
/^(.*)@example\.org$/ ${1}
+113
View File
@@ -0,0 +1,113 @@
# See /usr/share/postfix/main.cf.dist for a commented, more complete version
# See http://www.postfix.org/COMPATIBILITY_README.html
compatibility_level = 3.9
# Which domain that locally-originated mail appears to come from.
# Debian policy suggests to read this value from /etc/mailname.
#XX needs a review in postinst&config
#myorigin = /etc/mailname
#myorigin = $mydomain
myorigin = /etc/mailname
# Text that follows the 220 code in the SMTP server's greeting banner.
# You MUST specify $myhostname at the start due to an RFC requirement.
smtpd_banner = $myhostname ESMTP $mail_name (Debian)
# IP protocols to use: ipv4, ipv6, or all
# (set this explicitly so `post-install upgrade-configuration' wont complain)
inet_protocols = all
# List of "trusted" SMTP clients (maptype:mapname allowed) that have more
# privileges than "strangers". If mynetworks is not specified (the default),
# mynetworks_style is used to compute its value.
#mynetworks_style = class
#mynetworks_style = subnet
mynetworks_style = host
#
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
# List of domains (maptype:mapname allowed) that this machine considers
# itself the final destination for.
mydestination = $myhostname, $mydomain, mail, localhost.localdomain, localhost, localhost.$mydomain
# Maximum size of a user mailbox
mailbox_size_limit = 0
# Optional external command to use instead of mailbox delivery. If set,
# you must set up an alias to forward root mail to a real user.
#mailbox_command = /usr/bin/procmail
#mailbox_command = /usr/bin/procmail -a "$EXTENSION"
mailbox_command = /usr/lib/dovecot/deliver
# List of alias maps to use to lookup local addresses.
# Per Debian Policy it should be /etc/aliases.
alias_maps = hash:/etc/aliases
# List of alias maps to make indexes on, when running newaliases.
alias_database = hash:/etc/aliases
# Notify (or not) local biff service when new mail arrives.
# Rarely used these days.
biff = no
# Separator between user name and address extension (user+foo@domain)
#recipient_delimiter = +
recipient_delimiter = +
# A host to send "other" mail to
#relayhost = $mydomain
#relayhost = [gateway.example.com]
#relayhost = [ip.add.re.ss]:port
#relayhost = uucphost
relayhost =
# Where to look for Cyrus SASL configuration files. Upstream default is unset
# (use compiled-in SASL library default), Debian Policy says it should be
# /etc/postfix/sasl.
cyrus_sasl_config_path = /etc/postfix/sasl
# SMTP server RSA key and certificate in PEM format
smtpd_tls_key_file = /etc/ssl/example.org/privkey.pem
smtpd_tls_cert_file = /etc/ssl/example.org/fullchain.pem
# SMTP Server security level: none|may|encrypt
smtpd_tls_security_level = may
# List of CAs for SMTP Client to trust
# Prefer this over _CApath when smtp is running chrooted
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
# SMTP Client TLS security level: none|may|encrypt|...
smtp_tls_security_level = may
# SMTP Client TLS session cache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_relay_restrictions = permit_sasl_authenticated, reject_unauth_destination
myhostname = mail.example.org
inet_interfaces = all
mail_name = example.org
mydomain = example.org
smtpd_tls_auth_only = yes
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtp_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtpd_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtp_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtpd_sasl_auth_enable = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sender_login_maps = pcre:/etc/postfix/login_maps.pcre
smtpd_sender_restrictions = reject_sender_login_mismatch, permit_sasl_authenticated, permit_mynetworks, reject_unknown_reverse_client_hostname, reject_unknown_sender_domain
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination, reject_unknown_recipient_domain
smtpd_helo_required = yes
smtpd_helo_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, reject_unknown_helo_hostname
home_mailbox = Mail/Inbox/
header_checks = regexp:/etc/postfix/header_checks
smtpd_sasl_security_options = noanonymous, noplaintext
smtpd_sasl_tls_security_options = noanonymous
milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:localhost:12301
non_smtpd_milters = inet:localhost:12301
smtpd_forbid_bare_newline = normalize
smtpd_forbid_bare_newline_exclusions = $mynetworks
+165
View File
@@ -0,0 +1,165 @@
#
# Postfix master process configuration file. For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: https://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type private unpriv chroot wakeup maxproc command + args
# (yes) (yes) (no) (never) (100)
# ==========================================================================
#smtp inet n - y - 1 postscreen
#smtpd pass - - y - - smtpd
#dnsblog unix - - y - 0 dnsblog
#tlsproxy unix - - y - 0 tlsproxy
# Choose one: enable submission for loopback clients only, or for any client.
#127.0.0.1:submission inet n - y - - smtpd
#submission inet n - y - - smtpd
# -o syslog_name=postfix/submission
# -o smtpd_forbid_unauth_pipelining=no
# -o smtpd_tls_security_level=encrypt
# -o smtpd_sasl_auth_enable=yes
# -o smtpd_tls_auth_only=yes
# -o local_header_rewrite_clients=static:all
# -o smtpd_hide_client_session=yes
# -o smtpd_reject_unlisted_recipient=no
# Instead of specifying complex smtpd_<xxx>_restrictions here,
# specify "smtpd_<xxx>_restrictions=$mua_<xxx>_restrictions"
# here, and specify mua_<xxx>_restrictions in main.cf (where
# "<xxx>" is "client", "helo", "sender", "relay", or "recipient").
# -o smtpd_client_restrictions=
# -o smtpd_helo_restrictions=
# -o smtpd_sender_restrictions=
# -o smtpd_relay_restrictions=
# -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
# -o milter_macro_daemon_name=ORIGINATING
# Choose one: enable submissions for loopback clients only, or for any client.
#127.0.0.1:submissions inet n - y - - smtpd
#submissions inet n - y - - smtpd
# -o syslog_name=postfix/submissions
# -o smtpd_forbid_unauth_pipelining=no
# -o smtpd_tls_wrappermode=yes
# -o smtpd_sasl_auth_enable=yes
# -o local_header_rewrite_clients=static:all
# -o smtpd_hide_client_session=yes
# -o smtpd_reject_unlisted_recipient=no
# Instead of specifying complex smtpd_<xxx>_restrictions here,
# specify "smtpd_<xxx>_restrictions=$mua_<xxx>_restrictions"
# here, and specify mua_<xxx>_restrictions in main.cf (where
# "<xxx>" is "client", "helo", "sender", "relay", or "recipient").
# -o smtpd_client_restrictions=
# -o smtpd_helo_restrictions=
# -o smtpd_sender_restrictions=
# -o smtpd_relay_restrictions=
# -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
# -o milter_macro_daemon_name=ORIGINATING
#628 inet n - y - - qmqpd
pickup unix n - y 60 1 pickup
cleanup unix n - y - 0 cleanup
qmgr unix n - n 300 1 qmgr
#qmgr unix n - n 300 1 oqmgr
tlsmgr unix - - y 1000? 1 tlsmgr
rewrite unix - - y - - trivial-rewrite
bounce unix - - y - 0 bounce
defer unix - - y - 0 bounce
trace unix - - y - 0 bounce
verify unix - - y - 1 verify
flush unix n - y 1000? 0 flush
proxymap unix - - n - - proxymap
proxywrite unix - - n - 1 proxymap
relay unix - - y - - smtp
# -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq unix n - y - - showq
error unix - - y - - error
retry unix - - y - - error
discard unix - - y - - discard
local unix - n n - - local
virtual unix - n n - - virtual
lmtp unix - - y - - lmtp
anvil unix - - y - 1 anvil
scache unix - - y - 1 scache
postlog unix-dgram n - n - 1 postlogd
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent. See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
#maildrop unix - n n - - pipe
# flags=DRXhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
# lmtp cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
# mailbox_transport = lmtp:inet:localhost
# virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus unix - n n - - pipe
# flags=DRX user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
#
# Old example of delivery via Cyrus.
#
#old-cyrus unix - n n - - pipe
# flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
#uucp unix - n n - - pipe
# flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# ====================================================================
#
# Other external delivery methods.
#
#ifmail unix - n n - - pipe
# flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
#
#bsmtp unix - n n - - pipe
# flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -f $sender $nexthop $recipient
#
#scalemail-backend unix - n n - 2 pipe
# flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store
# ${nexthop} ${user} ${extension}
#
#mailman unix - n n - - pipe
# flags=FRX user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
# ${nexthop} ${user}
smtp unix - - n - - smtp
smtp inet n - y - - smtpd
-o content_filter=spamassassin
submission inet n - y - - smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_security_level=encrypt
-o smtpd_tls_auth_only=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
-o smtpd_sender_restrictions=reject_sender_login_mismatch
-o smtpd_sender_login_maps=pcre:/etc/postfix/login_maps.pcre
-o smtpd_recipient_restrictions=permit_sasl_authenticated,reject_unauth_destination
smtps inet n - y - - smtpd
-o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
spamassassin unix - n n - - pipe
user=debian-spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}
@@ -0,0 +1,3 @@
[Service]
ExecStart=
ExecStart=/usr/sbin/opendkim -P /run/opendkim/opendkim.pid -p inet:12301@localhost
@@ -0,0 +1,5 @@
require ["fileinto", "mailbox"];
if header :contains "X-Spam-Flag" "YES"
{
fileinto "Junk";
}
+322
View File
@@ -0,0 +1,322 @@
#!/bin/sh
# emailwiz test scenarios; runs as root inside the disposable test container.
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck disable=SC2016,SC2012 # sh -c strings expand in the child; backup names are ours
set -u
SCENARIO=$1
PASS=0; FAILS=0
t_ok() { PASS=$((PASS + 1)); echo " ok $*"; }
t_fail() { FAILS=$((FAILS + 1)); echo " FAIL $*"; }
check() { _d=$1; shift; if "$@" >/tmp/check.out 2>&1; then t_ok "$_d"; else t_fail "$_d"; sed 's/^/ /' /tmp/check.out | tail -15; fi; }
check_not() { _d=$1; shift; if "$@" >/tmp/check.out 2>&1; then t_fail "$_d"; sed 's/^/ /' /tmp/check.out | tail -15; else t_ok "$_d"; fi; }
section() { echo; echo "== $*"; }
DOMAIN=example.org
HOST=mail.example.org
TESTPW='container-only-test-pw'
install_tool() {
cp -a /src /usr/local/lib/emailwiz
ln -sf /usr/local/lib/emailwiz/emailwiz /usr/local/sbin/emailwiz
}
# Test-only CA + wildcard cert in /etc/ssl/DOMAIN (an externally managed certificate).
make_cert() {
d=/etc/ssl/$DOMAIN; mkdir -p "$d"; cd /tmp || exit 1
openssl req -x509 -newkey rsa:2048 -nodes -days 30 -subj /CN=emailwiz-test-CA \
-keyout ca.key -out ca.crt 2>/dev/null
openssl req -newkey rsa:2048 -nodes -subj "/CN=*.$DOMAIN" -keyout "$d/privkey.pem" -out leaf.csr 2>/dev/null
printf 'subjectAltName=DNS:*.%s,DNS:%s\n' "$DOMAIN" "$DOMAIN" >ext
openssl x509 -req -in leaf.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 30 \
-extfile ext -out leaf.crt 2>/dev/null
cat leaf.crt ca.crt >"$d/fullchain.pem"
chown root:ssl-cert "$d/privkey.pem" "$d/fullchain.pem" 2>/dev/null || chgrp ssl-cert "$d/privkey.pem"
chmod 640 "$d/privkey.pem"
cp ca.crt /usr/local/share/ca-certificates/emailwiz-test.crt && update-ca-certificates >/dev/null
cd /
}
# Reproduce a host installed by upstream emailwiz (config captured from a real install).
setup_prod_state() {
# Copy as root:root and keep existing directory metadata (/, /etc, ...).
(cd /src/tests/fixtures/upstream-install && tar -cf - .) | tar -C / --no-same-owner --no-overwrite-dir -xf -
mkdir -p /etc/postfix/dkim/$DOMAIN
opendkim-genkey -b 2048 -D /etc/postfix/dkim/$DOMAIN -d $DOMAIN -s mail
chgrp -R opendkim /etc/postfix/dkim/$DOMAIN; chmod -R g+r /etc/postfix/dkim/$DOMAIN
sievec /var/lib/dovecot/sieve/default.sieve
# A pre-existing mailbox that must survive untouched.
install -d -o alice -g alice -m 700 /home/alice/Mail /home/alice/Mail/Inbox \
/home/alice/Mail/Inbox/cur /home/alice/Mail/Inbox/new /home/alice/Mail/Inbox/tmp
printf 'From: a@example.org\nSubject: old mail\n\nkeep me\n' >/home/alice/Mail/Inbox/cur/1700000000.M1P1.mx1:2,S
chown alice:alice /home/alice/Mail/Inbox/cur/*
postalias /etc/aliases
systemctl daemon-reload
for s in opendkim spamd dovecot postfix fail2ban; do systemctl restart $s; done
sleep 2
}
conf_for_prod() {
mkdir -p /etc/emailwiz
cat >/etc/emailwiz/emailwiz.conf <<EOF
DOMAIN='$DOMAIN'
MAIL_HOSTNAME='$HOST'
ROOT_ALIAS='alice'
TLS_MODE='external'
TLS_CERT='/etc/ssl/$DOMAIN/fullchain.pem'
TLS_KEY='/etc/ssl/$DOMAIN/privkey.pem'
EOF
chmod 644 /etc/emailwiz/emailwiz.conf
}
etc_sum() { find /etc /var/lib/dovecot -xdev -type f -not -path '*/ssl/certs/*' -exec sha256sum {} + 2>/dev/null | sort | sha256sum; }
smtp_tests() {
section "SMTP/IMAP behaviour"
echo "alice:$TESTPW" | chpasswd
# Non-loopback address: clients are outside mynetworks, like real ones.
IP=$(ip -4 -o addr show eth0 | awk '{sub("/.*", "", $4); print $4}')
check "587: authenticated submission accepted" \
swaks -s "$IP" -p 587 -tls -a PLAIN -au alice -ap "$TESTPW" -f alice@$DOMAIN -t postmaster@$DOMAIN --h-Subject swaks587
check "465: authenticated submission accepted" \
swaks -s "$IP" -p 465 -tlsc -a PLAIN -au alice -ap "$TESTPW" -f alice+tag@$DOMAIN -t postmaster@$DOMAIN --h-Subject swaks465
check_not "587: wrong password rejected" \
swaks -s "$IP" -p 587 -tls -a PLAIN -au alice -ap wrong -f alice@$DOMAIN -t postmaster@$DOMAIN
check_not "587: sender login mismatch rejected (alice as postmaster@)" \
swaks -s "$IP" -p 587 -tls -a PLAIN -au alice -ap "$TESTPW" -f postmaster@$DOMAIN -t alice@$DOMAIN
check_not "587: unauthenticated mail rejected" \
swaks -s "$IP" -p 587 -tls -f someone@gmail.com -t alice@$DOMAIN
check_not "465: unauthenticated mail to local user rejected (spam-filter bypass closed)" \
swaks -s "$IP" -p 465 -tlsc -f someone@gmail.com -t alice@$DOMAIN
check_not "25: AUTH not offered after STARTTLS" sh -c \
"swaks -s $IP -p 25 -tls -q ehlo 2>&1 | grep -q '250-AUTH'"
check "IMAPS login works" sh -c \
"printf 'a LOGIN alice $TESTPW\r\nb LOGOUT\r\n' | timeout 10 openssl s_client -quiet -connect 127.0.0.1:993 2>/dev/null | grep -q '^a OK'"
# Dovecot treats same-IP connections as secure, so cleartext refusal on 143
# cannot be exercised from inside the container; assert the settings instead
# (verified from the host: LOGINDISABLED / PRIVACYREQUIRED).
check "dovecot: ssl=required, auth_allow_cleartext=no" sh -c \
'[ "$(doveconf -h ssl)" = required ] && [ "$(doveconf -h auth_allow_cleartext)" = no ]'
sleep 3
check "submitted mail delivered to Maildir" sh -c "grep -rl 'Subject: swaks587' /home/alice/Mail/Inbox/new/"
check "DKIM signature on submitted mail verifies" python3 - <<'EOF'
import dkim, glob, subprocess, base64
pub = subprocess.run(["sh","-c","openssl rsa -in /etc/postfix/dkim/example.org/mail.private -pubout -outform DER 2>/dev/null | base64 -w0"],capture_output=True,text=True).stdout
def dns(name, timeout=5):
assert name == b"mail._domainkey.example.org.", name
return ("v=DKIM1; k=rsa; p=" + pub).encode()
f = [p for p in glob.glob("/home/alice/Mail/Inbox/new/*") if b"Subject: swaks587" in open(p,"rb").read()][0]
raise SystemExit(0 if dkim.verify(open(f,"rb").read(), dnsfunc=dns) else 1)
EOF
check "spamd reload succeeds" systemctl reload spamd
}
scenario_migration() {
section "setup: reproduce an upstream emailwiz install"
install_tool; make_cert; setup_prod_state; conf_for_prod
for s in postfix dovecot opendkim spamd; do check "baseline $s active" systemctl is-active -q $s; done
section "plan is read-only"
before=$(etc_sum)
check "plan exits 10 with pending changes" sh -c 'emailwiz plan --detailed-exitcode >/tmp/plan.txt 2>&1; [ $? -eq 10 ]'
check "plan left /etc unchanged" test "$before" = "$(etc_sum)"
check "plan replaces upstream emailwiz.local" grep -q 'changed .*/etc/fail2ban/jail.d/emailwiz.local' /tmp/plan.txt
check_not "plan output has no secrets" grep -q 'PRIVATE KEY' /tmp/plan.txt
section "negative: bad certificate path changes nothing"
cp /etc/emailwiz/emailwiz.conf /tmp/conf.bak
echo "TLS_CERT='/nonexistent.pem'" >>/etc/emailwiz/emailwiz.conf
before=$(etc_sum)
check_not "apply refuses with missing cert" emailwiz apply --yes
check "nothing changed after refused apply" test "$before" = "$(etc_sum)"
cp /tmp/conf.bak /etc/emailwiz/emailwiz.conf
section "negative: non-interactive apply needs --yes"
check_not "apply without --yes and no tty refuses" sh -c 'emailwiz apply </dev/null'
section "apply (migration)"
keysum=$(sha256sum /etc/postfix/dkim/$DOMAIN/mail.private)
sha256sum /home/alice/Mail/Inbox/cur/* >/tmp/mailsum
check "apply succeeds" emailwiz apply --yes
check "existing DKIM key preserved" test "$keysum" = "$(sha256sum /etc/postfix/dkim/$DOMAIN/mail.private)"
check_not "upstream [sieve] jail gone" grep -q '^\[sieve\]' /etc/fail2ban/jail.d/emailwiz.local
check "opendkim override retired" test ! -e /etc/systemd/system/opendkim.service.d/override.conf
check "header_checks removed from main.cf" sh -c '[ -z "$(postconf -h header_checks)" ]'
check "existing mailbox untouched" sh -c '[ "$(cat /tmp/mailsum)" = "$(sha256sum /home/alice/Mail/Inbox/cur/*)" ]'
check "backup created and readable" sh -c 'ls /var/backups/emailwiz/*-apply/config.tar.gz && tar -tzf /var/backups/emailwiz/*-apply/config.tar.gz >/dev/null'
check "backup dir mode 0700" sh -c '[ "$(stat -c %a /var/backups/emailwiz)" = 700 ]'
section "idempotence"
check "second plan: no changes (exit 0)" emailwiz plan --detailed-exitcode
check "second apply: nothing to do" sh -c 'emailwiz apply --yes 2>&1 | grep -q "nothing to do"'
check "no duplicate master.cf services" sh -c '[ "$(grep -c "^submission " /etc/postfix/master.cf)" = 1 ] && [ "$(grep -c "^spamassassin " /etc/postfix/master.cf)" = 1 ]'
section "validate"
check "validate --no-dns --deliver-test passes" emailwiz validate --no-dns --deliver-test
smtp_tests
section "regression: PrivateTmp deleted under a running service"
# Seen on a real host: a manual rm of /tmp/systemd-private-* made every
# namespaced reload fail with 226/NAMESPACE, and apply 1.0.0 ignored it.
rm -rf /tmp/systemd-private-*-dovecot.service-*
check_not "precondition: dovecot reload now fails" systemctl reload dovecot
echo "JUNK_AUTOEXPUNGE='60d'" >>/etc/emailwiz/emailwiz.conf
check "apply succeeds by restarting dovecot" sh -c 'emailwiz apply --yes 2>&1 | tee /tmp/a.log; grep -q "reload of dovecot failed; restarting" /tmp/a.log'
check "dovecot runs the new config" sh -c 'doveadm config -n 2>/dev/null | grep -q "autoexpunge = 60d" || doveconf -n | grep -q "autoexpunge = 60d"; systemctl is-active -q dovecot && [ "$(systemctl show dovecot -p ExecMainStartTimestampMonotonic --value)" -gt 0 ]'
section "negative: failed service action restores previous config"
cp /etc/dovecot/dovecot.conf /tmp/dovecot.before
systemctl mask dovecot >/dev/null 2>&1 # reload and restart both fail now
echo "JUNK_AUTOEXPUNGE='90d'" >>/etc/emailwiz/emailwiz.conf
check "apply exits 3 when dovecot cannot be reloaded/restarted" sh -c 'emailwiz apply --yes; [ $? -eq 3 ]'
check "dovecot.conf restored" cmp /tmp/dovecot.before /etc/dovecot/dovecot.conf
systemctl unmask dovecot >/dev/null 2>&1
cp /tmp/conf.bak /etc/emailwiz/emailwiz.conf
check "apply converges after unmask" emailwiz apply --yes
check "plan clean" emailwiz plan --detailed-exitcode
section "rollback"
bk=$(basename "$(ls -d /var/backups/emailwiz/*-apply | head -1)")
check "rollback succeeds" emailwiz rollback "$bk" --yes
check "rollback restored upstream emailwiz.local" grep -q '^\[sieve\]' /etc/fail2ban/jail.d/emailwiz.local
check "backup archives the DKIM key once" sh -c "[ \$(tar -tzf /var/backups/emailwiz/$bk/config.tar.gz | grep -c 'mail.private\$') = 1 ]"
check "rollback restored original main.cf" cmp /src/tests/fixtures/upstream-install/etc/postfix/main.cf /etc/postfix/main.cf
check "rollback removed files created by apply" test ! -e /etc/postfix/emailwiz_outbound_header_checks
for s in postfix dovecot opendkim; do check "after rollback $s active" systemctl is-active -q $s; done
check "re-apply after rollback" emailwiz apply --yes
check "plan clean after re-apply" emailwiz plan --detailed-exitcode
section "one-time PAM migration"
check "migrate-upstream --fix-pam" emailwiz migrate-upstream --fix-pam
check_not "nullok line removed from pam.d/dovecot" grep -q '^auth *required *pam_unix.so nullok' /etc/pam.d/dovecot
check "IMAP login still works after PAM fix" sh -c \
"printf 'a LOGIN alice $TESTPW\r\nb LOGOUT\r\n' | timeout 10 openssl s_client -quiet -connect 127.0.0.1:993 2>/dev/null | grep -q '^a OK'"
check "migrate-upstream --fix-pam is idempotent" sh -c 'emailwiz migrate-upstream --fix-pam 2>&1 | grep -q "no emailwiz PAM lines"'
}
scenario_clean() {
section "clean install (package defaults, no emailwiz)"
install_tool; make_cert
echo "root: alice" >>/etc/aliases
check "init writes config" emailwiz init $DOMAIN
sed -i "s|^TLS_CERT=.*|TLS_CERT='/etc/ssl/$DOMAIN/fullchain.pem'|; s|^TLS_KEY=.*|TLS_KEY='/etc/ssl/$DOMAIN/privkey.pem'|; s|^ROOT_ALIAS=.*|ROOT_ALIAS='alice'|" /etc/emailwiz/emailwiz.conf
check "install-packages is a no-op when installed" sh -c 'emailwiz install-packages 2>&1 | grep -q "all required packages"'
check "plan shows DKIM key note" sh -c 'emailwiz plan --no-diff 2>&1 | grep -q "will generate a new"'
check "apply on clean system" emailwiz apply --yes
check "DKIM key generated 0640 root:opendkim" sh -c '[ "$(stat -c "%a %U %G" /etc/postfix/dkim/example.org/mail.private)" = "640 root opendkim" ]'
check "plan clean after apply" emailwiz plan --detailed-exitcode
check "dns prints DKIM record" sh -c 'emailwiz dns | grep -q "v=DKIM1; k=rsa; p=MII"'
check "dns omits AAAA without global IPv6" sh -c 'emailwiz dns | grep -q "no AAAA"'
check "validate --no-dns --deliver-test passes" emailwiz validate --no-dns --deliver-test
check "timers active" systemctl is-active -q emailwiz-certcheck.timer emailwiz-backup.timer
check "cert-check passes (30-day cert > 21 day threshold)" emailwiz cert-check
check "scheduled backup works" emailwiz backup --scheduled
smtp_tests
check "unsupported OS refused" sh -c 'sed -i s/VERSION_ID=\"13\"/VERSION_ID=\"12\"/ /etc/os-release; emailwiz plan; [ $? -eq 4 ]'
}
# shellcheck disable=SC2086 # $SETUP_ENV is a list of VAR=value words for env(1)
SETUP_ENV="DOMAIN=$DOMAIN ROOT_ALIAS=alice SETUP_UFW=yes SETUP_USER=bob"
scenario_setup() {
section "make install (from the read-only source tree)"
check "make install" make -C /src install
check "installed tool runs" sh -c 'emailwiz version | grep -q "^emailwiz 2\."'
check "Makefile shipped with the install" test -f /usr/local/lib/emailwiz/Makefile
make_cert
ufw allow 22/tcp >/dev/null && ufw --force enable >/dev/null
section "setup refuses to prompt without a terminal"
check "setup </dev/null exits 2" sh -c 'emailwiz setup </dev/null; [ $? -eq 2 ]'
check "nothing written" test ! -e /etc/emailwiz/emailwiz.conf
section "setup --non-interactive (external certificate)"
# shellcheck disable=SC2086
check "setup succeeds" env $SETUP_ENV TLS_MODE=external \
TLS_CERT=/etc/ssl/$DOMAIN/fullchain.pem TLS_KEY=/etc/ssl/$DOMAIN/privkey.pem \
emailwiz setup --non-interactive
check "config written 0644 root" sh -c '[ "$(stat -c "%a %U" /etc/emailwiz/emailwiz.conf)" = "644 root" ]'
for p in 25 465 587 993 995; do
check "ufw allows $p/tcp" sh -c "ufw status | grep -Eq '^$p/tcp +ALLOW'"
done
check_not "ufw: no udp rules added" sh -c "ufw status | grep -q '/udp'"
check_not "ufw: port 80 not opened (external TLS)" sh -c "ufw status | grep -Eq '^80/tcp'"
check "ufw: ssh rule untouched" sh -c "ufw status | grep -Eq '^22/tcp +ALLOW'"
check "account bob created in group mail" sh -c 'id -nG bob | grep -qw mail'
check "DNS file saved 0600 with DKIM" sh -c '[ "$(stat -c %a /root/emailwiz-dns.txt)" = 600 ] && grep -q "v=DKIM1" /root/emailwiz-dns.txt'
check "root aliased to alice" sh -c 'postalias -q root /etc/aliases | grep -qx alice'
check "plan clean after setup" emailwiz plan --detailed-exitcode
echo "bob:$TESTPW" | chpasswd
check "bob can submit on 587" swaks -s 127.0.0.1 -p 587 -tls -a PLAIN -au bob -ap "$TESTPW" \
-f bob@$DOMAIN -t alice@$DOMAIN --h-Subject setup-test
section "setup is rerunnable"
# shellcheck disable=SC2086
check "second setup succeeds" env $SETUP_ENV TLS_MODE=external emailwiz setup --non-interactive
check "second setup: apply had nothing to do" sh -c "env $SETUP_ENV TLS_MODE=external emailwiz setup --non-interactive 2>&1 | grep -q 'nothing to do'"
check "no duplicate ufw rules" sh -c '[ "$(ufw status | grep -v "(v6)" | grep -c "^25/tcp ")" = 1 ]'
section "setup protects an existing different config"
cp /etc/emailwiz/emailwiz.conf /tmp/conf.before
check "different DOMAIN refused without SETUP_OVERWRITE_CONFIG" sh -c \
'env DOMAIN=other.example emailwiz setup --non-interactive; [ $? -eq 2 ]'
check "config unchanged" cmp /tmp/conf.before /etc/emailwiz/emailwiz.conf
section "make lint inside Debian 13"
check "make lint" make -C /src lint
}
# Fake certbot: records its arguments; a real (non --dry-run) certonly
# installs the test certificate as the Let's Encrypt live files.
install_certbot_stub() {
cat >/usr/local/bin/certbot <<'STUB'
#!/bin/sh
echo "$*" >>/tmp/certbot.log
case " $* " in *" --dry-run "*) exit 0 ;; esac
[ "$1" = certonly ] || exit 0
live=/etc/letsencrypt/live/mail.example.org
mkdir -p "$live"
cp /etc/ssl/example.org/fullchain.pem "$live/fullchain.pem"
cp /etc/ssl/example.org/privkey.pem "$live/privkey.pem"
chmod 600 "$live/privkey.pem"
STUB
chmod 755 /usr/local/bin/certbot
}
scenario_certbot() {
install_tool; make_cert; install_certbot_stub
systemctl start nginx
section "setup with TLS_MODE=certbot while nginx owns port 80"
check "setup succeeds" env DOMAIN=$DOMAIN ROOT_ALIAS=alice SETUP_UFW=no TLS_MODE=certbot \
emailwiz setup --non-interactive
check "certbot used the nginx authenticator" grep -q 'certonly --nginx' /tmp/certbot.log
check "dry run before issuance" sh -c 'grep -n -- --dry-run /tmp/certbot.log | head -1 | grep -q "^1:"'
check "real contact address, not unsafe registration" grep -q -- '-m postmaster@example.org' /tmp/certbot.log
check_not "no --register-unsafely-without-email" grep -q unsafely /tmp/certbot.log
check "Postfix uses the certbot certificate" sh -c '[ "$(postconf -h smtpd_tls_cert_file)" = /etc/letsencrypt/live/mail.example.org/fullchain.pem ]'
check "deploy hook installed" test -x /etc/letsencrypt/renewal-hooks/deploy/emailwiz-reload
check "deploy hook ignores other domains" env RENEWED_DOMAINS=www.example.org /etc/letsencrypt/renewal-hooks/deploy/emailwiz-reload
check "deploy hook reloads for the mail host" env RENEWED_DOMAINS=mail.example.org /etc/letsencrypt/renewal-hooks/deploy/emailwiz-reload
check "validate (certbot timer, hook, renew dry run)" emailwiz validate --no-dns --renew-test
check "nginx config untouched by emailwiz" nginx -t
section "authenticator selection"
systemctl stop nginx; rm -rf /etc/letsencrypt/live/mail.example.org; : >/tmp/certbot.log
check "nothing on :80 -> --standalone" sh -c 'emailwiz tls-obtain && grep -q "certonly --standalone" /tmp/certbot.log'
check "existing certificate is reused" sh -c ': >/tmp/certbot.log; emailwiz tls-obtain && [ ! -s /tmp/certbot.log ]'
rm -rf /etc/letsencrypt/live/mail.example.org
nc -l -p 80 -k >/dev/null 2>&1 &
ncpid=$!; sleep 1
check "unknown program on :80 -> refuse" sh -c 'emailwiz tls-obtain 2>&1 | grep -q "port 80 is used by nc"; [ ! -d /etc/letsencrypt/live/mail.example.org ]'
kill $ncpid 2>/dev/null
}
case $SCENARIO in
migration) scenario_migration ;;
clean) scenario_clean ;;
setup) scenario_setup ;;
certbot) scenario_certbot ;;
*) echo "unknown scenario"; exit 2 ;;
esac
echo
echo "[$SCENARIO] $PASS passed, $FAILS failed"
[ $FAILS -eq 0 ]
Executable
+50
View File
@@ -0,0 +1,50 @@
#!/bin/sh
# Run the emailwiz test suite in disposable Debian 13 systemd containers.
# usage: tests/run.sh [migration|clean|setup|certbot|all] (needs docker; builds the image)
# SPDX-License-Identifier: GPL-3.0-or-later
set -eu
cd "$(dirname "$0")/.."
ROOT=$(pwd)
IMG=emailwiz-test:trixie
which=${1:-all}
echo "== static checks"
shellcheck -x -P lib emailwiz install.sh lib/*.sh templates/certbot-deploy-hook tests/*.sh
for f in emailwiz lib/*.sh; do sh -n "$f"; done
echo "shellcheck + sh -n: OK"
docker build -q -t "$IMG" -f tests/Containerfile tests >/dev/null
run_scenario() {
name=$1
cid=$(docker run -d --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw \
--hostname mx1 --tmpfs /run --tmpfs /run/lock \
-v "$ROOT:/src:ro" "$IMG")
trap 'docker rm -f "$cid" >/dev/null 2>&1 || :' EXIT
# wait for systemd
i=0
until docker exec "$cid" systemctl is-system-running 2>/dev/null | grep -Eq 'running|degraded'; do
i=$((i + 1)); [ $i -gt 60 ] && { echo "systemd did not boot"; exit 1; }; sleep 1
done
rc=0
docker exec "$cid" sh /src/tests/in-container.sh "$name" || rc=$?
docker rm -f "$cid" >/dev/null
trap - EXIT
return $rc
}
fails=0
case $which in
migration | all) run_scenario migration || fails=$((fails + 1)) ;;
esac
case $which in
clean | all) run_scenario clean || fails=$((fails + 1)) ;;
esac
case $which in
setup | all) run_scenario setup || fails=$((fails + 1)) ;;
esac
case $which in
certbot | all) run_scenario certbot || fails=$((fails + 1)) ;;
esac
echo
[ $fails -eq 0 ] && echo "ALL SCENARIOS PASSED" || { echo "$fails SCENARIO(S) FAILED"; exit 1; }