2017-09-13 16:14:14 +02:00
commit 54f6e50bb5
354 changed files with 43829 additions and 9889 deletions

15
.gitignore vendored
View File

@ -3,5 +3,18 @@ data/conf/sogo/sieve.creds
data/conf/dovecot/dovecot-master.passwd
mailcow.conf
mailcow.conf_backup
data/conf/nginx/listen.active
data/conf/nginx/listen*active
data/conf/nginx/server_name.active
data/conf/postfix/sql
data/conf/dovecot/sql
data/web/inc/vars.local.inc.php
data/assets/ssl/*
.vscode/*
data/web/.well-known/acme-challenge
data/conf/rspamd/local.d/*
data/conf/rspamd/override.d/*
!data/conf/nginx/dynmaps.conf
!data/conf/nginx/site.conf
data/conf/nginx/*.conf
data/conf/dovecot/extra.conf
data/conf/rspamd/custom/*

16
.travis.yml 100644
View File

@ -0,0 +1,16 @@
sudo: required
services:
- docker
script:
- echo 'Europe/Berlin' | MAILCOW_HOSTNAME=build.mailcow ./generate_config.sh
- docker-compose pull --ignore-pull-failures --parallel
- docker-compose build
- docker login --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD
- docker-compose push
branches:
only:
- master
env:
global:
- secure: MpxpTwD7f0CNEVLitSpVmocK7O9r+BwFE1deEHK4AlQo/oc9cOlhGe1EL3mx9zbglPmjlDg/8kMUGv6vSirIabfBo9Szjps76bHckFr9lr2Ykkg0e29oC8pgPpSXD1eY/1ZIN/FvIkxpUFLETo1okS/j9q/A0DCGFmti0n3EoMORsgRz9CpNAiEh0zpSd6+euPAGHuczuCrDuO84my9bIOCjA/+aPunHNeXiuM8yIM2SxCSyGtIKT0+jvquIvLF58VxivysXBlRfhDn8fhB09nXA2Ru/derYQACfcmNSn9Pd4bDpebPJW5B9H/XA8xjb58uKinUlncbAMB/QnxoT75j9YRWJZRSQ+34XNYP6ZgK9soZ2TC6djQyEKTUu45Kp/1s+poSn42m9jytJJTmmK0KxsZTRcC8JD5nrjIMZWPUNNTwC5L4+I7ZRWg2WooK3LNyq1Ng8Hn6W77wSgsvAJw2HD3Lx58AprGUhHuBeaIZRuSN9aKwZrl9vKQJLqPnOp/nF2EC6kot5HYYtcotGtETXPUDih21gWD5ZM2BqVqYfQQnJnNMgeYmMdj6QQuTFqhuNJf7hXRIRkTnD3j1gDOLKQZazW0+N2JE8XWDFwi6fKScDsxT85lJti9HmzHa7+k4RVHmUYuDgRoPuzUgjWHvPsiz3/Z8WQ9JYpH84S8w=
- secure: fWzZisT6nGDNL4lf6tXB07eFG2drgBakHxzdF/NFVvzuP861RFR6omuL+ED0PgXrEHDJBxaBLv52je8irmUXrAH1CNr7T8DWiZo/h5h609Uzr+38T1NnIu4krL0Wo6/CDwlLKnzqTq9yBIZLQSHVJmo8AOpo1JPIi2ajodqj9ZfmAxDQTQl+G6zvQjtqIkYHsHY7A44Rto0f14ykn7w2S82Jn6Ry89VNI5V1WEO3sMpM/XekNP/HokNcRIuntL/0+kuLvTJ5akGoTjBQxSnSW95opzPeGky74HRU2obExJYqKvF0VfVJRNAqejwjIiFIbbjqV0Sk5391kFuhuBErQQDM1bOHGdxZ41HsJH29qNWIl7C33Yl10qERoqecgsJ1N/bS2ZEmWqm/zQh5GClCXPvYmzEqMYsMGM3vjbKdjDlc1Wh2w/eFclsXN9LSXh1mc35rtj46frcT6e5Kof87AIfC9hTgDvk9kAsyjaHMkSHSZthbZXCIcsD8qriNm5UqfFBYD79mPIP1S2YMQ2jscCsjHOZgYVrcm0kzDF21J1w6H0Lo7d1jw37LYlegBdtLQ9gYgqY2D5m+nxWuVoD5FZmpR+5JGtK+ootyLFF8aiFoHXd4op1JCxRLjgkmnZKXzw3kTQSpE7oa7CgzchtQmK2nqcqla1b5Qk7ilVcjooo=

46
CODE_OF_CONDUCT.md 100644
View File

@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, documentation edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at info@servercow.de. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

9
CONTRIBUTING.md 100644
View File

@ -0,0 +1,9 @@
When a problem occurs, then always for a reason! What you want to do in such a case is:
1. Read your logs; follow them to see what the reason for your problem is.
2. Follow the leads given to you in your logfiles and start investigating.
3. Restarting the troubled service or the whole stack to see if the problem persists.
4. Read the [documentation](https://mailcow.github.io/mailcow-dockerized-docs/) of the troubled service and search it's bugtracker for your problem.
5. Search our [issues](https://github.com/mailcow/mailcow-dockerized/issues) for your problem.
6. [Create an issue](https://github.com/mailcow/mailcow-dockerized/issues) over at our GitHub repository if you think your problem might be a bug or a missing feature you badly need. But please make sure, that you include **all the logs** and a full description to your problem.
8. Connect to IRC ([chat.freenode.net](https://webchat.freenode.net/)) and join our IRC channel #mailcow.

674
LICENSE 100644
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://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 <http://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:
{project} Copyright (C) {year} {fullname}
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
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -2,4 +2,9 @@
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JWBSYHF4SMC68)
Please see the official documentation for instructions => [mailcow.email/dockerized](https://mailcow.email/dockerized)
**mailcow Bitcoin donations:** 1E5rgzgA1sS3QH7r1ToWxRC3GEavfsGMrx
Please see [the official documentation](https://mailcow.github.io/mailcow-dockerized-docs/) for instructions.
**Important**: mailcow makes use of various open-source software. Please assure you agree with their license before using mailcow.
Any part of mailcow itself is released under **GNU General Public License, Version 3**.

View File

@ -0,0 +1,16 @@
FROM alpine:3.6
LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
RUN apk add --update --no-cache \
bash \
acme-client \
curl \
openssl \
bind-tools \
jq \
mariadb-client
COPY docker-entrypoint.sh /srv/docker-entrypoint.sh
ENTRYPOINT ["/srv/docker-entrypoint.sh"]

View File

@ -0,0 +1,262 @@
#!/bin/bash
ACME_BASE=/var/lib/acme
SSL_EXAMPLE=/var/lib/ssl-example
mkdir -p ${ACME_BASE}/acme/private
restart_containers(){
for container in $*; do
echo "Restarting ${container}..."
curl -X POST \
--unix-socket /var/run/docker.sock \
"http/containers/${container}/restart"
done
}
verify_hash_match(){
CERT_HASH=$(openssl x509 -noout -modulus -in "${1}" | openssl md5)
KEY_HASH=$(openssl rsa -noout -modulus -in "${2}" | openssl md5)
if [[ ${CERT_HASH} != ${KEY_HASH} ]]; then
echo "Certificate and key hashes do not match!"
return 1
else
echo "Verified hashes."
return 0
fi
}
get_ipv4(){
local IPV4=
local IPV4_SRCS=
local TRY=
IPV4_SRCS[0]="api.ipify.org"
IPV4_SRCS[1]="ifconfig.co"
IPV4_SRCS[2]="icanhazip.com"
IPV4_SRCS[3]="v4.ident.me"
IPV4_SRCS[4]="ipecho.net/plain"
IPV4_SRCS[5]="mailcow.email/ip.php"
until [[ ! -z ${IPV4} ]] || [[ ${TRY} -ge 100 ]]; do
IPV4=$(curl --connect-timeout 3 -m 10 -L4s ${IPV4_SRCS[$RANDOM % ${#IPV4_SRCS[@]} ]} | grep -E "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
[[ ! -z ${TRY} ]] && sleep 1
TRY=$((TRY+1))
done
echo ${IPV4}
}
[[ ! -f ${ACME_BASE}/dhparams.pem ]] && cp ${SSL_EXAMPLE}/dhparams.pem ${ACME_BASE}/dhparams.pem
if [[ -f ${ACME_BASE}/cert.pem ]] && [[ -f ${ACME_BASE}/key.pem ]]; then
ISSUER=$(openssl x509 -in ${ACME_BASE}/cert.pem -noout -issuer)
if [[ ${ISSUER} != *"Let's Encrypt"* && ${ISSUER} != *"mailcow"* ]]; then
echo "Found certificate with issuer other than mailcow snake-oil CA and Let's Encrypt, skipping ACME client..."
exit 0
else
declare -a SAN_ARRAY_NOW
SAN_NAMES=$(openssl x509 -noout -text -in ${ACME_BASE}/cert.pem | awk '/X509v3 Subject Alternative Name/ {getline;gsub(/ /, "", $0); print}' | tr -d "DNS:")
if [[ ! -z ${SAN_NAMES} ]]; then
IFS=',' read -a SAN_ARRAY_NOW <<< ${SAN_NAMES}
echo "Found Let's Encrypt or mailcow snake-oil CA issued certificate with SANs: ${SAN_ARRAY_NOW[*]}"
fi
fi
else
if [[ -f ${ACME_BASE}/acme/fullchain.pem ]] && [[ -f ${ACME_BASE}/acme/private/privkey.pem ]]; then
if verify_hash_match ${ACME_BASE}/acme/fullchain.pem ${ACME_BASE}/acme/private/privkey.pem; then
echo "Restoring previous acme certificate and restarting script..."
cp ${ACME_BASE}/acme/fullchain.pem ${ACME_BASE}/cert.pem
cp ${ACME_BASE}/acme/private/privkey.pem ${ACME_BASE}/key.pem
exec env TRIGGER_RESTART=1 $(readlink -f "$0")
fi
ISSUER="mailcow"
else
echo "Restoring mailcow snake-oil certificates and restarting script..."
cp ${SSL_EXAMPLE}/cert.pem ${ACME_BASE}/cert.pem
cp ${SSL_EXAMPLE}/key.pem ${ACME_BASE}/key.pem
exec env TRIGGER_RESTART=1 $(readlink -f "$0")
fi
fi
while true; do
if [[ "${SKIP_LETS_ENCRYPT}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
echo "SKIP_LETS_ENCRYPT=y, skipping Let's Encrypt..."
exit 0
fi
if [[ "${SKIP_IP_CHECK}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
SKIP_IP_CHECK=y
fi
unset SQL_DOMAIN_ARR
unset VALIDATED_CONFIG_DOMAINS
unset ADDITIONAL_VALIDATED_SAN
declare -a SQL_DOMAIN_ARR
declare -a VALIDATED_CONFIG_DOMAINS
declare -a ADDITIONAL_VALIDATED_SAN
IFS=',' read -r -a ADDITIONAL_SAN_ARR <<< "${ADDITIONAL_SAN}"
IPV4=$(get_ipv4)
# Container ids may have changed
CONTAINERS_RESTART=($(curl --silent --unix-socket /var/run/docker.sock http/containers/json | jq -rc 'map(select(.Names[] | contains ("nginx-mailcow") or contains ("postfix-mailcow") or contains ("dovecot-mailcow"))) | .[] .Id' | tr "\n" " "))
while read domain; do
SQL_DOMAIN_ARR+=("${domain}")
done < <(mysql -h mysql-mailcow -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM domain WHERE backupmx=0" -Bs)
while read alias_domain; do
SQL_DOMAIN_ARR+=("${alias_domain}")
done < <(mysql -h mysql-mailcow -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT alias_domain FROM alias_domain" -Bs)
for SQL_DOMAIN in "${SQL_DOMAIN_ARR[@]}"; do
A_CONFIG=$(dig A autoconfig.${SQL_DOMAIN} +short | tail -n 1)
if [[ ! -z ${A_CONFIG} ]]; then
echo "Found A record for autoconfig.${SQL_DOMAIN}: ${A_CONFIG}"
if [[ ${IPV4:-ERR} == ${A_CONFIG} ]] || [[ ${SKIP_IP_CHECK} == "y" ]]; then
echo "Confirmed A record autoconfig.${SQL_DOMAIN}"
VALIDATED_CONFIG_DOMAINS+=("autoconfig.${SQL_DOMAIN}")
else
echo "Cannot match your IP ${IPV4} against hostname autoconfig.${SQL_DOMAIN} (${A_CONFIG})"
fi
else
echo "No A record for autoconfig.${SQL_DOMAIN} found"
fi
A_DISCOVER=$(dig A autodiscover.${SQL_DOMAIN} +short | tail -n 1)
if [[ ! -z ${A_DISCOVER} ]]; then
echo "Found A record for autodiscover.${SQL_DOMAIN}: ${A_DISCOVER}"
if [[ ${IPV4:-ERR} == ${A_DISCOVER} ]] || [[ ${SKIP_IP_CHECK} == "y" ]]; then
echo "Confirmed A record autodiscover.${SQL_DOMAIN}"
VALIDATED_CONFIG_DOMAINS+=("autodiscover.${SQL_DOMAIN}")
else
echo "Cannot match your IP ${IPV4} against hostname autodiscover.${SQL_DOMAIN} (${A_DISCOVER})"
fi
else
echo "No A record for autodiscover.${SQL_DOMAIN} found"
fi
done
A_MAILCOW_HOSTNAME=$(dig A ${MAILCOW_HOSTNAME} +short | tail -n 1)
if [[ ! -z ${A_MAILCOW_HOSTNAME} ]]; then
echo "Found A record for ${MAILCOW_HOSTNAME}: ${A_MAILCOW_HOSTNAME}"
if [[ ${IPV4:-ERR} == ${A_MAILCOW_HOSTNAME} ]] || [[ ${SKIP_IP_CHECK} == "y" ]]; then
echo "Confirmed A record ${MAILCOW_HOSTNAME}"
VALIDATED_MAILCOW_HOSTNAME=${MAILCOW_HOSTNAME}
else
echo "Cannot match your IP ${IPV4} against hostname ${MAILCOW_HOSTNAME} (${A_MAILCOW_HOSTNAME}) "
fi
else
echo "No A record for ${MAILCOW_HOSTNAME} found"
fi
for SAN in "${ADDITIONAL_SAN_ARR[@]}"; do
if [[ ${SAN} == ${MAILCOW_HOSTNAME} ]]; then
continue
fi
A_SAN=$(dig A ${SAN} +short | tail -n 1)
if [[ ! -z ${A_SAN} ]]; then
echo "Found A record for ${SAN}: ${A_SAN}"
if [[ ${IPV4:-ERR} == ${A_SAN} ]] || [[ ${SKIP_IP_CHECK} == "y" ]]; then
echo "Confirmed A record ${SAN}"
ADDITIONAL_VALIDATED_SAN+=("${SAN}")
else
echo "Cannot match your IP against hostname ${SAN}"
fi
else
echo "No A record for ${SAN} found"
fi
done
# Unique elements
ALL_VALIDATED=(${VALIDATED_MAILCOW_HOSTNAME} $(echo ${VALIDATED_CONFIG_DOMAINS[*]} ${ADDITIONAL_VALIDATED_SAN[*]} | xargs -n1 | sort -u | xargs))
if [[ -z ${ALL_VALIDATED[*]} ]]; then
echo "Cannot validate hostnames, skipping Let's Encrypt..."
exit 0
fi
ORPHANED_SAN=($(echo ${SAN_ARRAY_NOW[*]} ${ALL_VALIDATED[*]} | tr ' ' '\n' | sort | uniq -u ))
if [[ ! -z ${ORPHANED_SAN[*]} ]] && [[ ${ISSUER} != *"mailcow"* ]]; then
DATE=$(date +%Y-%m-%d_%H_%M_%S)
echo "Found orphaned SAN ${ORPHANED_SAN[*]} in certificate, moving old files to ${ACME_BASE}/acme/private/${DATE}.bak/, keeping key file..."
mkdir -p ${ACME_BASE}/acme/private/${DATE}.bak/
[[ -f ${ACME_BASE}/acme/private/account.key ]] && mv ${ACME_BASE}/acme/private/account.key ${ACME_BASE}/acme/private/${DATE}.bak/
[[ -f ${ACME_BASE}/acme/fullchain.pem ]] && mv ${ACME_BASE}/acme/fullchain.pem ${ACME_BASE}/acme/private/${DATE}.bak/
[[ -f ${ACME_BASE}/acme/cert.pem ]] && mv ${ACME_BASE}/acme/cert.pem ${ACME_BASE}/acme/private/${DATE}.bak/
cp ${ACME_BASE}/acme/private/privkey.pem ${ACME_BASE}/acme/private/${DATE}.bak/ # Keep key for TLSA 3 1 1 records
fi
acme-client \
-v -e -b -N -n \
-f ${ACME_BASE}/acme/private/account.key \
-k ${ACME_BASE}/acme/private/privkey.pem \
-c ${ACME_BASE}/acme \
${ALL_VALIDATED[*]}
case "$?" in
0) # new certs
# cp the new certificates and keys
cp ${ACME_BASE}/acme/fullchain.pem ${ACME_BASE}/cert.pem
cp ${ACME_BASE}/acme/private/privkey.pem ${ACME_BASE}/key.pem
# restart docker containers
if ! verify_hash_match ${ACME_BASE}/cert.pem ${ACME_BASE}/key.pem; then
echo "Certificate was successfully requested, but key and certificate have non-matching hashes, restoring mailcow snake-oil and restarting containers..."
cp ${SSL_EXAMPLE}/cert.pem ${ACME_BASE}/cert.pem
cp ${SSL_EXAMPLE}/key.pem ${ACME_BASE}/key.pem
fi
restart_containers ${CONTAINERS_RESTART[*]}
;;
1) # failure
if [[ -f ${ACME_BASE}/acme/private/${DATE}.bak/fullchain.pem ]] && [[ -f ${ACME_BASE}/acme/private/${DATE}.bak/privkey.pem ]]; then
echo "Error requesting certificate, restoring previous certificate from backup and restarting containers...."
cp ${ACME_BASE}/acme/private/${DATE}.bak/fullchain.pem ${ACME_BASE}/cert.pem
cp ${ACME_BASE}/acme/private/${DATE}.bak/privkey.pem ${ACME_BASE}/key.pem
TRIGGER_RESTART=1
elif [[ -f ${ACME_BASE}/acme/fullchain.pem ]] && [[ -f ${ACME_BASE}/acme/private/privkey.pem ]]; then
echo "Error requesting certificate, restoring from previous acme request and restarting containers..."
cp ${ACME_BASE}/acme/fullchain.pem ${ACME_BASE}/cert.pem
cp ${ACME_BASE}/acme/private/privkey.pem ${ACME_BASE}/key.pem
TRIGGER_RESTART=1
fi
if ! verify_hash_match ${ACME_BASE}/cert.pem ${ACME_BASE}/key.pem; then
echo "Error verifying certificates, restoring mailcow snake-oil and restarting containers..."
cp ${SSL_EXAMPLE}/cert.pem ${ACME_BASE}/cert.pem
cp ${SSL_EXAMPLE}/key.pem ${ACME_BASE}/key.pem
TRIGGER_RESTART=1
fi
[[ ${TRIGGER_RESTART} == 1 ]] && restart_containers ${CONTAINERS_RESTART[*]}
exit 1;;
2) # no change
if ! diff ${ACME_BASE}/acme/fullchain.pem ${ACME_BASE}/cert.pem; then
echo "Certificate was not changed, but active certificate does not match the verified certificate, fixing and restarting containers..."
cp ${ACME_BASE}/acme/fullchain.pem ${ACME_BASE}/cert.pem
cp ${ACME_BASE}/acme/private/privkey.pem ${ACME_BASE}/key.pem
restart_containers ${CONTAINERS_RESTART[*]}
fi
if ! verify_hash_match ${ACME_BASE}/cert.pem ${ACME_BASE}/key.pem; then
echo "Certificate was not changed, but hashes do not match, restoring from previous acme request and restarting containers..."
cp ${ACME_BASE}/acme/fullchain.pem ${ACME_BASE}/cert.pem
cp ${ACME_BASE}/acme/private/privkey.pem ${ACME_BASE}/key.pem
restart_containers ${CONTAINERS_RESTART[*]}
fi
;;
*) # unspecified
if [[ -f ${ACME_BASE}/acme/private/${DATE}.bak/fullchain.pem ]] && [[ -f ${ACME_BASE}/acme/private/${DATE}.bak/privkey.pem ]]; then
echo "Error requesting certificate, restoring previous certificate from backup and restarting containers...."
cp ${ACME_BASE}/acme/private/${DATE}.bak/fullchain.pem ${ACME_BASE}/cert.pem
cp ${ACME_BASE}/acme/private/${DATE}.bak/privkey.pem ${ACME_BASE}/key.pem
TRIGGER_RESTART=1
elif [[ -f ${ACME_BASE}/acme/fullchain.pem ]] && [[ -f ${ACME_BASE}/acme/private/privkey.pem ]]; then
echo "Error requesting certificate, restoring from previous acme request and restarting containers..."
cp ${ACME_BASE}/acme/fullchain.pem ${ACME_BASE}/cert.pem
cp ${ACME_BASE}/acme/private/privkey.pem ${ACME_BASE}/key.pem
TRIGGER_RESTART=1
fi
if ! verify_hash_match ${ACME_BASE}/cert.pem ${ACME_BASE}/key.pem; then
echo "Error verifying certificates, restoring mailcow snake-oil..."
cp ${SSL_EXAMPLE}/cert.pem ${ACME_BASE}/cert.pem
cp ${SSL_EXAMPLE}/key.pem ${ACME_BASE}/key.pem
TRIGGER_RESTART=1
fi
[[ ${TRIGGER_RESTART} == 1 ]] && restart_containers ${CONTAINERS_RESTART[*]}
exit 1;;
esac
echo "ACME certificate validation done. Sleeping for another day."
sleep 86400
done

View File

@ -0,0 +1,26 @@
FROM alpine:3.6
LABEL maintainer "André Peters <andre.peters@servercow.de>"
# Add scripts
COPY dl_files.sh bootstrap.sh ./
# Installation
RUN apk add --update \
&& apk add --no-cache clamav clamav-libunrar curl bash \
&& chmod +x /dl_files.sh \
&& set -ex; /bin/bash /dl_files.sh \
&& mkdir /run/clamav \
&& chown clamav:clamav /run/clamav \
&& chmod 750 /run/clamav \
&& sed -i '/Foreground yes/s/^#//g' /etc/clamav/clamd.conf \
&& sed -i '/TCPSocket 3310/s/^#//g' /etc/clamav/clamd.conf \
&& sed -i 's/#PhishingSignatures yes/PhishingSignatures no/g' /etc/clamav/clamd.conf \
&& sed -i 's/#PhishingScanURLs yes/PhishingScanURLs no/g' /etc/clamav/clamd.conf \
&& sed -i '/Foreground yes/s/^#//g' /etc/clamav/freshclam.conf
# Port provision
EXPOSE 3310
# AV daemon bootstrapping
CMD ["/bootstrap.sh"]

View File

@ -0,0 +1,15 @@
#!/bin/bash
trap "kill 0" SIGINT
touch /var/log/clamav/clamd.log /var/log/clamav/freshclam.log
chown -R clamav:clamav /var/log/clamav/
if [[ "${SKIP_CLAMD}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
echo "SKIP_CLAMD=y, skipping ClamAV..."
exit 0
fi
freshclam -d &
clamd &
tail -f /var/log/clamav/clamd.log /var/log/clamav/freshclam.log

View File

@ -0,0 +1,32 @@
#!/bin/bash
declare -a DB_MIRRORS=(
"switch.clamav.net"
"clamavdb.heanet.ie"
"clamav.iol.cz"
"clamav.univ-nantes.fr"
"clamav.easynet.fr"
"clamav.begi.net"
)
declare -a DB_MIRRORS=( $(shuf -e "${DB_MIRRORS[@]}") )
DB_FILES=(
"bytecode.cvd"
"daily.cvd"
"main.cvd"
)
for i in "${DB_MIRRORS[@]}"; do
for j in "${DB_FILES[@]}"; do
[[ -f "/var/lib/clamav/${j}" && -s "/var/lib/clamav/${j}" ]] && continue;
if [[ $(curl -o /dev/null --connect-timeout 1 \
--max-time 1 \
--silent \
--head \
--write-out "%{http_code}\n" "${i}/${j}") == 200 ]]; then
curl "${i}/${j}" -o "/var/lib/clamav/${j}" -#
fi
done
done
chown clamav:clamav /var/lib/clamav/*.cvd

View File

@ -1,87 +1,108 @@
From ubuntu:xenial
MAINTAINER Andre Peters <andre.peters@servercow.de>
FROM debian:stretch-slim
LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
ENV DEBIAN_FRONTEND noninteractive
ARG DEBIAN_FRONTEND=noninteractive
ENV LC_ALL C
ENV DOVECOT_VERSION 2.2.32
ENV PIGEONHOLE_VERSION 0.4.20
RUN dpkg-divert --local --rename --add /sbin/initctl \
&& ln -sf /bin/true /sbin/initctl \
&& dpkg-divert --local --rename --add /usr/bin/ischroot \
&& ln -sf /bin/true /usr/bin/ischroot
RUN apt-get update
RUN apt-get -y install dovecot-common \
dovecot-core \
dovecot-imapd \
dovecot-lmtpd \
dovecot-managesieved \
dovecot-sieve \
dovecot-mysql \
dovecot-pop3d \
dovecot-dev \
syslog-ng \
syslog-ng-core \
ca-certificates \
supervisor \
wget \
curl \
build-essential \
autotools-dev \
RUN apt-get update && apt-get -y install \
automake \
autotools-dev \
build-essential \
ca-certificates \
cpanminus \
curl \
default-libmysqlclient-dev \
libauthen-ntlm-perl \
libbz2-dev \
libcrypt-ssleay-perl \
libdbd-mysql-perl \
libdbi-perl \
libdigest-hmac-perl \
libfile-copy-recursive-perl \
libio-compress-perl \
libio-socket-inet6-perl \
libio-socket-ssl-perl \
libio-tee-perl \
libipc-run-perl \
liblockfile-simple-perl \
liblz-dev \
liblz4-dev \
liblzma-dev \
libmodule-scandeps-perl \
libnet-ssleay-perl \
libpam-dev \
libpar-packer-perl \
libreadonly-perl \
libssl-dev \
libterm-readkey-perl \
libtest-pod-perl \
libtest-simple-perl \
libunicode-string-perl \
libproc-processtable-perl \
liburi-perl \
libdbi-perl \
liblockfile-simple-perl \
libdbd-mysql-perl \
libipc-run-perl \
lzma-dev \
make \
cpanminus
supervisor \
syslog-ng \
syslog-ng-core \
syslog-ng-mod-redis \
&& rm -rf /var/lib/apt/lists/*
RUN curl https://www.dovecot.org/releases/2.2/dovecot-$DOVECOT_VERSION.tar.gz | tar xvz \
&& cd dovecot-$DOVECOT_VERSION \
&& ./configure --with-mysql --with-lzma --with-lz4 --with-ssl=openssl --with-notify=inotify --with-storages=mdbox,sdbox,maildir,mbox,imapc,pop3c --with-bzlib --with-zlib \
&& make -j3 \
&& make install \
&& make clean \
&& cd .. && rm -rf dovecot-$DOVECOT_VERSION \
&& curl https://pigeonhole.dovecot.org/releases/2.2/dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION.tar.gz | tar xvz \
&& cd dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION \
&& ./configure \
&& make -j3 \
&& make install \
&& make clean \
&& cd .. && rm -rf dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION
RUN sed -i -E 's/^(\s*)system\(\);/\1unix-stream("\/dev\/log");/' /etc/syslog-ng/syslog-ng.conf
RUN cpanm Data::Uniqid Mail::IMAPClient String::Util
RUN echo '* * * * * root /usr/local/bin/imapsync_cron.pl' > /etc/cron.d/imapsync
RUN echo '30 3 * * * vmail /usr/bin/doveadm quota recalc -A' > /etc/cron.d/dovecot-sync
RUN echo '30 3 * * * vmail /usr/local/bin/doveadm quota recalc -A' > /etc/cron.d/dovecot-sync
WORKDIR /tmp
COPY syslog-ng.conf /etc/syslog-ng/syslog-ng.conf
COPY imapsync /usr/local/bin/imapsync
COPY postlogin.sh /usr/local/bin/postlogin.sh
COPY imapsync_cron.pl /usr/local/bin/imapsync_cron.pl
COPY report-spam.sieve /usr/local/lib/dovecot/sieve/report-spam.sieve
COPY report-ham.sieve /usr/local/lib/dovecot/sieve/report-ham.sieve
COPY rspamd-pipe-ham /usr/local/lib/dovecot/sieve/rspamd-pipe-ham
COPY rspamd-pipe-spam /usr/local/lib/dovecot/sieve/rspamd-pipe-spam
COPY docker-entrypoint.sh /
COPY supervisord.conf /etc/supervisor/supervisord.conf
RUN wget http://hg.dovecot.org/dovecot-antispam-plugin/archive/tip.tar.gz -O - | tar xvz \
&& cd /tmp/dovecot-antispam* \
&& ./autogen.sh \
&& ./configure --prefix=/usr \
&& make \
&& make install
RUN chmod +x /usr/local/lib/dovecot/sieve/rspamd-pipe-ham \
/usr/local/lib/dovecot/sieve/rspamd-pipe-spam \
/usr/local/bin/imapsync_cron.pl \
/usr/local/bin/postlogin.sh \
/usr/local/bin/imapsync
COPY ./imapsync /usr/local/bin/imapsync
COPY ./postlogin.sh /usr/local/bin/postlogin.sh
COPY ./imapsync_cron.pl /usr/local/bin/imapsync_cron.pl
COPY ./rspamd-pipe /usr/local/bin/rspamd-pipe
COPY ./docker-entrypoint.sh /
COPY ./supervisord.conf /etc/supervisor/supervisord.conf
RUN groupadd -g 5000 vmail \
&& groupadd -g 401 dovecot \
&& groupadd -g 402 dovenull \
&& useradd -g vmail -u 5000 vmail -d /var/vmail \
&& useradd -c "Dovecot unprivileged user" -d /dev/null -u 401 -g dovecot -s /bin/false dovecot \
&& useradd -c "Dovecot login user" -d /dev/null -u 402 -g dovenull -s /bin/false dovenull
RUN chmod +x /usr/local/bin/rspamd-pipe
RUN chmod +x /usr/local/bin/imapsync_cron.pl
RUN groupadd -g 5000 vmail
RUN useradd -g vmail -u 5000 vmail -d /var/vmail
RUN touch /etc/default/locale
RUN apt-get purge -y build-essential automake autotools-dev \
&& apt-get autoremove --purge -y
EXPOSE 24 10001
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
RUN rm -rf \
/tmp/* \
/var/tmp/*

View File

@ -6,23 +6,75 @@ sed -i "/^\$DBUSER/c\\\$DBUSER='${DBUSER}';" /usr/local/bin/imapsync_cron.pl
sed -i "/^\$DBPASS/c\\\$DBPASS='${DBPASS}';" /usr/local/bin/imapsync_cron.pl
sed -i "/^\$DBNAME/c\\\$DBNAME='${DBNAME}';" /usr/local/bin/imapsync_cron.pl
# Set Dovecot config parameters, escape " in db password
DBPASS=$(echo ${DBPASS} | sed 's/"/\\"/g')
sed -i "/^connect/c\connect = \"host=mysql dbname=${DBNAME} user=${DBUSER} password=${DBPASS}\"" /etc/dovecot/sql/*
# Create missing directories
[[ ! -d /usr/local/etc/dovecot/sql/ ]] && mkdir -p /usr/local/etc/dovecot/sql/
[[ ! -d /var/vmail/sieve ]] && mkdir -p /var/vmail/sieve
[[ ! -d /etc/sogo ]] && mkdir -p /etc/sogo
cat /etc/dovecot/sieve_after > /var/vmail/sieve/global.sieve
sievec /var/vmail/sieve/global.sieve
chown -R vmail:vmail /var/vmail/sieve
# Set Dovecot sql config parameters, escape " in db password
DBPASS=$(echo ${DBPASS} | sed 's/"/\\"/g')
# Create quota dict for Dovecot
cat <<EOF > /usr/local/etc/dovecot/sql/dovecot-dict-sql.conf
connect = "host=mysql dbname=${DBNAME} user=${DBUSER} password=${DBPASS}"
map {
pattern = priv/quota/storage
table = quota2
username_field = username
value_field = bytes
}
map {
pattern = priv/quota/messages
table = quota2
username_field = username
value_field = messages
}
EOF
# Create user and pass dict for Dovecot
cat <<EOF > /usr/local/etc/dovecot/sql/dovecot-mysql.conf
driver = mysql
connect = "host=mysql dbname=${DBNAME} user=${DBUSER} password=${DBPASS}"
default_pass_scheme = SSHA256
password_query = SELECT password FROM mailbox WHERE username = '%u' AND domain IN (SELECT domain FROM domain WHERE domain='%d' AND active='1')
user_query = SELECT CONCAT('maildir:/var/vmail/',maildir) AS mail, 5000 AS uid, 5000 AS gid, concat('*:bytes=', quota) AS quota_rule FROM mailbox WHERE username = '%u' AND active = '1'
iterate_query = SELECT username FROM mailbox WHERE active='1';
EOF
# Create global sieve_after script
cat /usr/local/etc/dovecot/sieve_after > /var/vmail/sieve/global.sieve
# Check permissions of vmail directory.
# Do not do this every start-up, it may take a very long time. So we use a stat check here.
if [[ $(stat -c %U /var/vmail/) != "vmail" ]] ; then chown -R vmail:vmail /var/vmail ; fi
# Create random master for SOGo sieve features
RAND_USER=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 16 | head -n 1)
RAND_PASS=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 24 | head -n 1)
echo ${RAND_USER}:$(doveadm pw -s SHA1 -p ${RAND_PASS}) > /etc/dovecot/dovecot-master.passwd
echo ${RAND_USER}:$(doveadm pw -s SHA1 -p ${RAND_PASS}) > /usr/local/etc/dovecot/dovecot-master.passwd
echo ${RAND_USER}:${RAND_PASS} > /etc/sogo/sieve.creds
# 401 is user dovecot
if [[ ! -f /mail_crypt/ecprivkey.pem || ! -f /mail_crypt/ecpubkey.pem ]]; then
openssl ecparam -name prime256v1 -genkey | openssl pkey -out /mail_crypt/ecprivkey.pem
openssl pkey -in /mail_crypt/ecprivkey.pem -pubout -out /mail_crypt/ecpubkey.pem
chown 401 /mail_crypt/ecprivkey.pem /mail_crypt/ecpubkey.pem
else
chown 401 /mail_crypt/ecprivkey.pem /mail_crypt/ecpubkey.pem
fi
# Compile sieve scripts
sievec /var/vmail/sieve/global.sieve
sievec /usr/local/lib/dovecot/sieve/report-spam.sieve
sievec /usr/local/lib/dovecot/sieve/report-ham.sieve
# Fix permissions
chown -R vmail:vmail /var/vmail/sieve
# Fix more than 1 hardlink issue
touch /etc/crontab /etc/cron.*/*
# Clean old PID if any
[[ -f /usr/local/var/run/dovecot/master.pid ]] && rm /usr/local/var/run/dovecot/master.pid
exec "$@"

View File

@ -1,11 +1,20 @@
#!/usr/bin/perl
use DBI;
use File::Temp qw/ mkstemp /;
use LockFile::Simple qw(lock trylock unlock);
use Proc::ProcessTable;
use Data::Dumper qw(Dumper);
use IPC::Run 'run';
use String::Util 'trim';
use File::Temp;
my $t = Proc::ProcessTable->new;
my $imapsync_running = grep { $_->{cmndline} =~ /^\/usr\/bin\/perl \/usr\/local\/bin\/imapsync\s/ } @{$t->table};
if ($imapsync_running eq 1)
{
print "imapsync is active, exiting...";
exit;
}
$DBNAME = '';
$DBUSER = '';
@ -16,12 +25,15 @@ $dsn = "DBI:mysql:database=" . $DBNAME . ";host=mysql";
$lock_file = $run_dir . "/imapsync_busy";
$lockmgr = LockFile::Simple->make(-autoclean => 1, -max => 1);
$lockmgr->lock($lock_file) || die "can't lock ${lock_file}";
$dbh = DBI->connect($dsn, $DBUSER, $DBPASS);
$dbh = DBI->connect($dsn, $DBUSER, $DBPASS, {
mysql_auto_reconnect => 1,
mysql_enable_utf8mb4 => 1
});
open my $file, '<', "/etc/sogo/sieve.creds";
my $creds = <$file>;
close $file;
my ($master_user, $master_pass) = split /:/, $creds;
my $sth = $dbh->prepare("SELECT id, user1, user2, host1, authmech1, password1, exclude, port1, enc1, delete2duplicates, maxage, subfolder2 FROM imapsync WHERE active = 1 AND (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(last_run) > mins_interval * 60 OR last_run IS NULL)");
my $sth = $dbh->prepare("SELECT id, user1, user2, host1, authmech1, password1, exclude, port1, enc1, delete2duplicates, maxage, subfolder2, delete1, delete2 FROM imapsync WHERE active = 1 AND (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(last_run) > mins_interval * 60 OR last_run IS NULL) ORDER BY last_run");
$sth->execute();
my $row;
@ -39,25 +51,36 @@ while ($row = $sth->fetchrow_arrayref()) {
$delete2duplicates = @$row[9];
$maxage = @$row[10];
$subfolder2 = @$row[11];
$delete1 = @$row[12];
$delete2 = @$row[13];
if ($enc1 eq "TLS") { $enc1 = "--tls1"; } elsif ($enc1 eq "SSL") { $enc1 = "--ssl1"; } else { undef $enc1; }
my $template = $run_dir . '/imapsync.XXXXXXX';
my $passfile1 = File::Temp->new(TEMPLATE => $template);
my $passfile2 = File::Temp->new(TEMPLATE => $template);
print $passfile1 "$password1\n";
print $passfile2 trim($master_pass) . "\n";
run [ "/usr/local/bin/imapsync",
"--timeout1", "10",
"--tmpdir", "/tmp",
"--subscribeall",
($exclude eq "" ? () : ("--exclude", $exclude)),
($subfolder2 eq "" ? () : ('--subfolder2', $subfolder2)),
($maxage eq "0" ? () : ('--maxage', $maxage)),
($exclude eq "" ? () : ("--exclude", $exclude)),
($subfolder2 eq "" ? () : ('--subfolder2', $subfolder2)),
($maxage eq "0" ? () : ('--maxage', $maxage)),
($delete2duplicates ne "1" ? () : ('--delete2duplicates')),
(!defined($enc1) ? () : ($enc1)),
($delete1 ne "1" ? () : ('--delete')),
($delete2 ne "1" ? () : ('--delete2')),
(!defined($enc1) ? () : ($enc1)),
"--host1", $host1,
"--user1", $user1,
"--password1", $password1,
"--passfile1", $passfile1->filename,
"--port1", $port1,
"--host2", "localhost",
"--user2", $user2 . '*' . trim($master_user),
"--password2", trim($master_pass),
"--passfile2", $passfile2->filename,
'--no-modulesversion'], ">", \my $stdout;
$update = $dbh->prepare("UPDATE imapsync SET returned_text = ?, last_run = NOW() WHERE id = ?");

View File

@ -0,0 +1,11 @@
require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];
if environment :matches "imap.mailbox" "*" {
set "mailbox" "${1}";
}
if string "${mailbox}" "Trash" {
stop;
}
pipe :copy "rspamd-pipe-ham";

View File

@ -0,0 +1,3 @@
require ["vnd.dovecot.pipe", "copy"];
pipe :copy "rspamd-pipe-spam";

View File

@ -1,8 +0,0 @@
#!/bin/bash
if [[ ${2} == "learn_spam" ]]; then
/usr/bin/curl --data-binary @- http://rspamd:11334/learnspam < /dev/stdin
elif [[ ${2} == "learn_ham" ]]; then
/usr/bin/curl --data-binary @- http://rspamd:11334/learnham < /dev/stdin
fi
# Always return 0 to satisfy Dovecot...
exit 0

View File

@ -0,0 +1,4 @@
#!/bin/bash
/usr/bin/curl -s --data-binary @- http://rspamd:11334/learnham < /dev/stdin
# Always return 0 to satisfy Dovecot...
exit 0

View File

@ -0,0 +1,4 @@
#!/bin/bash
/usr/bin/curl -s --data-binary @- http://rspamd:11334/learnspam < /dev/stdin
# Always return 0 to satisfy Dovecot...
exit 0

View File

@ -3,19 +3,16 @@ nodaemon=true
[program:syslog-ng]
command=/usr/sbin/syslog-ng --foreground --no-caps
redirect_stderr=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autostart=true
stdout_syslog=true
[program:dovecot]
command=/usr/sbin/dovecot -F
command=/usr/local/sbin/dovecot -F
autorestart=true
[program:logfiles]
command=/usr/bin/tail -f /var/log/mail.log /var/log/syslog
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
[program:cron]
command=/usr/sbin/cron -f
autorestart=true

View File

@ -0,0 +1,50 @@
@version: 3.8
@include "scl.conf"
options {
chain_hostnames(off);
flush_lines(0);
use_dns(no);
use_fqdn(no);
owner("root"); group("adm"); perm(0640);
stats_freq(0);
bad_hostname("^gconfd$");
};
source s_src {
unix-stream("/dev/log");
internal();
};
destination d_stdout { pipe("/dev/stdout"); };
destination d_redis_ui_log {
redis(
host("redis-mailcow")
persist-name("redis1")
port(6379)
command("LPUSH" "DOVECOT_MAILLOG" "$(format-json time=\"$S_UNIXTIME\" priority=\"$PRIORITY\" program=\"$PROGRAM\" message=\"$MESSAGE\")\n")
);
};
destination d_redis_f2b_channel {
redis(
host("redis-mailcow")
persist-name("redis2")
port(6379)
command("PUBLISH" "F2B_CHANNEL" "$MESSAGE")
);
};
destination d_redis_cleanup {
redis(
host("redis-mailcow")
persist-name("redis3")
port(6379)
command("LTRIM" "DOVECOT_MAILLOG" "0" "9999")
);
};
filter f_mail { facility(mail); };
log {
source(s_src);
destination(d_stdout);
filter(f_mail);
destination(d_redis_ui_log);
destination(d_redis_f2b_channel);
destination(d_redis_cleanup);
};

View File

@ -0,0 +1,8 @@
FROM python:2-alpine
LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
RUN apk add -U --no-cache iptables ip6tables
RUN pip install redis ipaddress
COPY logwatch.py /
CMD ["python2", "-u", "/logwatch.py"]

View File

@ -0,0 +1,184 @@
#!/usr/bin/env python2
import re
import os
import time
import atexit
import signal
import ipaddress
import subprocess
from threading import Thread
import redis
import time
import json
yes_regex = re.compile(r'([yY][eE][sS]|[yY])+$')
if re.search(yes_regex, os.getenv('SKIP_FAIL2BAN', 0)):
print "Skipping Fail2ban container..."
raise SystemExit
r = redis.StrictRedis(host='172.22.1.249', decode_responses=True, port=6379, db=0)
pubsub = r.pubsub()
RULES = {}
RULES[1] = 'warning: .*\[([0-9a-f\.:]+)\]: SASL .+ authentication failed'
RULES[2] = '-login: Disconnected \(auth failed, .+\): user=.*, method=.+, rip=([0-9a-f\.:]+),'
RULES[3] = '-login: Aborted login \(no auth .+\): user=.+, rip=([0-9a-f\.:]+), lip.+'
RULES[4] = '-login: Aborted login \(tried to use disallowed .+\): user=.+, rip=([0-9a-f\.:]+), lip.+'
RULES[5] = 'SOGo.+ Login from \'([0-9a-f\.:]+)\' for user .+ might not have worked'
RULES[6] = 'mailcow UI: Invalid password for .+ by ([0-9a-f\.:]+)'
r.setnx("F2B_BAN_TIME", "1800")
r.setnx("F2B_MAX_ATTEMPTS", "10")
r.setnx("F2B_RETRY_WINDOW", "600")
bans = {}
log = {}
quit_now = False
def ban(address):
BAN_TIME = int(r.get("F2B_BAN_TIME"))
MAX_ATTEMPTS = int(r.get("F2B_MAX_ATTEMPTS"))
RETRY_WINDOW = int(r.get("F2B_RETRY_WINDOW"))
WHITELIST = r.hgetall("F2B_WHITELIST")
ip = ipaddress.ip_address(address.decode('ascii'))
if type(ip) is ipaddress.IPv6Address and ip.ipv4_mapped:
ip = ip.ipv4_mapped
address = str(ip)
if ip.is_private or ip.is_loopback:
return
self_network = ipaddress.ip_network(address.decode('ascii'))
if WHITELIST:
for wl_key in WHITELIST:
wl_net = ipaddress.ip_network(wl_key.decode('ascii'), False)
if wl_net.overlaps(self_network):
log['time'] = int(round(time.time()))
log['priority'] = "info"
log['message'] = "Address %s is whitelisted by rule %s" % (self_network, wl_net)
r.lpush("F2B_LOG", json.dumps(log, ensure_ascii=False))
print "Address %s is whitelisted by rule %s" % (self_network, wl_net)
return
net = ipaddress.ip_network((address + ('/24' if type(ip) is ipaddress.IPv4Address else '/64')).decode('ascii'), strict=False)
net = str(net)
if not net in bans or time.time() - bans[net]['last_attempt'] > RETRY_WINDOW:
bans[net] = { 'attempts': 0 }
active_window = RETRY_WINDOW
else:
active_window = time.time() - bans[net]['last_attempt']
bans[net]['attempts'] += 1
bans[net]['last_attempt'] = time.time()
active_window = time.time() - bans[net]['last_attempt']
if bans[net]['attempts'] >= MAX_ATTEMPTS:
log['time'] = int(round(time.time()))
log['priority'] = "crit"
log['message'] = "Banning %s" % net
r.lpush("F2B_LOG", json.dumps(log, ensure_ascii=False))
print "Banning %s for %d minutes" % (net, BAN_TIME / 60)
if type(ip) is ipaddress.IPv4Address:
subprocess.call(["iptables", "-I", "INPUT", "-s", net, "-j", "REJECT"])
subprocess.call(["iptables", "-I", "FORWARD", "-s", net, "-j", "REJECT"])
else:
subprocess.call(["ip6tables", "-I", "INPUT", "-s", net, "-j", "REJECT"])
subprocess.call(["ip6tables", "-I", "FORWARD", "-s", net, "-j", "REJECT"])
r.hset("F2B_ACTIVE_BANS", "%s" % net, log['time'] + BAN_TIME)
else:
log['time'] = int(round(time.time()))
log['priority'] = "warn"
log['message'] = "%d more attempts in the next %d seconds until %s is banned" % (MAX_ATTEMPTS - bans[net]['attempts'], RETRY_WINDOW, net)
r.lpush("F2B_LOG", json.dumps(log, ensure_ascii=False))
print "%d more attempts in the next %d seconds until %s is banned" % (MAX_ATTEMPTS - bans[net]['attempts'], RETRY_WINDOW, net)
def unban(net):
log['time'] = int(round(time.time()))
log['priority'] = "info"
r.lpush("F2B_LOG", json.dumps(log, ensure_ascii=False))
if not net in bans:
log['message'] = "%s is not banned, skipping unban and deleting from queue (if any)" % net
r.lpush("F2B_LOG", json.dumps(log, ensure_ascii=False))
print "%s is not banned, skipping unban and deleting from queue (if any)" % net
r.hdel("F2B_QUEUE_UNBAN", "%s" % net)
return
log['message'] = "Unbanning %s" % net
r.lpush("F2B_LOG", json.dumps(log, ensure_ascii=False))
print "Unbanning %s" % net
if type(ipaddress.ip_network(net.decode('ascii'))) is ipaddress.IPv4Network:
subprocess.call(["iptables", "-D", "INPUT", "-s", net, "-j", "REJECT"])
subprocess.call(["iptables", "-D", "FORWARD", "-s", net, "-j", "REJECT"])
else:
subprocess.call(["ip6tables", "-D", "INPUT", "-s", net, "-j", "REJECT"])
subprocess.call(["ip6tables", "-D", "FORWARD", "-s", net, "-j", "REJECT"])
r.hdel("F2B_ACTIVE_BANS", "%s" % net)
r.hdel("F2B_QUEUE_UNBAN", "%s" % net)
del bans[net]
def quit(signum, frame):
global quit_now
quit_now = True
def clear():
log['time'] = int(round(time.time()))
log['priority'] = "info"
log['message'] = "Clearing all bans"
r.lpush("F2B_LOG", json.dumps(log, ensure_ascii=False))
print "Clearing all bans"
for net in bans.copy():
unban(net)
pubsub.unsubscribe()
def watch():
log['time'] = int(round(time.time()))
log['priority'] = "info"
log['message'] = "Watching Redis channel F2B_CHANNEL"
r.lpush("F2B_LOG", json.dumps(log, ensure_ascii=False))
pubsub.subscribe("F2B_CHANNEL")
print "Subscribing to Redis channel F2B_CHANNEL"
while True:
for item in pubsub.listen():
for rule_id, rule_regex in RULES.iteritems():
if item['data'] and item['type'] == 'message':
result = re.search(rule_regex, item['data'])
if result:
addr = result.group(1)
print "%s matched rule id %d" % (addr, rule_id)
log['time'] = int(round(time.time()))
log['priority'] = "warn"
log['message'] = "%s matched rule id %d" % (addr, rule_id)
r.lpush("F2B_LOG", json.dumps(log, ensure_ascii=False))
ban(addr)
def autopurge():
while not quit_now:
BAN_TIME = int(r.get("F2B_BAN_TIME"))
MAX_ATTEMPTS = int(r.get("F2B_MAX_ATTEMPTS"))
QUEUE_UNBAN = r.hgetall("F2B_QUEUE_UNBAN")
if QUEUE_UNBAN:
for net in QUEUE_UNBAN:
unban(str(net))
for net in bans.copy():
if bans[net]['attempts'] >= MAX_ATTEMPTS:
if time.time() - bans[net]['last_attempt'] > BAN_TIME:
unban(net)
time.sleep(10)
if __name__ == '__main__':
watch_thread = Thread(target=watch)
watch_thread.daemon = True
watch_thread.start()
autopurge_thread = Thread(target=autopurge)
autopurge_thread.daemon = True
autopurge_thread.start()
signal.signal(signal.SIGTERM, quit)
atexit.register(clear)
while not quit_now:
time.sleep(0.5)

View File

@ -1,26 +0,0 @@
FROM ubuntu:xenial
MAINTAINER Andre Peters <andre.peters@debinux.de>
ENV DEBIAN_FRONTEND noninteractive
ENV LC_ALL C
RUN dpkg-divert --local --rename --add /sbin/initctl \
&& ln -sf /bin/true /sbin/initctl \
&& dpkg-divert --local --rename --add /usr/bin/ischroot \
&& ln -sf /bin/true /usr/bin/ischroot
RUN echo 'deb http://repo.powerdns.com/ubuntu xenial-rec-40 main' > /etc/apt/sources.list.d/pdns.list
RUN echo 'Package: pdns-*\n\
Pin: origin repo.powerdns.com\n\
Pin-Priority: 600\n' > /etc/apt/preferences.d/pdns
RUN apt-key adv --fetch-keys http://repo.powerdns.com/FD380FBB-pub.asc \
&& apt-get update \
&& apt-get install -y --force-yes pdns-recursor
CMD ["/usr/sbin/pdns_recursor"]
EXPOSE 53/udp
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

View File

@ -1,18 +0,0 @@
FROM php:7.1-fpm
MAINTAINER Andre Peters <andre.peters@servercow.de>
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update \
&& apt-get install -y zlib1g-dev libicu-dev g++ libidn11-dev libxml2-dev
RUN docker-php-ext-configure intl
RUN docker-php-ext-install intl pdo pdo_mysql xmlrpc
RUN pear install channel://pear.php.net/Net_IDNA2-0.1.1 Auth_SASL Net_IMAP NET_SMTP Net_IDNA2 Mail_mime
COPY ./docker-entrypoint.sh /
EXPOSE 9000
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["php-fpm"]

View File

@ -1,7 +0,0 @@
#!/bin/bash
set -e
if [[ ! -d "/data/dkim/txt" || ! -d "/data/dkim/keys" ]] ; then mkdir -p /data/dkim/{txt,keys} ; chown -R www-data:www-data /data/dkim; fi
if [[ $(stat -c %U /data/dkim/) != "www-data" ]] ; then chown -R www-data:www-data /data/dkim ; fi
exec "$@"

View File

@ -0,0 +1,27 @@
FROM php:7.1-fpm-alpine
LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
RUN apk add -U --no-cache libxml2-dev \
icu-dev \
icu-libs \
redis \
mysql-client \
bash \
autoconf \
g++ \
make \
openssl \
&& pecl install redis \
&& pecl clear-cache \
&& docker-php-ext-configure intl \
&& docker-php-ext-install intl pdo pdo_mysql xmlrpc \
&& docker-php-ext-enable redis \
&& pear install channel://pear.php.net/Net_IDNA2-0.1.1 Auth_SASL Net_IMAP NET_SMTP Net_IDNA2 Mail_mime \
&& apk del autoconf g++ make libxml2-dev icu-dev
COPY ./docker-entrypoint.sh /
EXPOSE 9000
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["php-fpm"]

View File

@ -0,0 +1,85 @@
#!/bin/bash
set -e
if [[ ! -d "/data/dkim/txt" || ! -d "/data/dkim/keys" ]] ; then mkdir -p /data/dkim/{txt,keys} ; chown -R www-data:www-data /data/dkim; fi
if [[ $(stat -c %U /data/dkim/) != "www-data" ]] ; then chown -R www-data:www-data /data/dkim ; fi
# Wait for containers
while ! mysqladmin ping --host mysql --silent; do
sleep 2
done
until [ $(redis-cli -h redis-mailcow PING) == "PONG" ]; do
sleep 2
done
# Migrate domain map
declare -a DOMAIN_ARR
redis-cli -h redis-mailcow DEL DOMAIN_MAP
while read line
do
DOMAIN_ARR+=("$line")
done < <(mysql -h mysql-mailcow -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM domain" -Bs)
if [[ ! -z ${DOMAIN_ARR} ]]; then
for domain in "${DOMAIN_ARR[@]}"; do
redis-cli -h redis-mailcow HSET DOMAIN_MAP ${domain} 1
done
fi
# Migrate tag settings map
declare -a SUBJ_TAG_ARR
redis-cli -h redis-mailcow DEL SUBJ_TAG_ARR
while read line
do
SUBJ_TAG_ARR+=("$line")
done < <(mysql -h mysql-mailcow -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT username FROM mailbox WHERE wants_tagged_subject='1'" -Bs)
if [[ ! -z ${SUBJ_TAG_ARR} ]]; then
for user in "${SUBJ_TAG_ARR[@]}"; do
redis-cli -h redis-mailcow HSET RCPT_WANTS_SUBJECT_TAG ${user} 1
mysql -h mysql-mailcow -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "UPDATE mailbox SET wants_tagged_subject='2' WHERE username = '${user}'"
done
fi
# Migrate DKIM keys
for file in $(ls /data/dkim/keys/); do
domain=${file%.dkim}
if [[ -f /data/dkim/txt/${file} ]]; then
redis-cli -h redis-mailcow HSET DKIM_PUB_KEYS "${domain}" "$(cat /data/dkim/txt/${file})"
redis-cli -h redis-mailcow HSET DKIM_PRIV_KEYS "dkim.${domain}" "$(cat /data/dkim/keys/${file})"
redis-cli -h redis-mailcow HSET DKIM_SELECTORS "${domain}" "dkim"
fi
rm /data/dkim/{keys,txt}/${file}
done
# Fix DKIM keys
# Fetch domains
declare -a DOMAIN_ARRAY
while read line
do
DOMAIN_ARRAY+=("$line")
done < <(mysql -h mysql-mailcow -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM domain" -Bs)
while read line
do
DOMAIN_ARRAY+=("$line")
done < <(mysql -h mysql-mailcow -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT alias_domain FROM alias_domain" -Bs)
# Loop through array and fix keys
if [[ ! -z ${DOMAIN_ARRAY} ]]; then
for domain in "${DOMAIN_ARRAY[@]}"; do
WRONG_KEY=$(redis-cli -h redis-mailcow HGET DKIM_PRIV_KEYS ${domain} | tr -d \")
if [[ ! -z ${WRONG_KEY} ]]; then
echo "Migrating defect key for domain ${domain}"
redis-cli -h redis-mailcow HSET DKIM_PRIV_KEYS "dkim.${domain}" ${WRONG_KEY}
redis-cli -h redis-mailcow HDEL DKIM_PRIV_KEYS "${domain}"
fi
done
fi
exec "$@"

View File

@ -1,7 +1,7 @@
From ubuntu:xenial
MAINTAINER Andre Peters <andre.peters@servercow.de>
FROM debian:stretch-slim
LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
ENV DEBIAN_FRONTEND noninteractive
ARG DEBIAN_FRONTEND=noninteractive
ENV LC_ALL C
RUN dpkg-divert --local --rename --add /sbin/initctl \
@ -9,25 +9,38 @@ RUN dpkg-divert --local --rename --add /sbin/initctl \
&& dpkg-divert --local --rename --add /usr/bin/ischroot \
&& ln -sf /bin/true /usr/bin/ischroot
RUN apt-get update
RUN apt-get install -y --no-install-recommends supervisor \
postfix \
sasl2-bin \
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
curl \
dirmngr \
gnupg \
libsasl2-modules \
postfix \
postfix-mysql \
postfix-pcre \
python-gpgme \
sasl2-bin \
sudo \
supervisor \
syslog-ng \
syslog-ng-core \
ca-certificates
syslog-ng-mod-redis \
&& rm -rf /var/lib/apt/lists/* \
&& touch /etc/default/locale
RUN sed -i -E 's/^(\s*)system\(\);/\1unix-stream("\/dev\/log");/' /etc/syslog-ng/syslog-ng.conf
RUN addgroup --system --gid 600 zeyple
RUN adduser --system --home /var/lib/zeyple --no-create-home --uid 600 --gid 600 --disabled-login zeyple
RUN touch /var/log/zeyple.log && chown zeyple: /var/log/zeyple.log
COPY zeyple.py /usr/local/bin/zeyple.py
COPY zeyple.conf /etc/zeyple.conf
COPY supervisord.conf /etc/supervisor/supervisord.conf
COPY syslog-ng.conf /etc/syslog-ng/syslog-ng.conf
COPY postfix.sh /opt/postfix.sh
COPY whitelist_forwardinghosts.sh /usr/local/bin/whitelist_forwardinghosts.sh
EXPOSE 588
CMD exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
RUN rm -rf /tmp/* /var/tmp/*

View File

@ -2,15 +2,131 @@
trap "postfix stop" EXIT
sed -i "/^user/c\user = ${DBUSER}" /opt/postfix/conf/sql/*
sed -i "/^password/c\password = ${DBPASS}" /opt/postfix/conf/sql/*
sed -i "/^dbname/c\dbname = ${DBNAME}" /opt/postfix/conf/sql/*
[[ ! -d /opt/postfix/conf/sql/ ]] && mkdir -p /opt/postfix/conf/sql/
if [[ -z $(grep null /etc/aliases) ]]; then
echo null: /dev/null >> /etc/aliases;
newaliases;
fi
cat <<EOF > /opt/postfix/conf/sql/mysql_relay_recipient_maps.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT DISTINCT CASE WHEN '%d' IN (SELECT domain FROM domain WHERE relay_all_recipients=1 AND domain='%d' AND backupmx=1) THEN '%s' ELSE (SELECT goto FROM alias WHERE address='%s' AND active='1') END AS result;
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_tls_enforce_in_policy.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT IF( EXISTS( SELECT 'TLS_ACTIVE' FROM alias LEFT OUTER JOIN mailbox ON mailbox.username = alias.goto WHERE (address='%s' OR address IN (SELECT CONCAT('%u', '@', target_domain) FROM alias_domain WHERE alias_domain='%d')) AND mailbox.tls_enforce_in = '1' AND mailbox.active = '1'), 'reject_plaintext_session', NULL) AS 'tls_enforce_in';
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_sender_dependent_default_transport_maps.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT GROUP_CONCAT(transport SEPARATOR '') AS transport_maps
FROM (
SELECT IF(EXISTS(SELECT 'smtp_type' FROM alias LEFT OUTER JOIN mailbox ON mailbox.username = alias.goto WHERE (address = '%s' OR address IN (SELECT CONCAT('%u', '@', target_domain) FROM alias_domain WHERE alias_domain = '%d')) AND mailbox.tls_enforce_out = '1' AND mailbox.active = '1'), 'smtp_enforced_tls:', 'smtp:') AS 'transport'
UNION ALL
SELECT hostname AS transport FROM relayhosts LEFT OUTER JOIN domain ON domain.relayhost = relayhosts.id WHERE relayhosts.active = '1' AND domain = '%d' OR domain IN (SELECT target_domain FROM alias_domain WHERE alias_domain = '%d')
)
AS transport_view;
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_sasl_passwd_maps.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT CONCAT_WS(':', username, password) AS auth_data FROM relayhosts WHERE id IN (SELECT relayhost FROM domain WHERE CONCAT('@', domain) = '%s');
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_virtual_alias_domain_catchall_maps.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT goto FROM alias,alias_domain WHERE alias_domain.alias_domain = '%d' and alias.address = CONCAT('@', alias_domain.target_domain) AND alias.active = 1 AND alias_domain.active='1'
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_virtual_alias_domain_maps.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT username FROM mailbox,alias_domain WHERE alias_domain.alias_domain = '%d' and mailbox.username = CONCAT('%u', '@', alias_domain.target_domain) AND mailbox.active = 1 AND alias_domain.active='1'
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_virtual_alias_maps.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT goto FROM alias WHERE address='%s' AND active='1';
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_virtual_domains_maps.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT alias_domain from alias_domain WHERE alias_domain='%s' AND active='1' UNION SELECT domain FROM domain WHERE domain='%s' AND active = '1' AND backupmx = '0'
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_virtual_mailbox_maps.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = '1'
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_virtual_relay_domain_maps.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT domain FROM domain WHERE domain='%s' AND backupmx = '1' AND active = '1'
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_virtual_sender_acl.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT goto FROM alias WHERE address='%s' AND active='1' AND (domain IN (SELECT domain FROM domain WHERE domain='%d' AND active='1') OR domain in (SELECT target_domain FROM alias_domain WHERE alias_domain='%d' AND active='1')) UNION SELECT logged_in_as FROM sender_acl WHERE send_as='@%d' OR send_as='%s' OR send_as IN ( SELECT CONCAT ('@',target_domain) FROM alias_domain WHERE alias_domain = '%d') OR send_as IN ( SELECT CONCAT ('%u','@',target_domain) FROM alias_domain WHERE alias_domain = '%d' ) AND logged_in_as NOT IN (SELECT goto FROM alias WHERE address='%s') UNION SELECT username FROM mailbox,alias_domain WHERE alias_domain.alias_domain = '%d' AND mailbox.username = CONCAT('%u','@',alias_domain.target_domain) AND mailbox.active ='1' AND alias_domain.active='1'
EOF
cat <<EOF > /opt/postfix/conf/sql/mysql_virtual_spamalias_maps.cf
user = ${DBUSER}
password = ${DBPASS}
hosts = mysql
dbname = ${DBNAME}
query = SELECT goto FROM spamalias WHERE address='%s' AND validity >= UNIX_TIMESTAMP()
EOF
# Reset GPG key permissions
mkdir -p /var/lib/zeyple/keys
chmod 700 /var/lib/zeyple/keys
chown -R 600:600 /var/lib/zeyple/keys
# Fix Postfix permissions
chgrp -R postdrop /var/spool/postfix/public
chgrp -R postdrop /var/spool/postfix/maildrop
postfix set-permissions
# Check Postfix configuration
postconf -c /opt/postfix/conf
if [[ $? != 0 ]]; then
echo "Postfix configuration error, refusing to start."
exit 1
else
postfix -c /opt/postfix/conf start
sleep infinity
sleep 126144000
fi

View File

@ -3,15 +3,23 @@ nodaemon=true
[program:syslog-ng]
command=/usr/sbin/syslog-ng --foreground --no-caps
redirect_stderr=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autostart=true
stdout_syslog=true
[program:postfix]
command=/opt/postfix.sh
autorestart=true
[program:postfix-maillog]
command=/usr/bin/tail -f /var/log/mail.log
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
[unix_http_server]
file=/var/tmp/supervisord.sock
chmod=0770
chown=nobody:nogroup
[supervisorctl]
serverurl=unix:///var/tmp/supervisord.sock
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

View File

@ -0,0 +1,49 @@
@version: 3.8
@include "scl.conf"
options {
chain_hostnames(off);
flush_lines(0);
use_dns(no);
use_fqdn(no);
owner("root"); group("adm"); perm(0640);
stats_freq(0);
bad_hostname("^gconfd$");
};
source s_src {
unix-stream("/dev/log");
internal();
};
destination d_stdout { pipe("/dev/stdout"); };
destination d_redis_ui_log {
redis(
host("redis-mailcow")
persist-name("redis1")
port(6379)
command("LPUSH" "POSTFIX_MAILLOG" "$(format-json time=\"$S_UNIXTIME\" priority=\"$PRIORITY\" program=\"$PROGRAM\" message=\"$MESSAGE\")\n")
);
};
destination d_redis_f2b_channel {
redis(
host("redis-mailcow")
persist-name("redis2")
port(6379)
command("PUBLISH" "F2B_CHANNEL" "$MESSAGE")
);
};
destination d_redis_cleanup {
redis(
host("redis-mailcow")
persist-name("redis3")
port(6379)
command("LTRIM" "POSTFIX_MAILLOG" "0" "9999")
);
};
filter f_mail { facility(mail); };
log {
source(s_src);
destination(d_stdout);
filter(f_mail);
destination(d_redis_ui_log);
destination(d_redis_f2b_channel);
destination(d_redis_cleanup);
};

View File

@ -0,0 +1,12 @@
#!/bin/bash
while read QUERY; do
QUERY=($QUERY)
if [ "${QUERY[0]}" != "get" ]; then
echo "500 dunno"
continue
fi
result=$(curl -s http://172.22.1.251:8081/forwardinghosts.php?host=${QUERY[1]})
logger -t whitelist_forwardinghosts -p mail.info "Look up ${QUERY[1]} on whitelist, result $result"
echo ${result}
done

View File

@ -0,0 +1,9 @@
[zeyple]
log_file = /dev/null
[gpg]
home = /var/lib/zeyple/keys
[relay]
host = localhost
port = 10026

View File

@ -0,0 +1,274 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import email
import email.mime.multipart
import email.mime.application
import email.encoders
import smtplib
import copy
from io import BytesIO
try:
from configparser import SafeConfigParser # Python 3
except ImportError:
from ConfigParser import SafeConfigParser # Python 2
import gpgme
# Boiler plate to avoid dependency on six
# BBB: Python 2.7 support
PY3K = sys.version_info > (3, 0)
def message_from_binary(message):
if PY3K:
return email.message_from_bytes(message)
else:
return email.message_from_string(message)
def as_binary_string(email):
if PY3K:
return email.as_bytes()
else:
return email.as_string()
def encode_string(string):
if isinstance(string, bytes):
return string
else:
return string.encode('utf-8')
__title__ = 'Zeyple'
__version__ = '1.2.0'
__author__ = 'Cédric Félizard'
__license__ = 'AGPLv3+'
__copyright__ = 'Copyright 2012-2016 Cédric Félizard'
class Zeyple:
"""Zeyple Encrypts Your Precious Log Emails"""
def __init__(self, config_fname='zeyple.conf'):
self.config = self.load_configuration(config_fname)
log_file = self.config.get('zeyple', 'log_file')
logging.basicConfig(
filename=log_file, level=logging.DEBUG,
format='%(asctime)s %(process)s %(levelname)s %(message)s'
)
logging.info("Zeyple ready to encrypt outgoing emails")
def load_configuration(self, filename):
"""Reads and parses the config file"""
config = SafeConfigParser()
config.read([
os.path.join('/etc/', filename),
filename,
])
if not config.sections():
raise IOError('Cannot open config file.')
return config
@property
def gpg(self):
protocol = gpgme.PROTOCOL_OpenPGP
if self.config.has_option('gpg', 'executable'):
executable = self.config.get('gpg', 'executable')
else:
executable = None # Default value
home_dir = self.config.get('gpg', 'home')
ctx = gpgme.Context()
ctx.set_engine_info(protocol, executable, home_dir)
ctx.armor = True
return ctx
def process_message(self, message_data, recipients):
"""Encrypts the message with recipient keys"""
message_data = encode_string(message_data)
in_message = message_from_binary(message_data)
logging.info(
"Processing outgoing message %s", in_message['Message-id'])
if not recipients:
logging.warn("Cannot find any recipients, ignoring")
sent_messages = []
for recipient in recipients:
logging.info("Recipient: %s", recipient)
key_id = self._user_key(recipient)
logging.info("Key ID: %s", key_id)
if key_id:
out_message = self._encrypt_message(in_message, key_id)
# Delete Content-Transfer-Encoding if present to default to
# "7bit" otherwise Thunderbird seems to hang in some cases.
del out_message["Content-Transfer-Encoding"]
else:
logging.warn("No keys found, message will be sent unencrypted")
out_message = copy.copy(in_message)
self._add_zeyple_header(out_message)
self._send_message(out_message, recipient)
sent_messages.append(out_message)
return sent_messages
def _get_version_part(self):
ret = email.mime.application.MIMEApplication(
'Version: 1\n',
'pgp-encrypted',
email.encoders.encode_noop,
)
ret.add_header(
'Content-Description',
"PGP/MIME version identification",
)
return ret
def _get_encrypted_part(self, payload):
ret = email.mime.application.MIMEApplication(
payload,
'octet-stream',
email.encoders.encode_noop,
name="encrypted.asc",
)
ret.add_header('Content-Description', "OpenPGP encrypted message")
ret.add_header(
'Content-Disposition',
'inline',
filename='encrypted.asc',
)
return ret
def _encrypt_message(self, in_message, key_id):
if in_message.is_multipart():
# get the body (after the first \n\n)
payload = in_message.as_string().split("\n\n", 1)[1].strip()
# prepend the Content-Type including the boundary
content_type = "Content-Type: " + in_message["Content-Type"]
payload = content_type + "\n\n" + payload
message = email.message.Message()
message.set_payload(payload)
payload = message.get_payload()
else:
payload = in_message.get_payload()
payload = encode_string(payload)
quoted_printable = email.charset.Charset('ascii')
quoted_printable.body_encoding = email.charset.QP
message = email.mime.nonmultipart.MIMENonMultipart(
'text', 'plain', charset='utf-8'
)
message.set_payload(payload, charset=quoted_printable)
mixed = email.mime.multipart.MIMEMultipart(
'mixed',
None,
[message],
)
# remove superfluous header
del mixed['MIME-Version']
payload = as_binary_string(mixed)
encrypted_payload = self._encrypt_payload(payload, [key_id])
version = self._get_version_part()
encrypted = self._get_encrypted_part(encrypted_payload)
out_message = copy.copy(in_message)
out_message.preamble = "This is an OpenPGP/MIME encrypted " \
"message (RFC 4880 and 3156)"
if 'Content-Type' not in out_message:
out_message['Content-Type'] = 'multipart/encrypted'
else:
out_message.replace_header(
'Content-Type',
'multipart/encrypted',
)
out_message.set_param('protocol', 'application/pgp-encrypted')
out_message.set_payload([version, encrypted])
return out_message
def _encrypt_payload(self, payload, key_ids):
"""Encrypts the payload with the given keys"""
payload = encode_string(payload)
plaintext = BytesIO(payload)
ciphertext = BytesIO()
self.gpg.armor = True
recipient = [self.gpg.get_key(key_id) for key_id in key_ids]
self.gpg.encrypt(recipient, gpgme.ENCRYPT_ALWAYS_TRUST,
plaintext, ciphertext)
return ciphertext.getvalue()
def _user_key(self, email):
"""Returns the GPG key for the given email address"""
logging.info("Trying to encrypt for %s", email)
keys = [key for key in self.gpg.keylist(email)]
if keys:
key = keys.pop() # NOTE: looks like keys[0] is the master key
key_id = key.subkeys[0].keyid
return key_id
return None
def _add_zeyple_header(self, message):
if self.config.has_option('zeyple', 'add_header') and \
self.config.getboolean('zeyple', 'add_header'):
message.add_header(
'X-Zeyple',
"processed by {0} v{1}".format(__title__, __version__)
)
def _send_message(self, message, recipient):
"""Sends the given message through the SMTP relay"""
logging.info("Sending message %s", message['Message-id'])
smtp = smtplib.SMTP(self.config.get('relay', 'host'),
self.config.get('relay', 'port'))
smtp.sendmail(message['From'], recipient, message.as_string())
smtp.quit()
logging.info("Message %s sent", message['Message-id'])
if __name__ == '__main__':
recipients = sys.argv[1:]
# BBB: Python 2.7 support
binary_stdin = sys.stdin.buffer if PY3K else sys.stdin
message = binary_stdin.read()
zeyple = Zeyple()
zeyple.process_message(message, recipients)

View File

@ -1,26 +0,0 @@
FROM ubuntu:xenial
MAINTAINER Andre Peters <andre.peters@servercow.de>
ENV DEBIAN_FRONTEND noninteractive
ENV LC_ALL C
RUN dpkg-divert --local --rename --add /sbin/initctl \
&& ln -sf /bin/true /sbin/initctl \
&& dpkg-divert --local --rename --add /usr/bin/ischroot \
&& ln -sf /bin/true /usr/bin/ischroot
RUN apt-key adv --fetch-keys http://rspamd.com/apt-stable/gpg.key \
&& echo "deb http://rspamd.com/apt-stable/ xenial main" > /etc/apt/sources.list.d/rspamd.list \
&& apt-get update \
&& apt-get --no-install-recommends -y --force-yes install rmilter cron syslog-ng syslog-ng-core supervisor
COPY supervisord.conf /etc/supervisor/supervisord.conf
EXPOSE 9000
RUN sed -i -E 's/^(\s*)system\(\);/\1unix-stream("\/dev\/log");/' /etc/syslog-ng/syslog-ng.conf
RUN touch /var/log/mail.log && chmod 640 /var/log/mail.log && chown root:adm /var/log/mail.log
CMD exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

View File

@ -1,18 +0,0 @@
[supervisord]
nodaemon=true
[program:syslog-ng]
command=/usr/sbin/syslog-ng --foreground --no-caps
redirect_stderr=true
autostart=true
stdout_syslog=true
[program:rmilter]
command=/usr/sbin/rmilter -n -c /etc/rmilter.conf.d/rmilter.conf
user=_rmilter
autorestart=true
[program:rmilter-syslog]
command=/usr/bin/tail -f /var/log/mail.log
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0

View File

@ -1,27 +1,28 @@
FROM ubuntu:xenial
MAINTAINER Andre Peters <andre.peters@debinux.de>
FROM debian:stretch-slim
LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
ENV DEBIAN_FRONTEND noninteractive
ARG DEBIAN_FRONTEND=noninteractive
ENV LC_ALL C
RUN dpkg-divert --local --rename --add /sbin/initctl \
&& ln -sf /bin/true /sbin/initctl \
&& dpkg-divert --local --rename --add /usr/bin/ischroot \
&& ln -sf /bin/true /usr/bin/ischroot
RUN apt-get update && apt-get install -y \
ca-certificates \
gnupg2 \
apt-transport-https \
&& apt-key adv --fetch-keys https://rspamd.com/apt/gpg.key \
&& echo "deb https://rspamd.com/apt/ stretch main" > /etc/apt/sources.list.d/rspamd.list \
&& apt-get update && apt-get install -y rspamd \
&& rm -rf /var/lib/apt/lists/* \
&& echo '.include $LOCAL_CONFDIR/local.d/rspamd.conf.local' > /etc/rspamd/rspamd.conf.local \
&& apt-get autoremove --purge \
&& apt-get clean \
&& mkdir -p /run/rspamd \
&& chown _rspamd:_rspamd /run/rspamd
RUN apt-key adv --fetch-keys http://rspamd.com/apt-stable/gpg.key \
&& echo "deb http://rspamd.com/apt-stable/ xenial main" > /etc/apt/sources.list.d/rspamd.list \
&& apt-get update \
&& apt-get -y install rspamd ca-certificates
COPY settings.conf /etc/rspamd/modules.d/settings.conf
COPY ratelimit.lua /usr/share/rspamd/lua/ratelimit.lua
COPY lua_util.lua /usr/share/rspamd/lib/lua_util.lua
COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN echo '.include $LOCAL_CONFDIR/local.d/rspamd.conf.local' > /etc/rspamd/rspamd.conf.local
# "Hardcoded" - we need them
RUN echo 'settings = "http://nginx:8081/settings.php";' > /etc/rspamd/modules.d/settings.conf
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["/usr/bin/rspamd","-f", "-u", "_rspamd", "-g", "_rspamd"]
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
USER _rspamd
EXPOSE 11333 11334
CMD /usr/bin/rspamd -f -u _rspamd -g _rspamd

View File

@ -0,0 +1,5 @@
#!/bin/bash
chown -R _rspamd:_rspamd /var/lib/rspamd
exec "$@"

View File

@ -0,0 +1,152 @@
local exports = {}
local lpeg = require 'lpeg'
local split_grammar = {}
local function rspamd_str_split(s, sep)
local gr = split_grammar[sep]
if not gr then
local _sep = lpeg.P(sep)
local elem = lpeg.C((1 - _sep)^0)
local p = lpeg.Ct(elem * (_sep * elem)^0)
gr = p
split_grammar[sep] = gr
end
return gr:match(s)
end
exports.rspamd_str_split = rspamd_str_split
local space = lpeg.S' \t\n\v\f\r'
local nospace = 1 - space
local ptrim = space^0 * lpeg.C((space^0 * nospace^1)^0)
local match = lpeg.match
exports.rspamd_str_trim = function(s)
return match(ptrim, s)
end
-- Robert Jay Gould http://lua-users.org/wiki/SimpleRound
exports.round = function(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult) / mult
end
exports.template = function(tmpl, keys)
local var_lit = lpeg.P { lpeg.R("az") + lpeg.R("AZ") + lpeg.R("09") + "_" }
local var = lpeg.P { (lpeg.P("$") / "") * ((var_lit^1) / keys) }
local var_braced = lpeg.P { (lpeg.P("${") / "") * ((var_lit^1) / keys) * (lpeg.P("}") / "") }
local template_grammar = lpeg.Cs((var + var_braced + 1)^0)
return lpeg.match(template_grammar, tmpl)
end
exports.remove_email_aliases = function(email_addr)
local function check_gmail_user(addr)
-- Remove all points
local no_dots_user = string.gsub(addr.user, '%.', '')
local cap, pluses = string.match(no_dots_user, '^([^%+][^%+]*)(%+.*)$')
if cap then
return cap, rspamd_str_split(pluses, '+'), nil
elseif no_dots_user ~= addr.user then
return no_dots_user,{},nil
end
return nil
end
local function check_address(addr)
if addr.user then
local cap, pluses = string.match(addr.user, '^([^%+][^%+]*)(%+.*)$')
if cap then
return cap, rspamd_str_split(pluses, '+'), nil
end
end
return nil
end
local function set_addr(addr, new_user, new_domain)
if new_user then
addr.user = new_user
end
if new_domain then
addr.domain = new_domain
end
if addr.domain then
addr.addr = string.format('%s@%s', addr.user, addr.domain)
else
addr.addr = string.format('%s@', addr.user)
end
if addr.name and #addr.name > 0 then
addr.raw = string.format('"%s" <%s>', addr.name, addr.addr)
else
addr.raw = string.format('<%s>', addr.addr)
end
end
local function check_gmail(addr)
local nu, tags, nd = check_gmail_user(addr)
if nu then
return nu, tags, nd
end
return nil
end
local function check_googlemail(addr)
local nd = 'gmail.com'
local nu, tags = check_gmail_user(addr)
if nu then
return nu, tags, nd
end
return nil, nil, nd
end
local specific_domains = {
['gmail.com'] = check_gmail,
['googlemail.com'] = check_googlemail,
}
if email_addr then
if email_addr.domain and specific_domains[email_addr.domain] then
local nu, tags, nd = specific_domains[email_addr.domain](email_addr)
if nu or nd then
set_addr(email_addr, nu, nd)
return nu, tags
end
else
local nu, tags, nd = check_address(email_addr)
if nu or nd then
set_addr(email_addr, nu, nd)
return nu, tags
end
end
return nil
end
end
exports.is_rspamc_or_controller = function(task)
local ua = task:get_request_header('User-Agent') or ''
local pwd = task:get_request_header('Password')
local is_rspamc = false
if tostring(ua) == 'rspamc' or pwd then is_rspamc = true end
return is_rspamc
end
local unpack_function = table.unpack or unpack
exports.unpack = function(t)
return unpack_function(t)
end
return exports

View File

@ -0,0 +1,723 @@
--[[
Copyright (c) 2011-2017, Vsevolod Stakhov <vsevolod@highsecure.ru>
Copyright (c) 2016-2017, Andrew Lewis <nerf@judo.za.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
if confighelp then
return
end
-- A plugin that implements ratelimits using redis
local E, settings = {}, {}
local N = 'ratelimit'
-- Senders that are considered as bounce
local bounce_senders = {'postmaster', 'mailer-daemon', '', 'null', 'fetchmail-daemon', 'mdaemon'}
-- Do not check ratelimits for these recipients
local whitelisted_rcpts = {'postmaster', 'mailer-daemon'}
local whitelisted_ip
local whitelisted_user
local max_rcpt = 5
local redis_params
local ratelimit_symbol
-- Do not delay mail after 1 day
local use_ip_score = false
local rl_prefix = 'RL'
local ip_score_lower_bound = 10
local ip_score_ham_multiplier = 1.1
local ip_score_spam_divisor = 1.1
local limits_hash
local message_func = function(_, limit_type)
return string.format('Ratelimit "%s" exceeded', limit_type)
end
local rspamd_logger = require "rspamd_logger"
local rspamd_util = require "rspamd_util"
local rspamd_lua_utils = require "lua_util"
local lua_redis = require "lua_redis"
local fun = require "fun"
local user_keywords = {'user'}
local redis_script_sha
local redis_script = [[local bucket
local limited = false
local buckets = {}
local queue_id = table.remove(ARGV)
local now = table.remove(ARGV)
local argi = 0
for i = 1, #KEYS do
local key = KEYS[i]
local period = tonumber(ARGV[argi+1])
local limit = tonumber(ARGV[argi+2])
if not buckets[key] then
buckets[key] = {
max_period = period,
limits = { {period, limit} },
}
else
table.insert(buckets[key].limits, {period, limit})
if period > buckets[key].max_period then
buckets[key].max_period = period
end
end
argi = argi + 2
end
for k, v in pairs(buckets) do
local maxp = v.max_period
redis.call('ZREMRANGEBYSCORE', k, '-inf', now - maxp)
for _, lim in ipairs(v.limits) do
local period = lim[1]
local limit = lim[2]
local rate
if period == maxp then
rate = redis.call('ZCARD', k)
else
rate = redis.call('ZCOUNT', k, now - period, '+inf')
end
if rate and rate >= limit then
limited = true
bucket = k
end
end
redis.call('EXPIRE', k, maxp)
if limited then break end
end
if not limited then
for k in pairs(buckets) do
redis.call('ZADD', k, now, queue_id)
end
end
return {limited, bucket}]]
local redis_script_symbol = [[local limited = false
local buckets, results = {}, {}
local queue_id = table.remove(ARGV)
local now = table.remove(ARGV)
local argi = 0
for i = 1, #KEYS do
local key = KEYS[i]
local period = tonumber(ARGV[argi+1])
local limit = tonumber(ARGV[argi+2])
if not buckets[key] then
buckets[key] = {
max_period = period,
limits = { {period, limit} },
}
else
table.insert(buckets[key].limits, {period, limit})
if period > buckets[key].max_period then
buckets[key].max_period = period
end
end
argi = argi + 2
end
for k, v in pairs(buckets) do
local maxp = v.max_period
redis.call('ZREMRANGEBYSCORE', k, '-inf', now - maxp)
for _, lim in ipairs(v.limits) do
local period = lim[1]
local limit = lim[2]
local rate
if period == maxp then
rate = redis.call('ZCARD', k)
else
rate = redis.call('ZCOUNT', k, now - period, '+inf')
end
if rate then
local mult = 2 * math.tanh(rate / (limit * 2))
if mult >= 0.5 then
table.insert(results, {k, tostring(mult)})
end
end
end
redis.call('ZADD', k, now, queue_id)
redis.call('EXPIRE', k, maxp)
end
return results]]
local function load_scripts(cfg, ev_base)
local function rl_script_cb(err, data)
if err then
rspamd_logger.errx(cfg, 'Script loading failed: ' .. err)
elseif type(data) == 'string' then
redis_script_sha = data
end
end
local script
if ratelimit_symbol then
script = redis_script_symbol
else
script = redis_script
end
lua_redis.redis_make_request_taskless(
ev_base,
cfg,
redis_params,
nil, -- key
true, -- is write
rl_script_cb, --callback
'SCRIPT', -- command
{'LOAD', script}
)
end
local limit_parser
local function parse_string_limit(lim, no_error)
local function parse_time_suffix(s)
if s == 's' then
return 1
elseif s == 'm' then
return 60
elseif s == 'h' then
return 3600
elseif s == 'd' then
return 86400
end
end
local function parse_num_suffix(s)
if s == '' then
return 1
elseif s == 'k' then
return 1000
elseif s == 'm' then
return 1000000
elseif s == 'g' then
return 1000000000
end
end
local lpeg = require "lpeg"
if not limit_parser then
local digit = lpeg.R("09")
limit_parser = {}
limit_parser.integer =
(lpeg.S("+-") ^ -1) *
(digit ^ 1)
limit_parser.fractional =
(lpeg.P(".") ) *
(digit ^ 1)
limit_parser.number =
(limit_parser.integer *
(limit_parser.fractional ^ -1)) +
(lpeg.S("+-") * limit_parser.fractional)
limit_parser.time = lpeg.Cf(lpeg.Cc(1) *
(limit_parser.number / tonumber) *
((lpeg.S("smhd") / parse_time_suffix) ^ -1),
function (acc, val) return acc * val end)
limit_parser.suffixed_number = lpeg.Cf(lpeg.Cc(1) *
(limit_parser.number / tonumber) *
((lpeg.S("kmg") / parse_num_suffix) ^ -1),
function (acc, val) return acc * val end)
limit_parser.limit = lpeg.Ct(limit_parser.suffixed_number *
(lpeg.S(" ") ^ 0) * lpeg.S("/") * (lpeg.S(" ") ^ 0) *
limit_parser.time)
end
local t = lpeg.match(limit_parser.limit, lim)
if t and t[1] and t[2] and t[2] ~= 0 then
return t[2], t[1]
end
if not no_error then
rspamd_logger.errx(rspamd_config, 'bad limit: %s', lim)
end
return nil
end
local function resize_element(x_score, x_total, element)
local x_ip_score
if not x_total then x_total = 0 end
if x_total < ip_score_lower_bound or x_total <= 0 then
x_score = 1
else
x_score = x_score / x_total
end
if x_score > 0 then
x_ip_score = x_score / ip_score_spam_divisor
element = element * rspamd_util.tanh(2.718281 * x_ip_score)
elseif x_score < 0 then
x_ip_score = ((1 + (x_score * -1)) * ip_score_ham_multiplier)
element = element * x_ip_score
end
return element
end
--- Check whether this addr is bounce
local function check_bounce(from)
return fun.any(function(b) return b == from end, bounce_senders)
end
local custom_keywords = {}
local keywords = {
['ip'] = {
['get_value'] = function(task)
local ip = task:get_ip()
if ip and ip:is_valid() then return ip end
return nil
end,
},
['rip'] = {
['get_value'] = function(task)
local ip = task:get_ip()
if ip and ip:is_valid() and not ip:is_local() then return ip end
return nil
end,
},
['from'] = {
['get_value'] = function(task)
local from = task:get_from(0)
if ((from or E)[1] or E).addr then
return string.lower(from[1]['addr'])
end
return nil
end,
},
['bounce'] = {
['get_value'] = function(task)
local from = task:get_from(0)
if not ((from or E)[1] or E).user then
return '_'
end
if check_bounce(from[1]['user']) then return '_' else return nil end
end,
},
['asn'] = {
['get_value'] = function(task)
local asn = task:get_mempool():get_variable('asn')
if not asn then
return nil
else
return asn
end
end,
},
['user'] = {
['get_value'] = function(task)
local auser = task:get_user()
if not auser then
return nil
else
return auser
end
end,
},
['to'] = {
['get_value'] = function()
return '%s' -- 'to' is special
end,
},
}
local function dynamic_rate_key(task, rtype)
local key_t = {rl_prefix, rtype}
local key_keywords = rspamd_str_split(rtype, '_')
local have_to, have_user = false, false
for _, v in ipairs(key_keywords) do
if (custom_keywords[v] and type(custom_keywords[v]['condition']) == 'function') then
if not custom_keywords[v]['condition']() then return nil end
end
local ret
if custom_keywords[v] and type(custom_keywords[v]['get_value']) == 'function' then
ret = custom_keywords[v]['get_value'](task)
elseif keywords[v] and type(keywords[v]['get_value']) == 'function' then
ret = keywords[v]['get_value'](task)
end
if not ret then return nil end
for _, uk in ipairs(user_keywords) do
if v == uk then have_user = true end
if have_user then break end
end
if v == 'to' then have_to = true end
if type(ret) ~= 'string' then ret = tostring(ret) end
table.insert(key_t, ret)
end
if (not have_user) and task:get_user() then
return nil
end
if not have_to then
return table.concat(key_t, ":")
else
local rate_keys = {}
local rcpts = task:get_recipients(0)
if not ((rcpts or E)[1] or E).addr then
return nil
end
local key_s = table.concat(key_t, ":")
local total_rcpt = 0
for _, r in ipairs(rcpts) do
if r['addr'] and total_rcpt < max_rcpt then
local key_f = string.format(key_s, string.lower(r['addr']))
table.insert(rate_keys, key_f)
total_rcpt = total_rcpt + 1
end
end
return rate_keys
end
end
local function process_buckets(task, buckets)
if not buckets then return end
local function rl_redis_cb(err, data)
if err then
rspamd_logger.infox(task, 'got error while setting limit: %1', err)
end
if not data then return end
if data[1] == 1 then
rspamd_logger.infox(task,
'ratelimit "%s" exceeded',
data[2])
task:set_pre_result('soft reject',
message_func(task, data[2]))
end
end
local function rl_symbol_redis_cb(err, data)
if err then
rspamd_logger.infox(task, 'got error while setting limit: %1', err)
end
if not data then return end
for i, b in ipairs(data) do
task:insert_result(ratelimit_symbol, b[2], string.format('%s:%s:%s', i, b[1], b[2]))
end
end
local redis_cb = rl_redis_cb
if ratelimit_symbol then redis_cb = rl_symbol_redis_cb end
local args = {redis_script_sha, #buckets}
for _, bucket in ipairs(buckets) do
table.insert(args, bucket[2])
end
for _, bucket in ipairs(buckets) do
if use_ip_score then
local asn_score,total_asn,
country_score,total_country,
ipnet_score,total_ipnet,
ip_score, total_ip = task:get_mempool():get_variable('ip_score',
'double,double,double,double,double,double,double,double')
local key_keywords = rspamd_str_split(bucket[2], '_')
local has_asn, has_ip = false, false
for _, v in ipairs(key_keywords) do
if v == "asn" then has_asn = true end
if v == "ip" then has_ip = true end
if has_ip and has_asn then break end
end
if has_asn and not has_ip then
bucket[1][2] = resize_element(asn_score, total_asn, bucket[1][2])
elseif has_ip then
if total_ip and total_ip > ip_score_lower_bound then
bucket[1][2] = resize_element(ip_score, total_ip, bucket[1][2])
elseif total_ipnet and total_ipnet > ip_score_lower_bound then
bucket[1][2] = resize_element(ipnet_score, total_ipnet, bucket[1][2])
elseif total_asn and total_asn > ip_score_lower_bound then
bucket[1][2] = resize_element(asn_score, total_asn, bucket[1][2])
elseif total_country and total_country > ip_score_lower_bound then
bucket[1][2] = resize_element(country_score, total_country, bucket[1][2])
else
bucket[1][2] = resize_element(ip_score, total_ip, bucket[1][2])
end
end
end
table.insert(args, bucket[1][1])
table.insert(args, bucket[1][2])
end
table.insert(args, rspamd_util.get_time())
table.insert(args, task:get_queue_id() or task:get_uid())
local ret = rspamd_redis_make_request(task,
redis_params, -- connect params
nil, -- hash key
true, -- is write
redis_cb, --callback
'evalsha', -- command
args -- arguments
)
if not ret then
rspamd_logger.errx(task, 'got error connecting to redis')
end
end
local function ratelimit_cb(task)
if rspamd_lua_utils.is_rspamc_or_controller(task) then return end
local args = {}
-- Get initial task data
local ip = task:get_from_ip()
if ip and ip:is_valid() and whitelisted_ip then
if whitelisted_ip:get_key(ip) then
-- Do not check whitelisted ip
rspamd_logger.infox(task, 'skip ratelimit for whitelisted IP')
return
end
end
-- Parse all rcpts
local rcpts = task:get_recipients()
local rcpts_user = {}
if rcpts then
fun.each(function(r)
fun.each(function(type) table.insert(rcpts_user, r[type]) end, {'user', 'addr'})
end, rcpts)
if fun.any(
function(r)
if fun.any(function(w) return r == w end, whitelisted_rcpts) then return true end
end,
rcpts_user) then
rspamd_logger.infox(task, 'skip ratelimit for whitelisted recipient')
return
end
end
-- Get user (authuser)
if whitelisted_user then
local auser = task:get_user()
if whitelisted_user:get_key(auser) then
rspamd_logger.infox(task, 'skip ratelimit for whitelisted user')
return
end
end
local redis_keys = {}
local redis_keys_rev = {}
local function collect_redis_keys()
local function collect_cb(err, data)
if err then
rspamd_logger.errx(task, 'redis error: %1', err)
else
for i, d in ipairs(data) do
if type(d) == 'string' then
local plim, size = parse_string_limit(d)
if plim then
table.insert(args, {{plim, size}, redis_keys_rev[i]})
end
end
end
return process_buckets(task, args)
end
end
local params, method
if limits_hash then
params = {limits_hash, rspamd_lua_utils.unpack(redis_keys)}
method = 'HMGET'
else
method = 'MGET'
params = redis_keys
end
local requested_keys = rspamd_redis_make_request(task,
redis_params, -- connect params
nil, -- hash key
true, -- is write
collect_cb, --callback
method, -- command
params -- arguments
)
if not requested_keys then
rspamd_logger.errx(task, 'got error connecting to redis')
return process_buckets(task, args)
end
end
local rate_key
for k in pairs(settings) do
rate_key = dynamic_rate_key(task, k)
if rate_key then
if type(rate_key) == 'table' then
for _, rk in ipairs(rate_key) do
if type(settings[k]) == 'string' and
(custom_keywords[settings[k]] and type(custom_keywords[settings[k]]['get_limit']) == 'function') then
local res = custom_keywords[settings[k]]['get_limit'](task)
if type(res) == 'string' then res = {res} end
for _, r in ipairs(res) do
local plim, size = parse_string_limit(r, true)
if plim then
table.insert(args, {{plim, size}, rk})
else
local rkey = string.match(settings[k], 'redis:(.*)')
if rkey then
table.insert(redis_keys, rkey)
redis_keys_rev[#redis_keys] = rk
else
rspamd_logger.infox(task, "Don't know what to do with limit: %1", settings[k])
end
end
end
end
end
else
if type(settings[k]) == 'string' and
(custom_keywords[settings[k]] and type(custom_keywords[settings[k]]['get_limit']) == 'function') then
local res = custom_keywords[settings[k]]['get_limit'](task)
if type(res) == 'string' then res = {res} end
for _, r in ipairs(res) do
local plim, size = parse_string_limit(r, true)
if plim then
table.insert(args, {{plim, size}, rate_key})
else
local rkey = string.match(r, 'redis:(.*)')
if rkey then
table.insert(redis_keys, rkey)
redis_keys_rev[#redis_keys] = rate_key
else
rspamd_logger.infox(task, "Don't know what to do with limit: %1", settings[k])
end
end
end
elseif type(settings[k]) == 'table' then
for _, rl in ipairs(settings[k]) do
table.insert(args, {{rl[1], rl[2]}, rate_key})
end
elseif type(settings[k]) == 'string' then
local rkey = string.match(settings[k], 'redis:(.*)')
if rkey then
table.insert(redis_keys, rkey)
redis_keys_rev[#redis_keys] = rate_key
else
rspamd_logger.infox(task, "Don't know what to do with limit: %1", settings[k])
end
end
end
end
end
if redis_keys[1] then
return collect_redis_keys()
else
return process_buckets(task, args)
end
end
local opts = rspamd_config:get_all_opt(N)
if opts then
if opts['limit'] then
rspamd_logger.errx(rspamd_config, 'Legacy ratelimit config format no longer supported')
end
if opts['rates'] and type(opts['rates']) == 'table' then
-- new way of setting limits
fun.each(function(t, lim)
if type(lim) == 'table' then
settings[t] = {}
fun.each(function(l)
local plim, size = parse_string_limit(l)
if plim then
table.insert(settings[t], {plim, size})
end
end, lim)
elseif type(lim) == 'string' then
local plim, size = parse_string_limit(lim)
if plim then
settings[t] = { {plim, size} }
end
end
end, opts['rates'])
end
if opts['dynamic_rates'] and type(opts['dynamic_rates']) == 'table' then
fun.each(function(t, lim)
if type(lim) == 'string' then
settings[t] = lim
end
end, opts['dynamic_rates'])
end
local enabled_limits = fun.totable(fun.map(function(t)
return t
end, settings))
rspamd_logger.infox(rspamd_config, 'enabled rate buckets: [%1]', table.concat(enabled_limits, ','))
if opts['whitelisted_rcpts'] and type(opts['whitelisted_rcpts']) == 'string' then
whitelisted_rcpts = rspamd_str_split(opts['whitelisted_rcpts'], ',')
elseif type(opts['whitelisted_rcpts']) == 'table' then
whitelisted_rcpts = opts['whitelisted_rcpts']
end
if opts['whitelisted_ip'] then
whitelisted_ip = rspamd_map_add('ratelimit', 'whitelisted_ip', 'radix',
'Ratelimit whitelist ip map')
end
if opts['whitelisted_user'] then
whitelisted_user = rspamd_map_add('ratelimit', 'whitelisted_user', 'set',
'Ratelimit whitelist user map')
end
if opts['symbol'] then
-- We want symbol instead of pre-result
ratelimit_symbol = opts['symbol']
end
if opts['max_rcpt'] then
max_rcpt = tonumber(opts['max_rcpt'])
end
if opts['use_ip_score'] then
use_ip_score = true
local ip_score_opts = rspamd_config:get_all_opt('ip_score')
if ip_score_opts and ip_score_opts['lower_bound'] then
ip_score_lower_bound = ip_score_opts['lower_bound']
end
end
if opts['custom_keywords'] then
custom_keywords = dofile(opts['custom_keywords'])
end
if opts['user_keywords'] then
user_keywords = opts['user_keywords']
end
if opts['message_func'] then
message_func = assert(load(opts['message_func']))()
end
if opts['limits_hash'] then
limits_hash = opts['limits_hash']
end
redis_params = rspamd_parse_redis_server('ratelimit')
if not redis_params then
rspamd_logger.infox(rspamd_config, 'no servers are specified, disabling module')
else
local s = {
type = 'prefilter,nostat',
name = 'RATELIMIT_CHECK',
priority = 4,
callback = ratelimit_cb,
}
if use_ip_score then
s.type = 'normal'
end
if ratelimit_symbol then
s.name = ratelimit_symbol
end
local id = rspamd_config:register_symbol(s)
if use_ip_score then
rspamd_config:register_dependency(id, 'IP_SCORE')
end
for _, v in pairs(custom_keywords) do
if type(v) == 'table' and type(v['init']) == 'function' then
v['init']()
end
end
end
end
rspamd_config:add_on_load(function(cfg, ev_base, worker)
load_scripts(cfg, ev_base)
end)

View File

@ -0,0 +1 @@
settings = "http://172.22.1.251:8081/settings.php";

View File

@ -1,51 +1,48 @@
FROM ubuntu:xenial
MAINTAINER Andre Peters <andre.peters@servercow.de>
FROM debian:stretch-slim
LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
ENV DEBIAN_FRONTEND noninteractive
ARG DEBIAN_FRONTEND=noninteractive
ENV LC_ALL C
ENV GOSU_VERSION 1.9
RUN dpkg-divert --local --rename --add /sbin/initctl \
&& ln -sf /bin/true /sbin/initctl \
&& dpkg-divert --local --rename --add /usr/bin/ischroot \
&& ln -sf /bin/true /usr/bin/ischroot
RUN apt-get update \
&& apt-get install -y --no-install-recommends apt-transport-https \
# Prerequisites
RUN apt-get update && apt-get install -y --no-install-recommends \
apt-transport-https \
ca-certificates \
wget \
cron \
gnupg \
mysql-client \
supervisor \
syslog-ng \
syslog-ng-core \
supervisor \
mysql-client \
cron \
&& dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \
&& wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \
&& wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc" \
&& export GNUPGHOME="$(mktemp -d)" \
&& gpg --keyserver ha.pool.sks-keyservers.net --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4 \
&& gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu \
&& rm -r "$GNUPGHOME" /usr/local/bin/gosu.asc \
&& chmod +x /usr/local/bin/gosu \
&& gosu nobody true
syslog-ng-mod-redis \
dirmngr \
netcat \
psmisc \
wget \
&& rm -rf /var/lib/apt/lists/* \
&& dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \
&& wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \
&& chmod +x /usr/local/bin/gosu \
&& gosu nobody true
RUN apt-key adv --keyserver keys.gnupg.net --recv-key 0x810273C4 \
&& echo "deb http://packages.inverse.ca/SOGo/nightly/3/ubuntu/ xenial xenial" > /etc/apt/sources.list.d/sogo.list \
&& apt-get update \
&& apt-get -y --force-yes install sogo sogo-activesync
RUN mkdir /usr/share/doc/sogo \
&& touch /usr/share/doc/sogo/empty.sh \
&& apt-key adv --keyserver sks.labs.nic.cz --recv-key A04BE668 \
&& echo "deb http://www.axis.cz/linux/debian stretch sogo-v3" > /etc/apt/sources.list.d/sogo.list \
&& apt-get update && apt-get install -y --force-yes \
sogo \
sogo-activesync \
&& rm -rf /var/lib/apt/lists/* \
&& echo '* * * * * sogo /usr/sbin/sogo-ealarms-notify 2>/dev/null' > /etc/cron.d/sogo \
&& echo '* * * * * sogo /usr/sbin/sogo-tool expire-sessions 60' >> /etc/cron.d/sogo \
&& echo '0 0 * * * sogo /usr/sbin/sogo-tool update-autoreply -p /etc/sogo/sieve.creds' >> /etc/cron.d/sogo \
&& touch /etc/default/locale
RUN sed -i -E 's/^(\s*)system\(\);/\1unix-stream("\/dev\/log");/' /etc/syslog-ng/syslog-ng.conf
RUN echo '* * * * * sogo /usr/sbin/sogo-ealarms-notify' > /etc/cron.d/sogo
RUN echo '* * * * * sogo /usr/sbin/sogo-tool expire-sessions 60' >> /etc/cron.d/sogo
RUN echo '0 0 * * * sogo /usr/sbin/sogo-tool update-autoreply -p /etc/sogo/sieve.creds' >> /etc/cron.d/sogo
COPY ./reconf-domains.sh /
COPY ./bootstrap-sogo.sh /
COPY syslog-ng.conf /etc/syslog-ng/syslog-ng.conf
COPY supervisord.conf /etc/supervisor/supervisord.conf
#EXPOSE 20000
#EXPOSE 9191
#EXPOSE 9192
CMD exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
RUN rm -rf /tmp/* /var/tmp/*

View File

@ -1,7 +1,14 @@
#!/bin/bash
# Wait for MySQL to warm-up
while mysqladmin ping --host mysql --silent; do
while mysqladmin ping --host 172.22.1.250 --silent; do
# Wait until port becomes free and send sig
until ! nc -z sogo-mailcow 20000;
do
killall -TERM sogod
sleep 3
done
# Recreate view
@ -30,8 +37,6 @@ cat <<EOF > /var/lib/sogo/GNUstep/Defaults/sogod.plist
<string>mysql://${DBUSER}:${DBPASS}@mysql:3306/${DBNAME}/sogo_cache_folder</string>
<key>OCSEMailAlarmsFolderURL</key>
<string>mysql://${DBUSER}:${DBPASS}@mysql:3306/${DBNAME}/sogo_alarms_folder</string>
<key>DomainFieldName</key>
<string>domain</string>
<key>OCSFolderInfoURL</key>
<string>mysql://${DBUSER}:${DBPASS}@mysql:3306/${DBNAME}/sogo_folder_info</string>
<key>OCSSessionsFolderURL</key>
@ -63,6 +68,8 @@ while read line
</array>
<key>KindFieldName</key>
<string>kind</string>
<key>DomainFieldName</key>
<string>domain</string>
<key>MultipleBookingsFieldName</key>
<string>multiple_bookings</string>
<key>canAuthenticate</key>
@ -93,6 +100,6 @@ echo ' </dict>
chown sogo:sogo -R /var/lib/sogo/
chmod 600 /var/lib/sogo/GNUstep/Defaults/sogod.plist
sleep 99999
exec gosu sogo /usr/sbin/sogod
done

View File

@ -3,38 +3,35 @@ nodaemon=true
[program:syslog-ng]
command=/usr/sbin/syslog-ng --foreground --no-caps
redirect_stderr=true
autostart=true
stdout_syslog=true
[group:sogo-group]
programs=reconf-domains,sogo
[program:sogo]
command=/usr/sbin/sogod
user=sogo
autorestart=true
priority=20
[program:reconf-domains]
command=/reconf-domains.sh
autorestart=true
priority=10
[program:sogo-syslog]
command=/usr/bin/tail -f /var/log/syslog -f /var/log/sogo/sogo.log
stdout_logfile=/dev/fd/1
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autostart=true
priority=1
[program:cron]
command=/usr/sbin/cron -f
autorestart=true
priority=2
[program:sogo-webres]
command=/usr/bin/python -u -m SimpleHTTPServer 9192
directory=/usr/lib/GNUstep/SOGo/
user=sogo
autorestart=true
priority=4
[program:bootstrap-sogo]
command=/bootstrap-sogo.sh
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
priority=3
startretries=10
autorestart=true
stopwaitsecs=120
[inet_http_server]
port=9191

View File

@ -0,0 +1,54 @@
@version: 3.8
@include "scl.conf"
options {
chain_hostnames(off);
flush_lines(0);
use_dns(no);
use_fqdn(no);
owner("root"); group("adm"); perm(0640);
stats_freq(0);
bad_hostname("^gconfd$");
};
source s_src {
unix-stream("/dev/log");
internal();
};
source s_sogo {
pipe("/dev/sogo_log" owner(sogo) group(sogo));
};
destination d_stdout { pipe("/dev/stdout"); };
destination d_redis_ui_log {
redis(
host("redis-mailcow")
persist-name("redis1")
port(6379)
command("LPUSH" "SOGO_LOG" "$(format-json time=\"$S_UNIXTIME\" priority=\"$PRIORITY\" program=\"$PROGRAM\" message=\"$MESSAGE\")\n")
);
};
destination d_redis_f2b_channel {
redis(
host("redis-mailcow")
persist-name("redis2")
port(6379)
command("PUBLISH" "F2B_CHANNEL" "$MESSAGE")
);
};
destination d_redis_cleanup {
redis(
host("redis-mailcow")
persist-name("redis3")
port(6379)
command("LTRIM" "SOGO_LOG" "0" "9999")
);
};
log {
source(s_sogo);
destination(d_redis_ui_log);
destination(d_redis_f2b_channel);
destination(d_redis_cleanup);
};
log {
source(s_sogo);
source(s_src);
destination(d_stdout);
};

View File

@ -0,0 +1,19 @@
FROM alpine:3.6
LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
RUN apk add --update --no-cache \
curl \
unbound \
bash \
openssl \
drill \
&& curl -o /etc/unbound/root.hints https://www.internic.net/domain/named.cache \
&& chown root:unbound /etc/unbound \
&& chmod 775 /etc/unbound
EXPOSE 53/udp 53/tcp
COPY docker-entrypoint.sh /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]

View File

@ -0,0 +1,8 @@
#!/bin/bash
echo "Receiving anchor key..."
/usr/sbin/unbound-anchor -a /etc/unbound/trusted-key.key
echo "Receiving root hints..."
curl -#o /etc/unbound/root.hints https://www.internic.net/domain/named.cache
exec "$@"

View File

@ -1,6 +1,9 @@
# --------------------------------------------------------------------------
# Please create a file "extra.conf" for persistent overrides to dovecot.conf
# --------------------------------------------------------------------------
auth_mechanisms = plain login
#mail_debug = yes
log_path = /var/log/mail.log
log_path = syslog
disable_plaintext_auth = yes
# Uncomment on NFS share
#mmap_disable = yes
@ -10,9 +13,8 @@ disable_plaintext_auth = yes
login_log_format_elements = "user=<%u> method=%m rip=%r lip=%l mpid=%e %c %k"
mail_home = /var/vmail/%d/%n
mail_location = maildir:~/
mail_plugins = quota acl zlib antispam
auth_username_chars = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890.-_@
ssl_protocols = !SSLv3 !SSLv2
mail_plugins = quota acl zlib listescape #mail_crypt
ssl_protocols = !SSLv3
ssl_prefer_server_ciphers = yes
ssl_cipher_list = EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA256:EECDH:+CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!IDEA:!ECDSA:kEDH:CAMELLIA128-SHA:AES128-SHA
ssl_options = no_compression
@ -24,14 +26,20 @@ auth_master_user_separator = *
mail_prefetch_count = 30
passdb {
driver = passwd-file
args = /etc/dovecot/dovecot-master.passwd
args = /usr/local/etc/dovecot/dovecot-master.passwd
master = yes
pass = yes
}
passdb {
args = /etc/dovecot/sql/dovecot-mysql.conf
args = /usr/local/etc/dovecot/sql/dovecot-mysql.conf
driver = sql
}
# Set doveadm_password=your-secret-password in data/conf/dovecot/extra.conf (create if missing)
service doveadm {
inet_listener {
port = 12345
}
}
namespace inbox {
inbox = yes
location =
@ -131,7 +139,10 @@ namespace inbox {
auto = subscribe
special_use = \Junk
}
mailbox "Junk E-mail" {
mailbox "Junk-E-Mail" {
special_use = \Junk
}
mailbox "Junk E-Mail" {
special_use = \Junk
}
mailbox "Spam" {
@ -199,15 +210,15 @@ listen = *,[::]
ssl_cert = </etc/ssl/mail/cert.pem
ssl_key = </etc/ssl/mail/key.pem
userdb {
args = /etc/dovecot/sql/dovecot-mysql.conf
args = /usr/local/etc/dovecot/sql/dovecot-mysql.conf
driver = sql
}
protocol imap {
mail_plugins = quota imap_quota imap_acl acl zlib imap_zlib antispam
mail_plugins = quota imap_quota imap_acl acl zlib imap_zlib imap_sieve listescape #mail_crypt
}
protocol lmtp {
mail_plugins = quota sieve acl zlib
auth_socket_path = /var/run/dovecot/auth-master
mail_plugins = quota sieve acl zlib listescape #mail_crypt
auth_socket_path = /usr/local/var/run/dovecot/auth-master
}
protocol sieve {
managesieve_logout_format = bytes=%i/%o
@ -218,22 +229,32 @@ plugin {
acl = vfile
quota = dict:Userquota::proxy::sqlquota
quota_rule2 = Trash:storage=+100%%
antispam_backend = mailtrain
antispam_spam = Junk
antispam_trash = Trash
antispam_mail_sendmail = /usr/local/bin/rspamd-pipe
antispam_mail_spam = learn_spam
antispam_mail_notspam = learn_ham
# Do not complain about empty parameter
antispam_mail_sendmail_args = --blind
sieve = /var/vmail/sieve/%u.sieve
sieve_plugins = sieve_imapsieve sieve_extprograms
# From elsewhere to Spam folder
imapsieve_mailbox1_name = Junk
imapsieve_mailbox1_causes = COPY
imapsieve_mailbox1_before = file:/usr/local/lib/dovecot/sieve/report-spam.sieve
# END
# From Spam folder to elsewhere
imapsieve_mailbox2_name = *
imapsieve_mailbox2_from = Junk
imapsieve_mailbox2_causes = COPY
imapsieve_mailbox2_before = file:/usr/local/lib/dovecot/sieve/report-ham.sieve
# END
sieve_pipe_bin_dir = /usr/local/lib/dovecot/sieve
sieve_global_extensions = +vnd.dovecot.pipe +vnd.dovecot.execute
sieve_after = /var/vmail/sieve/global.sieve
sieve_max_script_size = 1M
sieve_quota_max_scripts = 0
sieve_quota_max_storage = 0
listescape_char = "\\"
#mail_crypt_global_private_key = </mail_crypt/ecprivkey.pem
#mail_crypt_global_public_key = </mail_crypt/ecpubkey.pem
#mail_crypt_save_version = 2
}
dict {
sqlquota = mysql:/etc/dovecot/sql/dovecot-dict-sql.conf
sqlquota = mysql:/usr/local/etc/dovecot/sql/dovecot-dict-sql.conf
}
remote 127.0.0.1 {
disable_plaintext_auth = no
@ -245,3 +266,4 @@ service imap-postlogin {
unix_listener imap-postlogin {
}
}
!include_try /usr/local/etc/dovecot/extra.conf

View File

@ -9,16 +9,13 @@ if header :contains "X-Spam-Flag" "YES" {
}
if allof (
envelope :detail :matches "to" "*",
header :contains "X-Moo-Tag" "YES",
mailboxexists "INBOX/${s}"
) {
fileinto "INBOX/${s}";
}
elsif allof (
envelope :detail :matches "to" "*",
header :contains "X-Moo-Tag" "YES"
) {
set :lower "s" "${1}";
fileinto :create "INBOX/${s}";
set :lower :upperfirst "tag" "${1}";
if mailboxexists "INBOX/${1}" {
fileinto "INBOX/${1}";
} else {
fileinto :create "INBOX/${tag}";
}
}

View File

@ -1,15 +0,0 @@
connect = "host=mysql dbname=mailcow user=mailcow password=mysafepasswd"
map {
pattern = priv/quota/storage
table = quota2
username_field = username
value_field = bytes
}
map {
pattern = priv/quota/messages
table = quota2
username_field = username
value_field = messages
}

View File

@ -1,6 +0,0 @@
driver = mysql
connect = "host=mysql dbname=mailcow user=mailcow password=mysafepasswd"
default_pass_scheme = SSHA256
password_query = SELECT password FROM mailbox WHERE username = '%u' AND domain IN (SELECT domain FROM domain WHERE domain='%d' AND active='1')
user_query = SELECT CONCAT('maildir:/var/vmail/',maildir) AS mail, 5000 AS uid, 5000 AS gid, concat('*:bytes=', quota) AS quota_rule FROM mailbox WHERE username = '%u' AND active = '1'
iterate_query = SELECT username FROM mailbox WHERE active='1';

View File

@ -1,5 +1,6 @@
server {
listen 8081;
listen [::]:8081;
index index.php index.html;
server_name _;
error_log /var/log/nginx/error.log;

View File

@ -1 +0,0 @@
listen ${HTTPS_PORT};

View File

@ -1,6 +1,17 @@
server_tokens off;
# includes to http {
proxy_cache_path /tmp levels=1:2 keys_zone=sogo:10m inactive=24h max_size=1g;
server_names_hash_bucket_size 64;
# }
map $http_x_forwarded_proto $client_req_scheme {
default $scheme;
https https;
}
server {
include /etc/nginx/conf.d/listen.active;
include /etc/nginx/conf.d/listen_ssl.active;
include /etc/nginx/mime.types;
charset utf-8;
override_charset on;
@ -10,17 +21,46 @@ server {
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA256:EECDH:+CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!IDEA:!ECDSA:kEDH:CAMELLIA128-SHA:AES128-SHA';
add_header Strict-Transport-Security "max-age=15768000; includeSubDomains";
#ssl_session_cache shared:SSL:50m;
#ssl_session_timeout 1d;
#ssl_session_tickets off;
#add_header X-Frame-Options SAMEORIGIN;
#add_header X-Content-Type-Options nosniff;
#add_header X-XSS-Protection "1; mode=block";
#add_header Referrer-Policy: no-referrer-when-downgrade;
#add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload";
ssl_ecdh_curve secp384r1;
index index.php index.html;
server_name _ autodiscover.* autoconfig.*;
include /etc/nginx/conf.d/server_name.active;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
absolute_redirect off;
root /web;
location = /principals/ {
rewrite ^ https://$host/SOGo/dav;
location ~ ^/api/v1/(.*)$ {
try_files $uri $uri/ /json_api.php?query=$1;
}
location ^~ /.well-known/acme-challenge/ {
allow all;
default_type "text/plain";
}
# If behind reverse proxy, forwards the correct IP
set_real_ip_from 172.22.1.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
rewrite ^/.well-known/caldav$ /SOGo/dav/ permanent;
rewrite ^/.well-known/carddav$ /SOGo/dav/ permanent;
location ^~ /principals {
return 301 /SOGo/dav;
}
location ~ \.php$ {
@ -37,27 +77,28 @@ server {
fastcgi_read_timeout 1200;
}
rewrite ^(/save.+)$ /rspamd$1 last;
location /rspamd/ {
proxy_pass http://172.22.1.253:11334/;
proxy_set_header Host $host;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains";
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;
add_header X-XSS-Protection "1; mode=block";
proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
}
location ^~ /inc/init.sql {
deny all;
location ~* ^/Autodiscover/Autodiscover.xml {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass phpfpm:9000;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
try_files /autodiscover.php =404;
}
if ($host ~* autodiscover\.(.*)) {
rewrite ^(.*) /autodiscover.php last;
}
if ($host ~* autoconfig\.(.*)) {
rewrite ^(.*) /autoconfig.php last;
location ~ /(?:m|M)ail/(?:c|C)onfig-v1.1.xml {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass phpfpm:9000;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
try_files /autoconfig.php =404;
}
location ^~ /Microsoft-Server-ActiveSync {
@ -72,41 +113,44 @@ server {
proxy_busy_buffers_size 64k;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header Host $http_host;
proxy_set_header x-webobjects-server-protocol HTTP/1.0;
proxy_set_header x-webobjects-remote-host $remote_addr;
proxy_set_header x-webobjects-server-name $server_name;
proxy_set_header x-webobjects-server-url $scheme://$host:$server_port;
proxy_set_header x-webobjects-server-url $client_req_scheme://$http_host;
proxy_set_header x-webobjects-server-port $server_port;
client_body_buffer_size 128k;
client_max_body_size 100m;
client_max_body_size 0;
}
location ^~ /SOGo {
proxy_pass http://172.22.1.252:20000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header Host $http_host;
proxy_set_header x-webobjects-server-protocol HTTP/1.0;
proxy_set_header x-webobjects-remote-host $remote_addr;
proxy_set_header x-webobjects-server-name $server_name;
proxy_set_header x-webobjects-server-url $scheme://$host:$server_port;
proxy_set_header x-webobjects-server-url $client_req_scheme://$http_host;
proxy_set_header x-webobjects-server-port $server_port;
#proxy_connect_timeout 90;
#proxy_send_timeout 90;
#proxy_read_timeout 90;
#proxy_buffer_size 4k;
#proxy_buffers 4 32k;
#proxy_busy_buffers_size 64k;
#proxy_temp_file_write_size 64k;
client_body_buffer_size 128k;
client_max_body_size 100m;
client_max_body_size 0;
break;
}
location /SOGo.woa/WebServerResources/ {
proxy_pass http://172.22.1.252:9192/WebServerResources/;
proxy_set_header Host $host;
proxy_set_header Host $http_host;
proxy_cache sogo;
proxy_cache_valid 200 1d;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
#alias /usr/lib/GNUstep/SOGo/WebServerResources/;
allow all;
}
location /.woa/WebServerResources/ {
proxy_pass http://172.22.1.252:9192/WebServerResources/;
proxy_set_header Host $http_host;
proxy_cache sogo;
proxy_cache_valid 200 1d;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
@ -116,7 +160,7 @@ server {
location /SOGo/WebServerResources/ {
proxy_pass http://172.22.1.252:9192/WebServerResources/;
proxy_set_header Host $host;
proxy_set_header Host $http_host;
proxy_cache sogo;
proxy_cache_valid 200 1d;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
@ -126,7 +170,154 @@ server {
location (^/SOGo/so/ControlPanel/Products/[^/]*UI/Resources/.*\.(jpg|png|gif|css|js)$ {
proxy_pass http://172.22.1.252:9192/$1.SOGo/Resources/$2;
proxy_set_header Host $host;
proxy_set_header Host $http_host;
proxy_cache sogo;
proxy_cache_valid 200 1d;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
#alias /usr/lib/GNUstep/SOGo/$1.SOGo/Resources/$2;
}
}
server {
include /etc/nginx/conf.d/listen_plain.active;
include /etc/nginx/mime.types;
charset utf-8;
override_charset on;
index index.php index.html;
include /etc/nginx/conf.d/server_name.active;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
absolute_redirect off;
root /web;
location ~ ^/api/v1/(.*)$ {
try_files $uri $uri/ /json_api.php?query=$1;
}
location ^~ /.well-known/acme-challenge/ {
allow all;
default_type "text/plain";
}
# If behind reverse proxy, forwards the correct IP
set_real_ip_from 172.22.1.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
rewrite ^/.well-known/caldav$ /SOGo/dav/ permanent;
rewrite ^/.well-known/carddav$ /SOGo/dav/ permanent;
location ^~ /principals {
return 301 /SOGo/dav;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass phpfpm:9000;
fastcgi_index index.php;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PHP_VALUE "max_execution_time = 1200
max_input_time = 1200
memory_limit = 64M";
fastcgi_read_timeout 1200;
}
location /rspamd/ {
proxy_pass http://172.22.1.253:11334/;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
}
location ~* ^/Autodiscover/Autodiscover.xml {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass phpfpm:9000;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
try_files /autodiscover.php =404;
}
location ~ /(?:m|M)ail/(?:c|C)onfig-v1.1.xml {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass phpfpm:9000;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
try_files /autoconfig.php =404;
}
location ^~ /Microsoft-Server-ActiveSync {
proxy_pass http://172.22.1.252:20000/SOGo/Microsoft-Server-ActiveSync;
proxy_connect_timeout 1000;
proxy_next_upstream timeout error;
proxy_send_timeout 1000;
proxy_read_timeout 1000;
proxy_buffer_size 8k;
proxy_buffers 4 32k;
proxy_temp_file_write_size 64k;
proxy_busy_buffers_size 64k;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header x-webobjects-server-protocol HTTP/1.0;
proxy_set_header x-webobjects-remote-host $remote_addr;
proxy_set_header x-webobjects-server-name $server_name;
proxy_set_header x-webobjects-server-url $client_req_scheme://$http_host;
proxy_set_header x-webobjects-server-port $server_port;
client_body_buffer_size 128k;
client_max_body_size 0;
}
location ^~ /SOGo {
proxy_pass http://172.22.1.252:20000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header x-webobjects-server-protocol HTTP/1.0;
proxy_set_header x-webobjects-remote-host $remote_addr;
proxy_set_header x-webobjects-server-name $server_name;
proxy_set_header x-webobjects-server-url $client_req_scheme://$http_host;
proxy_set_header x-webobjects-server-port $server_port;
client_body_buffer_size 128k;
client_max_body_size 0;
break;
}
location /SOGo.woa/WebServerResources/ {
proxy_pass http://172.22.1.252:9192/WebServerResources/;
proxy_set_header Host $http_host;
proxy_cache sogo;
proxy_cache_valid 200 1d;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
#alias /usr/lib/GNUstep/SOGo/WebServerResources/;
allow all;
}
location /.woa/WebServerResources/ {
proxy_pass http://172.22.1.252:9192/WebServerResources/;
proxy_set_header Host $http_host;
proxy_cache sogo;
proxy_cache_valid 200 1d;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
#alias /usr/lib/GNUstep/SOGo/WebServerResources/;
allow all;
}
location /SOGo/WebServerResources/ {
proxy_pass http://172.22.1.252:9192/WebServerResources/;
proxy_set_header Host $http_host;
proxy_cache sogo;
proxy_cache_valid 200 1d;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
#alias /usr/lib/GNUstep/SOGo/WebServerResources/;
allow all;
}
location (^/SOGo/so/ControlPanel/Products/[^/]*UI/Resources/.*\.(jpg|png|gif|css|js)$ {
proxy_pass http://172.22.1.252:9192/$1.SOGo/Resources/$2;
proxy_set_header Host $http_host;
proxy_cache sogo;
proxy_cache_valid 200 1d;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;

View File

@ -0,0 +1,2 @@
listen ${HTTP_PORT};
listen [::]:${HTTP_PORT};

View File

@ -0,0 +1,2 @@
listen ${HTTPS_PORT} http2;
listen [::]:${HTTPS_PORT} http2;

View File

@ -0,0 +1 @@
server_name ${MAILCOW_HOSTNAME} autodiscover.* autoconfig.*;

View File

@ -1 +0,0 @@
addNTA("mailcow-network", "nta for local")

View File

@ -1,41 +0,0 @@
allow-from=127.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, 10.0.0.0/8
config-dir=/etc/powerdns
daemon=no
disable-syslog=yes
dnssec=process
dnssec-log-bogus=yes
dont-query=10.0.0.0/8, 100.64.0.0/10, 169.254.0.0/16, 192.168.0.0/16, 172.16.0.0/12, ::1/128, fc00::/7, fe80::/10, 0.0.0.0/8, 192.0.0.0/24, 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 240.0.0.0/4, ::/96, ::ffff:0:0/96, 100::/64, 2001:db8::/32
export-etc-hosts=off
# forward-zones=
forward-zones-recurse=mailcow-network.=127.0.0.11
local-address=0.0.0.0
local-port=53
loglevel=6
# lowercase-outgoing=no
lua-config-file=/etc/powerdns/pdns_custom.lua
# max-cache-entries=1000000
# max-cache-ttl=86400
# max-mthreads=2048
# max-negative-ttl=3600
# max-packetcache-entries=500000
# max-qperq=50
# max-tcp-clients=128
# max-tcp-per-client=0
# max-total-msec=7000
# minimum-ttl-override=0
# network-timeout=1500
# packetcache-servfail-ttl=60
# packetcache-ttl=3600
quiet=yes
# security-poll-suffix=secpoll.powerdns.com.
# serve-rfc1918=yes
# server-down-max-fails=64
# server-down-throttle-time=60
setgid=pdns
setuid=pdns
# spoof-nearmiss-max=20
# stack-size=200000
# threads=2
# trace=off
version-string=PowerDNS Recursor
webserver=no

View File

@ -9,7 +9,7 @@ smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_una
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 [fd4d:6169:6c63:6f77::]/64
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
@ -24,7 +24,7 @@ milter_default_action = accept
milter_protocol = 6
minimal_backoff_time = 300s
plaintext_reject_code = 550
postscreen_access_list = permit_mynetworks, cidr:/opt/postfix/conf/postscreen_access.cidr
postscreen_access_list = permit_mynetworks, cidr:/opt/postfix/conf/postscreen_access.cidr, tcp:127.0.0.1:10027
postscreen_bare_newline_enable = no
postscreen_blacklist_action = drop
postscreen_cache_cleanup_interval = 24h
@ -39,11 +39,11 @@ postscreen_greet_ttl = 2d
postscreen_greet_wait = 3s
postscreen_non_smtp_command_enable = no
postscreen_pipelining_enable = no
proxy_read_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_virtual_sender_acl.cf, proxy:mysql:/opt/postfix/conf/sql/mysql_tls_enforce_out_policy.cf, proxy:mysql:/opt/postfix/conf/sql/mysql_tls_enforce_in_policy.cf, $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $smtpd_sender_login_maps
proxy_read_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_virtual_sender_acl.cf, proxy:mysql:/opt/postfix/conf/sql/mysql_sender_dependent_default_transport_maps.cf, proxy:mysql:/opt/postfix/conf/sql/mysql_sasl_passwd_maps.cf, proxy:mysql:/opt/postfix/conf/sql/mysql_tls_enforce_in_policy.cf, $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $smtpd_sender_login_maps
queue_run_delay = 300s
relay_domains = proxy:mysql:/opt/postfix/conf/sql/mysql_virtual_relay_domain_maps.cf
relay_recipient_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_relay_recipient_maps.cf
sender_dependent_default_transport_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_tls_enforce_out_policy.cf
sender_dependent_default_transport_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_sender_dependent_default_transport_maps.cf
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_tls_cert_file = /etc/ssl/mail/cert.pem
smtp_tls_key_file = /etc/ssl/mail/key.pem
@ -83,11 +83,19 @@ virtual_alias_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_virtual_alias_maps.
virtual_gid_maps = static:5000
virtual_mailbox_base = /var/vmail/
virtual_mailbox_domains = proxy:mysql:/opt/postfix/conf/sql/mysql_virtual_domains_maps.cf
virtual_mailbox_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_virtual_mailbox_maps.cf, proxy:mysql:/opt/postfix/conf/sql/mysql_virtual_alias_domain_mailbox_maps.cf
virtual_mailbox_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_virtual_mailbox_maps.cf
virtual_minimum_uid = 104
virtual_transport = lmtp:inet:dovecot:24
virtual_uid_maps = static:5000
smtpd_milters = inet:rmilter:9900
non_smtpd_milters = inet:rmilter:9900
smtpd_milters = inet:rspamd:9900
non_smtpd_milters = inet:rspamd:9900
milter_mail_macros = i {mail_addr} {client_addr} {client_name} {auth_authen}
mydestination = localhost.localdomain, localhost
#content_filter=zeyple
# Prefere IPv4, useful for v4-only envs
smtp_address_preference = ipv4
smtp_sender_dependent_authentication = yes
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_sasl_passwd_maps.cf
smtp_sasl_security_options =
smtp_sasl_mechanism_filter = plain, login

View File

@ -16,6 +16,7 @@ smtp_enforced_tls unix - - n - - smtp
-o smtp_tls_security_level=encrypt
-o syslog_name=enforced-tls-smtp
-o smtp_delivery_status_filter=pcre:/opt/postfix/conf/smtp_dsn_filter
tlsproxy unix - - n - 0 tlsproxy
dnsblog unix - - n - 0 dnsblog
pickup fifo n - n 60 1 pickup
@ -43,3 +44,16 @@ anvil unix - - n - 1 anvil
scache unix - - n - 1 scache
maildrop unix - n n - - pipe flags=DRhu
user=vmail argv=/usr/bin/maildrop -d ${recipient}
zeyple unix - n n - - pipe
user=zeyple argv=/usr/local/bin/zeyple.py ${recipient}
127.0.0.1:10026 inet n - n - 10 smtpd
-o content_filter=
-o receive_override_options=no_unknown_recipient_checks,no_header_body_checks,no_milters
-o smtpd_helo_restrictions=
-o smtpd_client_restrictions=
-o smtpd_sender_restrictions=
-o smtpd_recipient_restrictions=permit_mynetworks,reject
-o mynetworks=127.0.0.0/8
-o smtpd_authorized_xforward_hosts=127.0.0.0/8
127.0.0.1:10027 inet n n n - 0 spawn user=nobody argv=/usr/local/bin/whitelist_forwardinghosts.sh

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT DISTINCT CASE WHEN '%d' IN (SELECT domain FROM domain WHERE relay_all_recipients=1 AND domain='%d' AND backupmx=1) THEN '%s' ELSE (SELECT goto FROM alias WHERE address='%s' AND active='1') END AS result;

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT IF( EXISTS( SELECT 'TLS_ACTIVE' FROM alias LEFT OUTER JOIN mailbox ON mailbox.username = alias.address WHERE (address='%s' OR address IN (SELECT CONCAT('%u', '@', target_domain) FROM alias_domain WHERE alias_domain='%d')) AND mailbox.tls_enforce_in = '1' AND mailbox.active = '1'), 'reject_plaintext_session', 'DUNNO') AS 'tls_enforce_in';

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT IF( EXISTS( SELECT 'TLS_ACTIVE' FROM alias LEFT OUTER JOIN mailbox ON mailbox.username = alias.address WHERE (address='%s' OR address IN (SELECT CONCAT('%u', '@', target_domain) FROM alias_domain WHERE alias_domain='%d')) AND mailbox.tls_enforce_out = '1' AND mailbox.active = '1'), 'smtp_enforced_tls:', 'DUNNO') AS 'tls_enforce_out';

View File

@ -1,6 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT goto FROM alias,alias_domain WHERE alias_domain.alias_domain = '%d' and alias.address = CONCAT('@', alias_domain.target_domain) AND alias.active = 1 AND alias_domain.active='1'

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT maildir FROM mailbox,alias_domain WHERE alias_domain.alias_domain = '%d' and mailbox.username = CONCAT('%u', '@', alias_domain.target_domain) AND mailbox.active = 1 AND alias_domain.active='1'

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT goto FROM alias,alias_domain WHERE alias_domain.alias_domain = '%d' and alias.address = CONCAT('%u', '@', alias_domain.target_domain) AND alias.active = 1 AND alias_domain.active='1'

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT goto FROM alias WHERE address='%s' AND active='1';

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT alias_domain from alias_domain WHERE alias_domain='%s' AND active='1' UNION SELECT domain FROM domain WHERE domain='%s' AND active = '1' AND backupmx = '0'

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = '1'

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT domain FROM domain WHERE domain='%s' AND backupmx = '1' AND active = '1'

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT goto FROM alias WHERE address='%s' AND active='1' AND domain IN(SELECT domain FROM domain WHERE domain='%d' AND active='1') UNION SELECT logged_in_as FROM sender_acl WHERE send_as='@%d' OR send_as='%s' OR send_as IN ( SELECT CONCAT ('@',target_domain) FROM alias_domain WHERE alias_domain = '%d') OR send_as IN ( SELECT CONCAT ('%u','@',target_domain) FROM alias_domain WHERE alias_domain = '%d' ) AND logged_in_as NOT IN (SELECT goto FROM alias WHERE address='%s') UNION SELECT goto FROM alias,alias_domain WHERE alias_domain.alias_domain = '%d' AND alias.address = CONCAT('%u','@',alias_domain.target_domain) AND alias.active ='1' AND alias_domain.active='1'

View File

@ -1,5 +0,0 @@
user = mailcow
password = mysafepasswd
hosts = mysql
dbname = mailcow
query = SELECT goto FROM spamalias WHERE address='%s' AND validity >= UNIX_TIMESTAMP()

View File

@ -1,42 +0,0 @@
bind_socket = inet:9900;
spamd {
servers = r:rspamd:11333;
connect_timeout = 1s;
results_timeout = 20s;
error_time = 10;
dead_time = 300;
maxerrors = 10;
reject_message = "Spam or virus message rejected due to high detection score";
whitelist = 127.0.0.1/32, [::1]/128;
spamd_soft_fail = yes;
rspamd_metric = "default";
extended_spam_headers = yes;
spam_header = "X-Spam-Flag";
spam_header_value = "YES";
};
redis {
servers_grey = redis:6379;
servers_limits = redis:6379;
servers_id = redis:6379;
id_prefix = "message_id.";
grey_prefix = "grey.";
white_prefix = "white.";
connect_timeout = 1s;
error_time = 10;
dead_time = 300;
maxerrors = 10;
};
tempdir = /tmp;
tempfiles_mode = 00600;
max_size = 20M;
strict_auth = yes;
use_dcc = no;
limits {
enable = false;
};
greylisting {
enable = false;
}
dkim {
enable = false;
};

View File

@ -0,0 +1 @@
1

View File

@ -0,0 +1,25 @@
local custom_keywords = {
['customrl'] = {},
}
function custom_keywords.customrl.get_value(task)
local rspamd_logger = require "rspamd_logger"
if task:has_symbol('DYN_RL') then
rspamd_logger.infox(rspamd_config, "task has a dynamic ratelimit symbol, processing...")
return "check"
else
rspamd_logger.infox(rspamd_config, "task has no dynamic ratelimit symbol, skipping...")
return
end
end
function custom_keywords.customrl.get_limit(task)
local rspamd_logger = require "rspamd_logger"
local dyn_rl_symbol = task:get_symbol("DYN_RL")
if dyn_rl_symbol then
local rl_value = dyn_rl_symbol[1].options[1]
rspamd_logger.infox(rspamd_config, "dynamic ratelimit symbol has option %s, returning...", rl_value)
return rl_value
end
end
-- returning custom keywords
return custom_keywords

View File

@ -1,22 +0,0 @@
<?php
ini_set('error_reporting', 0);
header('Content-Type: text/plain');
require_once "vars.inc.php";
$dsn = $database_type . ':host=' . $database_host . ';dbname=' . $database_name;
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $database_user, $database_pass, $opt);
$stmt = $pdo->query("SELECT `domain` FROM `domain`");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
while ($row = array_shift($rows)) {
echo strtolower(trim($row['domain'])) . PHP_EOL;
}
$stmt = $pdo->query("SELECT `alias_domain` FROM `alias_domain`");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
while ($row = array_shift($rows)) {
echo strtolower(trim($row['alias_domain'])) . PHP_EOL;
}
?>

View File

@ -0,0 +1,44 @@
<?php
header('Content-Type: text/plain');
ini_set('error_reporting', 0);
$redis = new Redis();
$redis->connect('redis-mailcow', 6379);
function in_net($addr, $net) {
$net = explode('/', $net);
if (count($net) > 1) {
$mask = $net[1];
}
$net = inet_pton($net[0]);
$addr = inet_pton($addr);
$length = strlen($net); // 4 for IPv4, 16 for IPv6
if (strlen($net) != strlen($addr)) {
return false;
}
if (!isset($mask)) {
$mask = $length * 8;
}
$addr_bin = '';
$net_bin = '';
for ($i = 0; $i < $length; ++$i) {
$addr_bin .= str_pad(decbin(ord(substr($addr, $i, $i+1))), 8, '0', STR_PAD_LEFT);
$net_bin .= str_pad(decbin(ord(substr($net, $i, $i+1))), 8, '0', STR_PAD_LEFT);
}
return substr($addr_bin, 0, $mask) == substr($net_bin, 0, $mask);
}
try {
foreach ($redis->hGetAll('WHITELISTED_FWD_HOST') as $host => $source) {
if (in_net($_GET['host'], $host)) {
echo '200 PERMIT';
exit;
}
}
echo '200 DUNNO';
}
catch (RedisException $e) {
echo '200 DUNNO';
exit;
}
?>

View File

@ -4,21 +4,105 @@ The match section performs AND operation on different matches: for example, if y
then the rule matches only when from AND rcpt match. For similar matches, the OR rule applies: if you have multiple rcpt matches,
then any of these will trigger the rule. If a rule is triggered then no more rules are matched.
*/
ini_set('error_reporting', '0');
header('Content-Type: text/plain');
require_once "vars.inc.php";
ini_set('error_reporting', 0);
$dsn = $database_type . ':host=' . $database_host . ';dbname=' . $database_name;
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $database_user, $database_pass, $opt);
try {
$pdo = new PDO($dsn, $database_user, $database_pass, $opt);
$stmt = $pdo->query("SELECT * FROM `filterconf`");
}
catch (PDOException $e) {
echo 'settings { }';
exit;
}
function parse_email($email) {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
$a = strrpos($email, '@');
return array('local' => substr($email, 0, $a), 'domain' => substr($email, $a));
}
function ucl_rcpts($object, $type) {
global $pdo;
if ($type == 'mailbox') {
// Standard aliases
$stmt = $pdo->prepare("SELECT `address` FROM `alias`
WHERE `goto` LIKE :object_goto
AND `address` NOT LIKE '@%'
AND `address` != :object_address");
$stmt->execute(array(
':object_goto' => '%' . $object . '%',
':object_address' => $object
));
$standard_aliases = $stmt->fetchAll(PDO::FETCH_ASSOC);
while ($row = array_shift($standard_aliases)) {
$local = parse_email($row['address'])['local'];
$domain = parse_email($row['address'])['domain'];
if (!empty($local) && !empty($domain)) {
$rcpt[] = '/' . $local . '\+.*' . $domain . '/i';
}
$rcpt[] = $row['address'];
}
// Aliases by alias domains
$stmt = $pdo->prepare("SELECT CONCAT(`local_part`, '@', `alias_domain`.`alias_domain`) AS `alias` FROM `mailbox`
LEFT OUTER JOIN `alias_domain` ON `mailbox`.`domain` = `alias_domain`.`target_domain`
WHERE `mailbox`.`username` = :object");
$stmt->execute(array(
':object' => $object
));
$by_domain_aliases = $stmt->fetchAll(PDO::FETCH_ASSOC);
array_filter($by_domain_aliases);
while ($row = array_shift($by_domain_aliases)) {
if (!empty($row['alias'])) {
$local = parse_email($row['alias'])['local'];
$domain = parse_email($row['alias'])['domain'];
if (!empty($local) && !empty($domain)) {
$rcpt[] = '/' . $local . '\+.*' . $domain . '/i';
}
$rcpt[] = $row['alias'];
}
}
// Mailbox self
$local = parse_email($row['object'])['local'];
$domain = parse_email($row['object'])['domain'];
if (!empty($local) && !empty($domain)) {
$rcpt[] = '/' . $local . '\+.*' . $domain . '/i';
}
$rcpt[] = $object;
}
elseif ($type == 'domain') {
// Domain self
$rcpt[] = '/.*@' . $object . '/i';
$stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
WHERE `target_domain` = :object");
$stmt->execute(array(':object' => $object));
$alias_domains = $stmt->fetchAll(PDO::FETCH_ASSOC);
array_filter($alias_domains);
while ($row = array_shift($alias_domains)) {
$rcpt[] = '/.*@' . $row['alias_domain'] . '/i';
}
}
if (!empty($rcpt)) {
return $rcpt;
}
return false;
}
?>
settings {
<?php
/*
// Start custom scores for users
*/
$stmt = $pdo->query("SELECT DISTINCT `object` FROM `filterconf` WHERE `option` = 'highspamlevel' OR `option` = 'lowspamlevel'");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
@ -26,45 +110,18 @@ while ($row = array_shift($rows)) {
$username_sane = preg_replace("/[^a-zA-Z0-9]+/", "", $row['object']);
?>
score_<?=$username_sane;?> {
priority = low;
priority = 4;
<?php
foreach (ucl_rcpts($row['object'], strpos($row['object'], '@') === FALSE ? 'domain' : 'mailbox') as $rcpt) {
?>
rcpt = "<?=$rcpt;?>";
<?php
}
$stmt = $pdo->prepare("SELECT `option`, `value` FROM `filterconf`
WHERE (`option` = 'highspamlevel' OR `option` = 'lowspamlevel')
AND `object`= :object");
$stmt->execute(array(':object' => $row['object']));
$spamscore = $stmt->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
$stmt = $pdo->prepare("SELECT GROUP_CONCAT(REPLACE(`value`, '*', '.*') SEPARATOR '|') AS `value` FROM `filterconf`
WHERE (`object`= :object OR `object`= :object_domain)
AND (`option` = 'blacklist_from' OR `option` = 'whitelist_from')");
$stmt->execute(array(':object' => $row['object'], ':object_domain' => substr(strrchr($row['object'], "@"), 1)));
$grouped_lists = $stmt->fetchAll(PDO::FETCH_COLUMN);
$value_sane = preg_replace("/\.\./", ".", (preg_replace("/\*/", ".*", $grouped_lists[0])));
?>
from = "/^((?!<?=$value_sane;?>).)*$/";
rcpt = "<?=$row['object'];?>";
<?php
$stmt = $pdo->prepare("SELECT `address` FROM `alias` WHERE `goto` = :object_goto AND `address` NOT LIKE '@%' AND `address` != :object_address");
$stmt->execute(array(':object_goto' => $row['object'], ':object_address' => $row['object']));
$rows_aliases_1 = $stmt->fetchAll(PDO::FETCH_ASSOC);
while ($row_aliases_1 = array_shift($rows_aliases_1)) {
?>
rcpt = "<?=$row_aliases_1['address'];?>";
<?php
}
$stmt = $pdo->prepare("SELECT CONCAT(`local_part`, '@', `alias_domain`.`alias_domain`) AS `aliases` FROM `mailbox`
LEFT OUTER JOIN `alias_domain` on `mailbox`.`domain` = `alias_domain`.`target_domain`
WHERE `mailbox`.`username` = :object");
$stmt->execute(array(':object' => $row['object']));
$rows_aliases_2 = $stmt->fetchAll(PDO::FETCH_ASSOC);
array_filter($rows_aliases_2);
while ($row_aliases_2 = array_shift($rows_aliases_2)) {
if (!empty($row_aliases_2['aliases'])) {
?>
rcpt = "<?=$row_aliases_2['aliases'];?>";
<?php
}
}
?>
apply "default" {
actions {
@ -95,56 +152,76 @@ while ($row = array_shift($rows)) {
$grouped_lists = $stmt->fetchAll(PDO::FETCH_COLUMN);
$value_sane = preg_replace("/\.\./", ".", (preg_replace("/\*/", ".*", $grouped_lists[0])));
?>
from = "/(<?=$value_sane;?>)/";
from = "/(<?=$value_sane;?>)/i";
<?php
if (!filter_var(trim($row['object']), FILTER_VALIDATE_EMAIL)) {
?>
priority = medium;
rcpt = "/.*@<?=$row['object'];?>/";
priority = 5;
<?php
$stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
WHERE `target_domain` = :object");
$stmt->execute(array(':object' => $row['object']));
$rows_domain_aliases = $stmt->fetchAll(PDO::FETCH_ASSOC);
array_filter($rows_domain_aliases);
while ($row_domain_aliases = array_shift($rows_domain_aliases)) {
foreach (ucl_rcpts($row['object'], strpos($row['object'], '@') === FALSE ? 'domain' : 'mailbox') as $rcpt) {
?>
rcpt = "/.*@<?=$row_domain_aliases['alias_domain'];?>/";
rcpt = "<?=$rcpt;?>";
<?php
}
}
else {
?>
priority = high;
rcpt = "<?=$row['object'];?>";
priority = 6;
<?php
}
$stmt = $pdo->prepare("SELECT `address` FROM `alias` WHERE `goto` = :object_goto AND `address` NOT LIKE '@%' AND `address` != :object_address");
$stmt->execute(array(':object_goto' => $row['object'], ':object_address' => $row['object']));
$rows_aliases_wl_1 = $stmt->fetchAll(PDO::FETCH_ASSOC);
array_filter($rows_aliases_wl_1);
while ($row_aliases_wl_1 = array_shift($rows_aliases_wl_1)) {
foreach (ucl_rcpts($row['object'], strpos($row['object'], '@') === FALSE ? 'domain' : 'mailbox') as $rcpt) {
?>
rcpt = "<?=$row_aliases_wl_1['address'];?>";
rcpt = "<?=$rcpt;?>";
<?php
}
$stmt = $pdo->prepare("SELECT CONCAT(`local_part`, '@', `alias_domain`.`alias_domain`) AS `aliases` FROM `mailbox`
LEFT OUTER JOIN `alias_domain` on `mailbox`.`domain` = `alias_domain`.`target_domain`
WHERE `mailbox`.`username` = :object");
$stmt->execute(array(':object' => $row['object']));
$rows_aliases_wl_2 = $stmt->fetchAll(PDO::FETCH_ASSOC);
array_filter($rows_aliases_wl_2);
while ($row_aliases_wl_2 = array_shift($rows_aliases_wl_2)) {
if (!empty($row_aliases_wl_2['aliases'])) {
?>
rcpt = "<?=$row_aliases_wl_2['aliases'];?>";
<?php
}
}
}
?>
apply "default" {
MAILCOW_MOO = -999.0;
MAILCOW_WHITE = -999.0;
}
symbols [
"MAILCOW_WHITE"
]
}
whitelist_header_<?=$username_sane;?> {
<?php
$stmt = $pdo->prepare("SELECT GROUP_CONCAT(REPLACE(`value`, '*', '.*') SEPARATOR '|') AS `value` FROM `filterconf`
WHERE `object`= :object
AND `option` = 'whitelist_from'");
$stmt->execute(array(':object' => $row['object']));
$grouped_lists = $stmt->fetchAll(PDO::FETCH_COLUMN);
$value_sane = preg_replace("/\.\./", ".", (preg_replace("/\*/", ".*", $grouped_lists[0])));
?>
request_header = {
"From" = "(<?=$value_sane;?>)";
}
<?php
if (!filter_var(trim($row['object']), FILTER_VALIDATE_EMAIL)) {
?>
priority = 5;
<?php
foreach (ucl_rcpts($row['object'], strpos($row['object'], '@') === FALSE ? 'domain' : 'mailbox') as $rcpt) {
?>
rcpt = "<?=$rcpt;?>";
<?php
}
}
else {
?>
priority = 6;
<?php
foreach (ucl_rcpts($row['object'], strpos($row['object'], '@') === FALSE ? 'domain' : 'mailbox') as $rcpt) {
?>
rcpt = "<?=$rcpt;?>";
<?php
}
}
?>
apply "default" {
MAILCOW_WHITE = -999.0;
}
symbols [
"MAILCOW_WHITE"
]
}
<?php
}
@ -167,58 +244,78 @@ while ($row = array_shift($rows)) {
$grouped_lists = $stmt->fetchAll(PDO::FETCH_COLUMN);
$value_sane = preg_replace("/\.\./", ".", (preg_replace("/\*/", ".*", $grouped_lists[0])));
?>
from = "/(<?=$value_sane;?>)/";
from = "/(<?=$value_sane;?>)/i";
<?php
if (!filter_var(trim($row['object']), FILTER_VALIDATE_EMAIL)) {
?>
priority = medium;
rcpt = "/.*@<?=$row['object'];?>/";
priority = 5;
<?php
$stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
WHERE `target_domain` = :object");
$stmt->execute(array(':object' => $row['object']));
$rows_domain_aliases = $stmt->fetchAll(PDO::FETCH_ASSOC);
array_filter($rows_domain_aliases);
while ($row_domain_aliases = array_shift($rows_domain_aliases)) {
foreach (ucl_rcpts($row['object'], strpos($row['object'], '@') === FALSE ? 'domain' : 'mailbox') as $rcpt) {
?>
rcpt = "/.*@<?=$row_domain_aliases['alias_domain'];?>/";
rcpt = "<?=$rcpt;?>";
<?php
}
}
else {
?>
priority = high;
rcpt = "<?=$row['object'];?>";
priority = 6;
<?php
}
$stmt = $pdo->prepare("SELECT `address` FROM `alias` WHERE `goto` = :object_goto AND `address` NOT LIKE '@%' AND `address` != :object_address");
$stmt->execute(array(':object_goto' => $row['object'], ':object_address' => $row['object']));
$rows_aliases_bl_1 = $stmt->fetchAll(PDO::FETCH_ASSOC);
array_filter($rows_aliases_bl_1);
while ($row_aliases_bl_1 = array_shift($rows_aliases_bl_1)) {
foreach (ucl_rcpts($row['object'], strpos($row['object'], '@') === FALSE ? 'domain' : 'mailbox') as $rcpt) {
?>
rcpt = "<?=$row_aliases_bl_1['address'];?>";
rcpt = "<?=$rcpt;?>";
<?php
}
$stmt = $pdo->prepare("SELECT CONCAT(`local_part`, '@', `alias_domain`.`alias_domain`) AS `aliases` FROM `mailbox`
LEFT OUTER JOIN `alias_domain` on `mailbox`.`domain` = `alias_domain`.`target_domain`
WHERE `mailbox`.`username` = :object");
$stmt->execute(array(':object' => $row['object']));
$rows_aliases_bl_2 = $stmt->fetchAll(PDO::FETCH_ASSOC);
array_filter($rows_aliases_bl_2);
while ($row_aliases_bl_2 = array_shift($rows_aliases_bl_2)) {
if (!empty($row_aliases_bl_2['aliases'])) {
?>
rcpt = "<?=$row_aliases_bl_2['aliases'];?>";
<?php
}
}
}
?>
apply "default" {
MAILCOW_MOO = 999.0;
MAILCOW_BLACK = 999.0;
}
symbols [
"MAILCOW_BLACK"
]
}
blacklist_header_<?=$username_sane;?> {
<?php
$stmt = $pdo->prepare("SELECT GROUP_CONCAT(REPLACE(`value`, '*', '.*') SEPARATOR '|') AS `value` FROM `filterconf`
WHERE `object`= :object
AND `option` = 'blacklist_from'");
$stmt->execute(array(':object' => $row['object']));
$grouped_lists = $stmt->fetchAll(PDO::FETCH_COLUMN);
$value_sane = preg_replace("/\.\./", ".", (preg_replace("/\*/", ".*", $grouped_lists[0])));
?>
request_header = {
"From" = "(<?=$value_sane;?>)";
}
<?php
if (!filter_var(trim($row['object']), FILTER_VALIDATE_EMAIL)) {
?>
priority = 5;
<?php
foreach (ucl_rcpts($row['object'], strpos($row['object'], '@') === FALSE ? 'domain' : 'mailbox') as $rcpt) {
?>
rcpt = "<?=$rcpt;?>";
<?php
}
}
else {
?>
priority = 6;
<?php
foreach (ucl_rcpts($row['object'], strpos($row['object'], '@') === FALSE ? 'domain' : 'mailbox') as $rcpt) {
?>
rcpt = "<?=$rcpt;?>";
<?php
}
}
?>
apply "default" {
MAILCOW_BLACK = 999.0;
}
symbols [
"MAILCOW_BLACK"
]
}
<?php
}
?>
}
}

View File

@ -1,22 +0,0 @@
<?php
ini_set('error_reporting', 0);
header('Content-Type: text/plain');
require_once "vars.inc.php";
$dsn = $database_type . ':host=' . $database_host . ';dbname=' . $database_name;
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $database_user, $database_pass, $opt);
$stmt = $pdo->query("SELECT `username` FROM `mailbox` WHERE `wants_tagged_subject` = '1'");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
while ($row = array_shift($rows)) {
echo strtolower(trim($row['username'])) . PHP_EOL;
}
$stmt = $pdo->query("SELECT CONCAT(mailbox.local_part, '@', alias_domain.alias_domain) as `tag_ad` FROM `mailbox` INNER JOIN `alias_domain` ON mailbox.domain = alias_domain.target_domain WHERE mailbox.wants_tagged_subject='1';");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
while ($row = array_shift($rows)) {
echo strtolower(trim($row['tag_ad'])) . PHP_EOL;
}
?>

View File

@ -1 +0,0 @@
../../../web/inc/vars.inc.php

View File

@ -0,0 +1,3 @@
<?php
require_once('../../../web/inc/vars.inc.php');
?>

View File

@ -0,0 +1,7 @@
clamav {
attachments_only = false;
symbol = "CLAM_VIRUS";
type = "clamav";
log_clean = true;
servers = "clamd:3310";
}

View File

@ -0,0 +1,30 @@
# If false, messages with empty envelope from are not signed
allow_envfrom_empty = false;
# If true, envelope/header domain mismatch is ignored
allow_hdrfrom_mismatch = false;
# If true, multiple from headers are allowed (but only first is used)
allow_hdrfrom_multiple = true;
# If true, username does not need to contain matching domain
allow_username_mismatch = false;
# If false, messages from authenticated users are not selected for signing
auth_only = true;
# Default path to key, can include '$domain' and '$selector' variables
path = "/data/dkim/keys/$domain.dkim";
# Default selector to use
selector = "dkim";
# If false, messages from local networks are not selected for signing
sign_local = true;
# Symbol to add when message is signed
symbol = "ARC_SIGNED";
# Whether to fallback to global config
try_fallback = true;
# Domain to use for DKIM signing: can be "header" or "envelope"
use_domain = "envelope";
# Whether to normalise domains to eSLD
use_esld = false;
# Whether to get keys from Redis
use_redis = true;
# Hash for DKIM keys in Redis
key_prefix = "DKIM_PRIV_KEYS";
# Selector map
selector_prefix = "DKIM_SELECTORS";

View File

@ -1,34 +0,0 @@
sign_condition =<<EOD
return function(task)
local smtp_from = task:get_from('smtp')
local mime_from = task:get_from('mime')
local rspamd_logger = require "rspamd_logger"
if smtp_from[1]['domain'] ~= nil and smtp_from[1]['domain'] ~= '' then
domain = smtp_from[1]['domain']
rspamd_logger.infox(task, "set domain found in smtp from field to %s", domain)
if not task:get_user() then
rspamd_logger.infox(task, "found domain in smtp header field, but user is not authenticated - skipped")
return false
end
elseif mime_from[1]['domain'] ~= nil and mime_from[1]['domain'] ~= '' then
domain = mime_from[1]['domain']
rspamd_logger.infox(task, "set domain found in mime from field to %s", domain)
else
rspamd_logger.infox(task, "cannot determine domain for dkim signing")
return false
end
local keyfile = io.open("/data/dkim/keys/" .. domain .. ".dkim")
if keyfile then
rspamd_logger.infox(task, "found dkim key file for domain %s", domain)
keyfile:close()
return {
key = "/data/dkim/keys/" .. domain .. ".dkim",
domain = domain,
selector = "dkim"
}
else
rspamd_logger.infox(task, "no key file for domain %s - skipped", domain)
end
return false
end
EOD;

View File

@ -0,0 +1,30 @@
# If false, messages with empty envelope from are not signed
allow_envfrom_empty = false;
# If true, envelope/header domain mismatch is ignored
allow_hdrfrom_mismatch = false;
# If true, multiple from headers are allowed (but only first is used)
allow_hdrfrom_multiple = true;
# If true, username does not need to contain matching domain
allow_username_mismatch = true;
# If false, messages from authenticated users are not selected for signing
auth_only = true;
# Default path to key, can include '$domain' and '$selector' variables
path = "/data/dkim/keys/$domain.dkim";
# Default selector to use
selector = "dkim";
# If false, messages from local networks are not selected for signing
sign_local = true;
# Symbol to add when message is signed
symbol = "DKIM_SIGNED";
# Whether to fallback to global config
try_fallback = true;
# Domain to use for DKIM signing: can be "header" or "envelope"
use_domain = "envelope";
# Whether to normalise domains to eSLD
use_esld = false;
# Whether to get keys from Redis
use_redis = true;
# Hash for DKIM keys in Redis
key_prefix = "DKIM_PRIV_KEYS";
# Selector map
selector_prefix = "DKIM_SELECTORS";

View File

@ -0,0 +1,22 @@
rules {
DKIM_FAIL {
action = "add header";
expression = "R_DKIM_REJECT & !MAILLIST & !MAILCOW_WHITE & !MAILCOW_BLACK";
require_action = ["no action", "greylist"];
}
VIRUS_FOUND {
action = "reject";
expression = "CLAM_VIRUS & !MAILCOW_WHITE";
honor_action = ["reject"];
}
WHITELIST_FORWARDING_HOST_NO_REJECT {
action = "add header";
expression = "WHITELISTED_FWD_HOST";
require_action = ["reject"];
}
WHITELIST_FORWARDING_HOST_NO_GREYLIST {
action = "no action";
expression = "WHITELISTED_FWD_HOST";
require_action = ["greylist", "soft reject"];
}
}

View File

@ -0,0 +1,39 @@
use = ["spam-header", "x-spamd-result", "x-rspamd-queue-id", "authentication-results"];
skip_local = false;
skip_authenticated = true;
routines {
spam-header {
header = "X-Spam-Flag";
value = "YES";
remove = 1;
}
authentication-results {
header = "Authentication-Results";
remove = 1;
spf_symbols {
pass = "R_SPF_ALLOW";
fail = "R_SPF_FAIL";
softfail = "R_SPF_SOFTFAIL";
neutral = "R_SPF_NEUTRAL";
temperror = "R_SPF_DNSFAIL";
none = "R_SPF_NA";
permerror = "R_SPF_PERMFAIL";
}
dkim_symbols {
pass = "R_DKIM_ALLOW";
fail = "R_DKIM_REJECT";
temperror = "R_DKIM_TEMPFAIL";
none = "R_DKIM_NA";
permerror = "R_DKIM_PERMFAIL";
}
dmarc_symbols {
pass = "DMARC_POLICY_ALLOW";
permerror = "DMARC_BAD_POLICY";
temperror = "DMARC_DNSFAIL";
none = "DMARC_NA";
reject = "DMARC_POLICY_REJECT";
softfail = "DMARC_POLICY_SOFTFAIL";
quarantine = "DMARC_POLICY_QUARANTINE";
}
}
}

View File

@ -0,0 +1,34 @@
# Extensions that are treated as 'bad'
# Number is score multiply factor
bad_extensions = {
scr = 4,
lnk = 4,
exe = 1,
jar = 2,
com = 4,
bat = 4,
ace = 4,
arj = 4,
cab = 3,
};
# Extensions that are particularly penalized for archives
bad_archive_extensions = {
pptx = 0.5,
docx = 0.5,
xlsx = 0.5,
pdf = 1.0,
jar = 3,
js = 0.5,
vbs = 7,
};
# Used to detect another archive in archive
archive_extensions = {
zip = 1,
arj = 1,
rar = 1,
ace = 1,
7z = 1,
cab = 1,
};

View File

@ -0,0 +1,22 @@
RCPT_MAILCOW_DOMAIN {
type = "rcpt";
filter = "email:domain"
map = "redis://DOMAIN_MAP"
}
RCPT_WANTS_SUBJECT_TAG {
type = "rcpt";
filter = "email:addr"
map = "redis://RCPT_WANTS_SUBJECT_TAG"
}
WHITELISTED_FWD_HOST {
type = "ip";
map = "redis://WHITELISTED_FWD_HOST"
}
KEEP_SPAM {
type = "ip";
map = "redis://KEEP_SPAM"
action = "accept";
}

View File

@ -0,0 +1,7 @@
timeout = 1.0;
symbol_bad_mx = "MX_INVALID";
symbol_no_mx = "MX_MISSING";
symbol_good_mx = "MX_GOOD";
expire = 86400;
key_prefix = "rmx";
enabled = true;

View File

@ -1,3 +1,9 @@
dns {
enable_dnssec = true;
enable_dnssec = true;
}
map_watch_interval = 15s;
dns {
timeout = 4s;
retransmits = 5;
}
disable_monitored = true;

View File

@ -1 +1,5 @@
# rspamd.conf.local
history_redis {}
worker "log_helper" {
count = 1;
}

View File

@ -7,69 +7,104 @@ rspamd_config.MAILCOW_AUTH = {
end
}
rspamd_config.MAILCOW_MOO = function (task)
return true
end
local modify_subject_map = rspamd_config:add_map({
url = 'http://nginx:8081/tags.php',
type = 'map',
description = 'Map of users to use subject tags for'
})
local auth_domain_map = rspamd_config:add_map({
url = 'http://nginx:8081/authoritative.php',
type = 'map',
description = 'Map of domains we are authoritative for'
})
rspamd_config.ADD_DELIMITER_TAG = {
rspamd_config:register_symbol({
name = 'TAG_MOO',
type = 'postfilter',
callback = function(task)
local util = require("rspamd_util")
local rspamd_logger = require "rspamd_logger"
local user_env_tagged = task:get_recipients(1)[1]['user']
local user_to_tagged = task:get_recipients(2)[1]['user']
local tagged_rcpt = task:get_symbol("TAGGED_RCPT")
local mailcow_domain = task:get_symbol("RCPT_MAILCOW_DOMAIN")
local domain = task:get_recipients(1)[1]['domain']
if tagged_rcpt and mailcow_domain then
local tag = tagged_rcpt[1].options[1]
rspamd_logger.infox("found tag: %s", tag)
local action = task:get_metric_action('default')
rspamd_logger.infox("metric action now: %s", action)
local user_env, tag_env = user_env_tagged:match("([^+]+)+(.*)")
local user_to, tag_to = user_to_tagged:match("([^+]+)+(.*)")
if action ~= 'no action' and action ~= 'greylist' then
rspamd_logger.infox("skipping tag handler for action: %s", action)
task:set_metric_action('default', action)
return true
end
local authdomain = auth_domain_map:get_key(domain)
local wants_subject_tag = task:get_symbol("RCPT_WANTS_SUBJECT_TAG")
if tag_env then
tag = tag_env
user = user_env
elseif tag_to then
tag = tag_to
user = user_env
end
if tag and authdomain then
rspamd_logger.infox("Domain %s is part of mailcow, start reading tag settings", domain)
local user_untagged = user .. '@' .. domain
rspamd_logger.infox("Querying tag settings for user %1", user_untagged)
if modify_subject_map:get_key(user_untagged) then
rspamd_logger.infox("User wants subject modified for tagged mail")
if wants_subject_tag then
rspamd_logger.infox("user wants subject modified for tagged mail")
local sbj = task:get_header('Subject')
if tag then
rspamd_logger.infox("Found tag %1, will modify subject header", tag)
new_sbj = '=?UTF-8?B?' .. tostring(util.encode_base64('[' .. tag .. '] ' .. sbj)) .. '?='
task:set_rmilter_reply({
remove_headers = {['Subject'] = 1},
add_headers = {['Subject'] = new_sbj}
})
end
new_sbj = '=?UTF-8?B?' .. tostring(util.encode_base64('[' .. tag .. '] ' .. sbj)) .. '?='
task:set_milter_reply({
remove_headers = {['Subject'] = 1},
add_headers = {['Subject'] = new_sbj}
})
else
rspamd_logger.infox("Add X-Moo-Tag header")
task:set_rmilter_reply({
task:set_milter_reply({
add_headers = {['X-Moo-Tag'] = 'YES'}
})
end
else
rspamd_logger.infox("Skip delimiter handling for untagged message or authenticated user")
end
return false
end
}
end,
priority = 11
})
rspamd_config:register_symbol({
name = 'DYN_RL_CHECK',
type = 'prefilter',
callback = function(task)
local util = require("rspamd_util")
local redis_params = rspamd_parse_redis_server('dyn_rl')
local rspamd_logger = require "rspamd_logger"
local envfrom = task:get_from(1)
local env_from_domain = envfrom[1].domain:lower() -- get smtp from domain in lower case
local env_from_addr = envfrom[1].addr:lower() -- get smtp from addr in lower case
local function redis_cb_user(err, data)
if err or type(data) ~= 'string' then
rspamd_logger.infox(rspamd_config, "dynamic ratelimit request for user %s returned invalid or empty data (\"%s\") or error (\"%s\") - trying dynamic ratelimit for domain...", env_from_addr, data, err)
local function redis_key_cb_domain(err, data)
if err or type(data) ~= 'string' then
rspamd_logger.infox(rspamd_config, "dynamic ratelimit request for domain %s returned invalid or empty data (\"%s\") or error (\"%s\")", env_from_domain, data, err)
else
rspamd_logger.infox(rspamd_config, "found dynamic ratelimit in redis for domain %s with value %s", env_from_domain, data)
task:insert_result('DYN_RL', 0.0, data)
end
end
local redis_ret_domain = rspamd_redis_make_request(task,
redis_params, -- connect params
env_from_domain, -- hash key
false, -- is write
redis_key_cb_domain, --callback
'HGET', -- command
{'RL_VALUE', env_from_domain} -- arguments
)
if not redis_ret_domain then
rspamd_logger.infox(rspamd_config, "cannot make request to load ratelimit for domain")
end
else
rspamd_logger.infox(rspamd_config, "found dynamic ratelimit in redis for user %s with value %s", env_from_addr, data)
task:insert_result('DYN_RL', 0.0, data)
end
end
local redis_ret_user = rspamd_redis_make_request(task,
redis_params, -- connect params
env_from_addr, -- hash key
false, -- is write
redis_cb_user, --callback
'HGET', -- command
{'RL_VALUE', env_from_addr} -- arguments
)
if not redis_ret_user then
rspamd_logger.infox(rspamd_config, "cannot make request to load ratelimit for user")
end
return true
end,
priority = 20
})

Some files were not shown because too many files have changed in this diff Show More