policyd-rate-limit-0.7.1/0000755000175000017500000000000012764505104016715 5ustar valentinvalentin00000000000000policyd-rate-limit-0.7.1/PKG-INFO0000644000175000017500000002313012764505104020011 0ustar valentinvalentin00000000000000Metadata-Version: 1.1 Name: policyd-rate-limit Version: 0.7.1 Summary: Postfix rate limit policy server implemented in Python3. Home-page: https://github.com/nitmir/policyd-rate-limit Author: Valentin Samir Author-email: valentin.samir@crans.org License: GPLv3 Download-URL: https://github.com/nitmir/policyd-rate-limit/releases/latest Description: Policyd rate limit ================== |travis| |coverage| |github_version| |pypi_version| |license| Postfix policyd server allowing to limit the number of mails accepted by postfix over several time periods, by sasl usernames and/or ip addresses. Installation ------------ First, create the user that will run the daemon:: adduser --system --group --home /run/policyd-rate-limit --no-create-home policyd-rate-limit Since version 0.6.0, the configuration file is written using the yaml, so you need the following package: * `pyyaml `_ (``sudo apt-get install python3-yaml`` on debian like systems) Depending of the backend storage you planning to use, you may need to install additional packages. (The default settings use the sqlite3 bakends and do not need extra packages). * `mysqldb `_ (``sudo apt-get install python3-mysqldb`` on debian like systems) for the mysql backend. * `psycopg2 `_ (``sudo apt-get install python3-psycopg2`` on debian like systems) fot the postgresql backend Install with pip:: sudo pip3 install policyd-rate-limit or from source code:: sudo make install This will install the ``policyd_rate_limit`` module, the ``policyd-rate-limit`` binary, copy the default config to ``/etc/policyd-rate-limit.conf`` if the file do not exists, copy an init script to ``/etc/init.d/policyd-rate-limit`` and an unit file to ``/etc/systemd/system/policyd-rate-limit.service``. After the installation, you may need to run ``sudo systemctl daemon-reload`` for make the unit file visible by systemd. You should run ``policyd-rate-limit --clean`` on a regular basis to delete old records from the database. It could be wise to put it in a daily cron, for example:: 0 0 * * * policyd-rate-limit /usr/local/bin/policyd-rate-limit --clean >/dev/null Settings -------- ``policyd-rate-limit`` search for its config first in ``~/.config/policyd-rate-limit.conf`` If not found, then in ``/etc/policyd-rate-limit.conf``, and if not found use the default config. * ``debug``: make ``policyd-rate-limit`` output logs to stderr. The default is ``True``. * ``user``: The user ``policyd-rate-limit`` will use to drop privileges. The default is ``"policyd-rate-limit"``. * ``group``: The group ``policyd-rate-limit`` will use to drop privileges. The defaut is ``"policyd-rate-limit"``. * ``pidfile``: path where the program will try to write its pid to. The default is ``"/var/run/policyd-rate-limit/policyd-rate-limit.pid"``. ``policyd-rate-limit`` will try to create the parent directory and chown it if it do not exists. * ``mysql_config``: The config to connect to a mysql server * ``pgsql_config``: The config to connect to a postgresql server * ``sqlite_config``: The config to connect to a sqlite3 database. * ``backend``: Which data backend to use. Possible values are ``0`` for sqlite3, ``1`` for mysql and ``2`` for postgresql. The default is ``0``, use the sqlite3 backend. * ``SOCKET``: The socket to bind to. Can be a path to an unix socket or a couple [ip, port]. The default is ``"/var/spool/postfix/ratelimit/policy"``. ``policyd-rate-limit`` will try to create the parent directory and chown it if it do not exists. * ``socket_permission``: Permissions on the unix socket (if unix socket used). The default is ``0o666``. * ``limits``: A list of couple [number of emails, number of seconds]. If one of the element of the list is exeeded (more than 'number of emails' on 'number of seconds' for an ip address or an sasl username), postfix will return a temporary failure. * ``limits_by_id``: A dictionnary of id -> limit list (see limits). Used to override limits and use custom limits for a particular id. Use an empty list for no limits for a particular id. Ids are sasl usernames or ip addresses. The default is ``{}``. * ``limit_by_sasl``: Apply limits by sasl usernames. The default is ``True``. * ``limit_by_ip``: Apply limits by ip addresses if sasl username is not found. The default is ``False``. * ``limited_networks``: A list of ip networks in cidr notation on which limits are applied. An empty list is equal to ``limit_by_ip = False``, put ``"0.0.0.0/0"`` and ``::/0`` for every ip addresses. * ``success_action``: If not limits are reach, which action postfix should do. The default is ``"dunno"``. See http://www.postfix.org/access.5.html for possible actions. * ``fail_action``: If a limit is reach, which action postfix should do. The default is ``"defer_if_permit Rate limit reach, retry later"``. * ``db_error_action`` : If we are unable to to contect the database backend, which action postfix should do. The default is ``"dunno"``. See http://www.postfix.org/access.5.html for possible actions. See http://www.postfix.org/access.5.html for possible actions. * ``config_file``: This parameter is automatically set to the path of the configuration file currently in use. You can call it conjunction with **--get-config** to known which configuration file is used. * ``report``: if ``True``, send a report to ``report_to`` about users reaching limits each time --clean is called. The default is ``False``. * ``report_from``: From who to send emails reports. It must be defined when ``report`` is ``True``. * ``report_to``: Address to send emails reports to. It must be defined when ``report`` is ``True``. * ``report_subject``: Subject of the report email. The default is ``"policyd-rate-limit report"``. * ``report_limits``: List of number of seconds from the limits list for which you want to be reported. The default is ``[86400]``. * ``report_only_if_needed``: Only send a report if some users have reach a reported limit. The default is ``True``. * ``smtp_server``: The smtp server to use to send emails ``["host", port]``. The default is ``["localhost", 25]``. * ``smtp_starttls``: Should we use starttls to send mails ? (you should set this to ``True`` if you use ``smtp_credentials``). The default is ``False``. * ``smtp_credentials``: Should we use credentials to connect to smtp_server ? if yes set ``["user", "password"]``, else ``null``. The default is ``null``. Postfix settings ---------------- For postfix 3.0 and later I recommend using the example below. It ensure that if policyd-rate-limit become unavailable for any reason, postfix will ignore it and keep accepting mail as if the rule was not here. I find it nice has in my opinion, policyd-rate-limit is a "non-critical" policy service. /etc/postfix/main.cf:: smtpd_recipient_restrictions = ..., check_policy_service { unix:ratelimit/policy, default_action=DUNNO }, ... On previous postfix versions, you must use: /etc/postfix/main.cf:: smtpd_recipient_restrictions = ..., check_policy_service unix:ratelimit/policy, ... .. |travis| image:: https://badges.genua.fr/travis/nitmir/policyd-rate-limit/master.svg :target: https://travis-ci.org/nitmir/policyd-rate-limit .. |coverage| image:: https://badges.genua.fr/local/coverage/?project=policyd-rate-limit :target: https://badges.genua.fr/local/coverage/policyd-rate-limit/ .. |pypi_version| image:: https://badges.genua.fr/pypi/v/policyd-rate-limit.svg :target: https://pypi.python.org/pypi/policyd-rate-limit .. |github_version| image:: https://badges.genua.fr/github/tag/nitmir/policyd-rate-limit.svg?label=github :target: https://github.com/nitmir/policyd-rate-limit/releases/latest .. |license| image:: https://badges.genua.fr/pypi/l/policyd-rate-limit.svg :target: https://www.gnu.org/licenses/gpl-3.0.html Keywords: Postfix,rate,limit,email Platform: UNKNOWN Classifier: Environment :: No Input/Output (Daemon) Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: POSIX Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications :: Email :: Mail Transport Agents Classifier: Topic :: Communications :: Email :: Filters policyd-rate-limit-0.7.1/docs/0000755000175000017500000000000012764505104017645 5ustar valentinvalentin00000000000000policyd-rate-limit-0.7.1/docs/policyd-rate-limit.8.rst0000644000175000017500000000643212763315175024270 0ustar valentinvalentin00000000000000================== policyd-rate-limit ================== ------------------------------- rate limiter SMTP policy daemon ------------------------------- :Author: Valentin Samir :Date: 2016-08-04 :Copyright: GPL-3 :Version: 3.8 :title_upper: policyd-rate-limit :Manual section: 8 :Manual group: policyd-rate-limit Synopsis ======== **policyd-rate-limit** [**-h**] [**--clean**] [**--get-config** *configname*] [**--file** *configpath*] Description =========== **policyd-rate-limit**)(8) is a SMTP policy daemon written in **python3**)(1) for **postfix**)(1). It keep track of the number of mails sent by sasl usernames and/or ip addresses over time sliding window. A configurable action (see **access**)(5)) is done then a user and/or ip address exceeds one or more configurable limits. Setup ===== For example, for postfix 3.0 and later, you can set in postfix **/etc/postfix/main.cf** configuration file:: smtpd_recipient_restrictions = ..., check_policy_service { unix:ratelimit/policy, default_action=DUNNO }, ... Postfix will ask policyd-rate-limit what to do on mail reception (success or fail action) and will accept mail if policyd-rate-limit become unavailable. On previous postfix versions, you must use:: smtpd_recipient_restrictions = ..., check_policy_service unix:ratelimit/policy, ... Options ======= **-h**, **--help** show this help message and exit **--clean** clean old records from the database **--get-config** *configname* return the value of the *configname* configuration parameter. You can get a value in a dictionary by using a dotted notation. For instance, for getting the key KEY in the dictionary DICT, you should use DICT.KEY for *configname*. You can call the configuration parameter *config_file* to known which configuration file is used. **-f**, **--file** path to a policyd-rate-limit configuration file Logging ======= Logging is output to stderr and redirected to **syslog**)(3) by systemd. Logs are produced only if the **debug** configuration parameter is set to True. Configuration ============= If the option **--file** is not specified, **policyd-rate-limit**)(8) try to read its configuration from the following path and choose the first existing file:: ~/.config/policyd-rate-limit.conf ~/.config/policyd-rate-limit.yaml /etc/policyd-rate-limit.conf /etc/policyd-rate-limit.yaml The .conf are the old configuration format. It was a python module and should not be used. The .yaml are the new configuration format using the YAML syntax. See YAML(3pm) for an overview of the format. See **policyd-rate-limit.yaml**)(5) for possible settings. Exit values =========== **0** Normal exit. **1** Only return then the option **--get-config** is used. Configuration parameter not found. **2** User or group set in the configuration file do not exists. **3** Another instance is already running **4** The configuration parameter SOCKET is malformed **5** Configuration file not found **6** Some error was raised during runtime **8** Error during cleaning See also ======== | **policyd-rate-limit.yaml**)(5): policyd-rate-limit configuration file | **master**)(5), Postfix master.cf file syntax | **access**)(5), Postfix SMTP access control table policyd-rate-limit-0.7.1/docs/policyd-rate-limit.yaml.5.rst0000644000175000017500000001223212763527543025225 0ustar valentinvalentin00000000000000======================= policyd-rate-limit.yaml ======================= ------------------------------------------- policyd-rate-limit configuration parameters ------------------------------------------- :Author: Valentin Samir :Date: 2016-08-04 :Copyright: GPL-3 :Version: 3.8 :title_upper: policyd-rate-limit.yaml :Manual section: 5 :Manual group: policyd-rate-limit Description =========== **policyd-rate-limit**)(8) was using a **python**)(1) style configuration file and not use a **yaml**)(3pm) file which is reads on startup. .conf files are the old python format confguration files and .yaml the new ones. Old style configuration files are deprecated and should not be used. If the **--file** option if not set, it searches for configuration files on the following paths:: ~/.config/policyd-rate-limit.conf ~/.config/policyd-rate-limit.yaml /etc/policyd-rate-limit.conf /etc/policyd-rate-limit.yaml and exits if not found. Settings ======== **debug** Make policyd-rate-limit output logs to stderr. The default is True. **user** The user policyd-rate-limit will use to drop privileges. The default is "policyd-rate-limit". **group** The group policyd-rate-limit will use to drop privileges. The default is "policyd-rate-limit". **pidfile** path where the program will try to write its pid to. The default is "/var/run/policyd-rate-limit/policyd-rate-limit.pid". policyd-rate-limit will try to create the parent directory and chown it if it do not exists. **mysql_config** The configuration to connect to a mysql server. It should be a dictionary of parameters to give to the MySQLdb.connect function. See the python3-mysqldb documentations. **pgsql_config** The configuration to connect to a postgresql server. It should be a dictionary of parameters to give to the psycopg2.connect function. See the python3-psycopg2 documentations. **sqlite_config** The configuration to connect to a sqlite3 database. It should be a dictionary of parameters to give to the sqlite3.connect function. See the python3 documentations. **backend** Which data backend to use. Possible values are 0 for sqlite3, 1 for mysql and 2 for postgresql. The default is 0, use the sqlite3 backend. **SOCKET** The socket to bind to. Can be a path to an unix socket or a couple [ip, port]. The default is "/var/spool/postfix/ratelimit/policy". policyd-rate-limit will try to create the parent directory and chown it if it do not exists. **socket_permission** Permissions on the unix socket (if unix socket used). The default is 0o666. **limits** A list of couple [number of emails, number of seconds]. If one of the element of the list is exceeded (more than 'number of emails' on 'number of seconds' for an ip address or an sasl username), postfix will return a temporary failure. **limits_by_id** A dictionnary of id -> limit list (see limits). Used to override limits and use custom limits for a particular id. Use an empty list for no limits for a particular id. Ids are sasl usernames or ip addresses. The default is {}. **limit_by_sasl** Apply limits by sasl usernames. The default is True. **limit_by_ip** Apply limits by ip addresses if sasl username is not found. The default is False. **limited_networks** A list of ip networks in cidr notation on which limits are applied. An empty list is equal to limit_by_ip = False, put "0.0.0.0/0" and ::/0 for every ip addresses. **success_action** If no limits are reach, which action postfix should do. The default is "dunno". See **access**)(5) for possible actions. **fail_action** If a limit is reach, which action postfix should do. The default is "defer_if_permit Rate limit reach, retry later". See **access**)(5) for possible actions. **db_error_action** If we are unable to to contect the database backend, which action postfix should do. The default is "dunno". See **access**)(5) for possible actions. **config_file** This parameter is automatically set to the path of the configuration file currently in use. You can call it in conjunction with **--get-config** to known which configuration file is used. **report** if True, send a report to **report_to** about users reaching limits each time --clean is called. The default is False. **report_from** From who to send emails reports. It must be defined when **report** is True. **report_to** Address to send emails reports to. It must be defined when **report** is True. **report_subject** Subject of the report email. The default is "policyd-rate-limit report". **report_limits** List of number of seconds from the limits list for which you want to be reported. The default is [86400]. **report_only_if_needed** Only send a report if some users have reach a reported limit. The default is True. **smtp_server** The smtp server to use to send emails ["host", port]. The default is ["localhost", 25]. **smtp_starttls** Should we use starttls to send mails ? (you should set this to True if you use **smtp_credentials**). The default is False. **smtp_credentials** Should we use credentials to connect to smtp_server ? if yes set ["user", "password"], else null. The default is null. See also ======== | **policyd-rate-limit**)(8) policyd-rate-limit-0.7.1/policyd-rate-limit0000755000175000017500000001262112764310751022357 0ustar valentinvalentin00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 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 version 3 for # more details. # # You should have received a copy of the GNU General Public License version 3 # along with this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # (c) 2015-2016 Valentin Samir import os import sys import argparse import signal from policyd_rate_limit.policyd import Policyd from policyd_rate_limit import utils from policyd_rate_limit.utils import config if __name__ == "__main__": # pragma: no branch parser = argparse.ArgumentParser() parser.add_argument("--clean", help="clean old records from the database", action="store_true") parser.add_argument( "--get-config", help="return the value of a config parameter", metavar='PARAMETER_NAME' ) parser.add_argument("--file", '-f', help="path to a config file", metavar='CONFIG_PATH') args = parser.parse_args() try: if args.file: config.setup(args.file) else: config.setup() except ValueError as error: sys.stderr.write("%s\n" % error) sys.exit(5) # if policyd-rate-limit was lauch by root, try creating piddir, socket dir and if used # sqlite3 database dir then, drop privileges if os.getuid() == 0: try: utils.make_directories() utils.drop_privileges() # if user/group from config do not exists, a ValueError is raised and we exit. except ValueError as error: sys.stderr.write("%s\n" % error) # continue running if asking for the value of a config param if not args.get_config: sys.exit(2) # ask for the value of a config param, print it and exit if args.get_config: try: sys.stdout.write(str(utils.get_config(args.get_config))) except (AttributeError): sys.stderr.write("%s not found\n" % args.get_config) sys.exit(1) # else we gonna need the database so we initialize it else: # do not lauch the daemon if no config file is found if not config.config_file: sys.exit(5) # we try to initialize the database. try: utils.database_init() # If initialization fail, lauch policyd-rate-limit anyway, we will try to initialize it # later, the database is maybe just not available right now. except Exception as error: sys.stderr.write("Fail to initialize database: %s\n" % error) # if database cleaning requested, remove old records and exit if args.clean: try: utils.clean() except ValueError as error: sys.stderr.write("%s\n" % error) sys.exit(8) # else we gonna lauch the policyd daemon else: # we check if policyd-rate-limit is not already running by lookig at config.pidfile try: # read the pid from pidfile (on clean exit policyd-rate-limit remote its pid file # so if it exists either policyd-rate-limit is already running or has crashed) if os.path.isfile(config.pidfile): with open(config.pidfile) as f: pid = int(f.read().strip()) try: # should raise OSError(3) if not process found and success if found os.kill(pid, 0) # no exception raised so the pid in pidfile is still running, we display a # error message and exit. sys.stderr.write( ( "policyd-rate-limit seems to be already running according to " "the pid in the file %s. Exiting.\n" ) % config.pidfile ) sys.exit(3) except OSError as error: # No such process if error.errno != 3: # pragma: no cover (should not happen) raise # unable to read the pid from pidfile, so we continue except (ValueError, OSError): pass try: # we try to write our pid. On failure a ValueError is raised utils.write_pidfile() try: p = Policyd() try: p.socket() except (ValueError, OSError) as error: sys.stderr.write("%s\n" % error) sys.exit(4) try: # exit upon SIGUSR1 reception. Used for coverage computation signal.signal(signal.SIGUSR1, utils.exit_signal_handler) p.run() except (KeyboardInterrupt, utils.Exit): pass finally: p.close_socket() finally: utils.remove_pidfile() except Exception as error: sys.stderr.write("%s\n" % error) sys.exit(6) policyd-rate-limit-0.7.1/LICENSE0000644000175000017500000010451412741446214017730 0ustar valentinvalentin00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . policyd-rate-limit-0.7.1/setup.cfg0000644000175000017500000000014512764505104020536 0ustar valentinvalentin00000000000000[metadata] description-file = README.rst [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 policyd-rate-limit-0.7.1/README.rst0000644000175000017500000001704112763651741020417 0ustar valentinvalentin00000000000000Policyd rate limit ================== |travis| |coverage| |github_version| |pypi_version| |license| Postfix policyd server allowing to limit the number of mails accepted by postfix over several time periods, by sasl usernames and/or ip addresses. Installation ------------ First, create the user that will run the daemon:: adduser --system --group --home /run/policyd-rate-limit --no-create-home policyd-rate-limit Since version 0.6.0, the configuration file is written using the yaml, so you need the following package: * `pyyaml `_ (``sudo apt-get install python3-yaml`` on debian like systems) Depending of the backend storage you planning to use, you may need to install additional packages. (The default settings use the sqlite3 bakends and do not need extra packages). * `mysqldb `_ (``sudo apt-get install python3-mysqldb`` on debian like systems) for the mysql backend. * `psycopg2 `_ (``sudo apt-get install python3-psycopg2`` on debian like systems) fot the postgresql backend Install with pip:: sudo pip3 install policyd-rate-limit or from source code:: sudo make install This will install the ``policyd_rate_limit`` module, the ``policyd-rate-limit`` binary, copy the default config to ``/etc/policyd-rate-limit.conf`` if the file do not exists, copy an init script to ``/etc/init.d/policyd-rate-limit`` and an unit file to ``/etc/systemd/system/policyd-rate-limit.service``. After the installation, you may need to run ``sudo systemctl daemon-reload`` for make the unit file visible by systemd. You should run ``policyd-rate-limit --clean`` on a regular basis to delete old records from the database. It could be wise to put it in a daily cron, for example:: 0 0 * * * policyd-rate-limit /usr/local/bin/policyd-rate-limit --clean >/dev/null Settings -------- ``policyd-rate-limit`` search for its config first in ``~/.config/policyd-rate-limit.conf`` If not found, then in ``/etc/policyd-rate-limit.conf``, and if not found use the default config. * ``debug``: make ``policyd-rate-limit`` output logs to stderr. The default is ``True``. * ``user``: The user ``policyd-rate-limit`` will use to drop privileges. The default is ``"policyd-rate-limit"``. * ``group``: The group ``policyd-rate-limit`` will use to drop privileges. The defaut is ``"policyd-rate-limit"``. * ``pidfile``: path where the program will try to write its pid to. The default is ``"/var/run/policyd-rate-limit/policyd-rate-limit.pid"``. ``policyd-rate-limit`` will try to create the parent directory and chown it if it do not exists. * ``mysql_config``: The config to connect to a mysql server * ``pgsql_config``: The config to connect to a postgresql server * ``sqlite_config``: The config to connect to a sqlite3 database. * ``backend``: Which data backend to use. Possible values are ``0`` for sqlite3, ``1`` for mysql and ``2`` for postgresql. The default is ``0``, use the sqlite3 backend. * ``SOCKET``: The socket to bind to. Can be a path to an unix socket or a couple [ip, port]. The default is ``"/var/spool/postfix/ratelimit/policy"``. ``policyd-rate-limit`` will try to create the parent directory and chown it if it do not exists. * ``socket_permission``: Permissions on the unix socket (if unix socket used). The default is ``0o666``. * ``limits``: A list of couple [number of emails, number of seconds]. If one of the element of the list is exeeded (more than 'number of emails' on 'number of seconds' for an ip address or an sasl username), postfix will return a temporary failure. * ``limits_by_id``: A dictionnary of id -> limit list (see limits). Used to override limits and use custom limits for a particular id. Use an empty list for no limits for a particular id. Ids are sasl usernames or ip addresses. The default is ``{}``. * ``limit_by_sasl``: Apply limits by sasl usernames. The default is ``True``. * ``limit_by_ip``: Apply limits by ip addresses if sasl username is not found. The default is ``False``. * ``limited_networks``: A list of ip networks in cidr notation on which limits are applied. An empty list is equal to ``limit_by_ip = False``, put ``"0.0.0.0/0"`` and ``::/0`` for every ip addresses. * ``success_action``: If not limits are reach, which action postfix should do. The default is ``"dunno"``. See http://www.postfix.org/access.5.html for possible actions. * ``fail_action``: If a limit is reach, which action postfix should do. The default is ``"defer_if_permit Rate limit reach, retry later"``. * ``db_error_action`` : If we are unable to to contect the database backend, which action postfix should do. The default is ``"dunno"``. See http://www.postfix.org/access.5.html for possible actions. See http://www.postfix.org/access.5.html for possible actions. * ``config_file``: This parameter is automatically set to the path of the configuration file currently in use. You can call it conjunction with **--get-config** to known which configuration file is used. * ``report``: if ``True``, send a report to ``report_to`` about users reaching limits each time --clean is called. The default is ``False``. * ``report_from``: From who to send emails reports. It must be defined when ``report`` is ``True``. * ``report_to``: Address to send emails reports to. It must be defined when ``report`` is ``True``. * ``report_subject``: Subject of the report email. The default is ``"policyd-rate-limit report"``. * ``report_limits``: List of number of seconds from the limits list for which you want to be reported. The default is ``[86400]``. * ``report_only_if_needed``: Only send a report if some users have reach a reported limit. The default is ``True``. * ``smtp_server``: The smtp server to use to send emails ``["host", port]``. The default is ``["localhost", 25]``. * ``smtp_starttls``: Should we use starttls to send mails ? (you should set this to ``True`` if you use ``smtp_credentials``). The default is ``False``. * ``smtp_credentials``: Should we use credentials to connect to smtp_server ? if yes set ``["user", "password"]``, else ``null``. The default is ``null``. Postfix settings ---------------- For postfix 3.0 and later I recommend using the example below. It ensure that if policyd-rate-limit become unavailable for any reason, postfix will ignore it and keep accepting mail as if the rule was not here. I find it nice has in my opinion, policyd-rate-limit is a "non-critical" policy service. /etc/postfix/main.cf:: smtpd_recipient_restrictions = ..., check_policy_service { unix:ratelimit/policy, default_action=DUNNO }, ... On previous postfix versions, you must use: /etc/postfix/main.cf:: smtpd_recipient_restrictions = ..., check_policy_service unix:ratelimit/policy, ... .. |travis| image:: https://badges.genua.fr/travis/nitmir/policyd-rate-limit/master.svg :target: https://travis-ci.org/nitmir/policyd-rate-limit .. |coverage| image:: https://badges.genua.fr/local/coverage/?project=policyd-rate-limit :target: https://badges.genua.fr/local/coverage/policyd-rate-limit/ .. |pypi_version| image:: https://badges.genua.fr/pypi/v/policyd-rate-limit.svg :target: https://pypi.python.org/pypi/policyd-rate-limit .. |github_version| image:: https://badges.genua.fr/github/tag/nitmir/policyd-rate-limit.svg?label=github :target: https://github.com/nitmir/policyd-rate-limit/releases/latest .. |license| image:: https://badges.genua.fr/pypi/l/policyd-rate-limit.svg :target: https://www.gnu.org/licenses/gpl-3.0.html policyd-rate-limit-0.7.1/setup.py0000755000175000017500000000436612764504413020445 0ustar valentinvalentin00000000000000#!/usr/bin/env python3 from setuptools import setup import os DESC = """Postfix rate limit policy server implemented in Python3.""" with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() data_files = [] def add_data_file(dir, file, check_dir=False, mkdir=False): path = os.path.join(dir, os.path.basename(file)) if not os.path.isfile(path): if not check_dir or mkdir or os.path.isdir(dir): if mkdir: try: os.mkdir(dir) except OSError: pass data_files.append((dir, [file])) # if install as root populate /etc if os.getuid() == 0: add_data_file("/etc", 'policyd_rate_limit/policyd-rate-limit.yaml') add_data_file('/etc/init.d', 'init/policyd-rate-limit') add_data_file( "/etc/systemd/system", 'init/policyd-rate-limit.service', check_dir=True ) # else use user .config dir else: conf_dir = os.path.expanduser("~/.config/") add_data_file(conf_dir, 'policyd_rate_limit/policyd-rate-limit.yaml', mkdir=True) setup( name='policyd-rate-limit', version='0.7.1', description=DESC, long_description=README, author='Valentin Samir', author_email='valentin.samir@crans.org', license='GPLv3', url='https://github.com/nitmir/policyd-rate-limit', download_url="https://github.com/nitmir/policyd-rate-limit/releases/latest", packages=['policyd_rate_limit', 'policyd_rate_limit.tests'], package_data={ 'policyd_rate_limit': [ 'policyd-rate-limit.conf', 'policyd-rate-limit.yaml', ] }, keywords=['Postfix', 'rate', 'limit', 'email'], scripts=['policyd-rate-limit'], data_files=data_files, classifiers=[ 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Communications :: Email :: Mail Transport Agents', 'Topic :: Communications :: Email :: Filters', ], install_requires=["PyYAML >= 3.11"], zip_safe=False, ) policyd-rate-limit-0.7.1/MANIFEST.in0000644000175000017500000000040012750614160020443 0ustar valentinvalentin00000000000000include LICENSE include README.rst include Makefile include init/policyd-rate-limit.service include init/policyd-rate-limit include docs/policyd-rate-limit.8.rst include docs/policyd-rate-limit.yaml.5.rst include policyd_rate_limit/policyd-rate-limit.yaml policyd-rate-limit-0.7.1/init/0000755000175000017500000000000012764505104017660 5ustar valentinvalentin00000000000000policyd-rate-limit-0.7.1/init/policyd-rate-limit.service0000644000175000017500000000035212741446214024753 0ustar valentinvalentin00000000000000[Unit] Description=Postfix policyd rate limiter After=syslog.target [Service] Type=simple ExecStart=/usr/local/bin/policyd-rate-limit KillSignal=SIGINT StandardOutput=syslog StandardError=syslog [Install] WantedBy=multi-user.target policyd-rate-limit-0.7.1/init/policyd-rate-limit0000755000175000017500000000344412741446760023332 0ustar valentinvalentin00000000000000#!/bin/sh ### BEGIN INIT INFO # Provides: policyd-rate-limit # Required-Start: $remote_fs $network $syslog # Required-Stop: $remote_fs $network $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Postfix policyd rate limiter ### END INIT INFO # 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 version 3 for # more details. # # You should have received a copy of the GNU General Public License version 3 # along with this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # (c) 2015 Valentin Samir DAEMON="/usr/local/bin/policyd-rate-limit" NAME="policyd-rate-limit" DESC="Postfix policyd rate limiter" PID="$($DAEMON --get-config pidfile)" [ -x $DAEMON ] || exit 0 . /lib/lsb/init-functions stoped(){ if [ -f $PID ]; then pid=`cat $PID` if ps -p $pid >/dev/null; then return 1 fi fi return 0 } start(){ if stoped; then log_daemon_msg "Starting $DESC" "$NAME" /sbin/start-stop-daemon --start --pidfile $PID -b --exec $DAEMON log_end_msg $? else log_action_msg "Already running: $NAME" fi } stop(){ if stoped; then log_action_msg "Not running: $NAME" else log_daemon_msg "Stopping $DESC" "$NAME" /sbin/start-stop-daemon --stop --pidfile $PID --retry 30 log_end_msg $? fi } status(){ status_of_proc -p "$PID" "$DAEMON" "$NAME" } case $1 in start) start ;; stop) stop ;; restart) stop && start ;; force-reload) stop && start ;; status) status ;; *) echo "Usage: $0 {start|stop|restart|force-reload|status}" >&2 exit 1 ;; esac exit $? policyd-rate-limit-0.7.1/policyd_rate_limit/0000755000175000017500000000000012764505104022571 5ustar valentinvalentin00000000000000policyd-rate-limit-0.7.1/policyd_rate_limit/utils.py0000644000175000017500000004555012763547610024323 0ustar valentinvalentin00000000000000# 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 version 3 for # more details. # # You should have received a copy of the GNU General Public License version 3 # along with this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # (c) 2015-2016 Valentin Samir # -*- mode: python; coding: utf-8 -*- import os import sys import threading import collections import ipaddress import time import imp import pwd import grp import warnings import smtplib import yaml from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from policyd_rate_limit.const import SQLITE_DB, MYSQL_DB, PGSQL_DB from policyd_rate_limit import config as default_config def ip_network(ip_str): try: return ipaddress.IPv4Network(ip_str) except ipaddress.AddressValueError: return ipaddress.IPv6Network(ip_str) class Exit(Exception): pass class Config(object): """Act as a config module, missing parameters fallbacks to default_config""" _config = None config_file = None database_is_initialized = False def __init__(self, config_file=None): if config_file is None: # search for config files in the following locations config_files = [ # will be deprecated in favor of .yaml file os.path.expanduser("~/.config/policyd-rate-limit.conf"), os.path.expanduser("~/.config/policyd-rate-limit.yaml"), # will be deprecated in favor of .yaml file "/etc/policyd-rate-limit.conf", "/etc/policyd-rate-limit.yaml", ] else: config_files = [config_file] for config_file in config_files: if os.path.isfile(config_file): try: # compatibility with old config style in a python module if config_file.endswith(".conf"): # pragma: no cover (deprecated) self._config = imp.load_source('config', config_file) warnings.warn( ( "New configuration use a .yaml file. " "Please migrate to it and delete you .conf file" ), stacklevel=3 ) cache_file = imp.cache_from_source(config_file) # remove the config pyc file try: os.remove(cache_file) except OSError: pass # remove the __pycache__ dir of the config pyc file if empty try: os.rmdir(os.path.dirname(cache_file)) except OSError: pass # new config file use yaml else: with open(config_file) as f: self._config = yaml.load(f) self.config_file = config_file break except PermissionError: pass # if not config file found, raise en error else: sys.stderr.write( "No config file found or bad permissions, searched for %s\n" % ( ", ".join(config_files), ) ) try: # pragma: no cover (deprecated) self.limited_networks = [ip_network(net) for net in self.limited_netword] warnings.warn( ( "The limited_netword config parameter is deprecated, please use " "limited_networks instead." ), stacklevel=3 ) except AttributeError: self.limited_networks = [ip_network(net) for net in self.limited_networks] def __getattr__(self, name): try: if self.config_file.endswith(".yaml"): ret = self._config[name] else: # pragma: no cover (deprecated) ret = getattr(self._config, name) # If an parameter is not defined in the config file, return its default value. except (AttributeError, KeyError): ret = getattr(default_config, name) if name == "SOCKET": if isinstance(ret, list): ret = tuple(ret) return ret class LazyConfig(object): """A lazy proxy to the Config class allowing to import config before it is initialized""" _config = None format_str = None def __getattr__(self, name): if self._config is None: raise RuntimeError("config is not initialized") return getattr(self._config, name) def setup(self, config_file=None): """initialize the config""" global cursor # initialize config self._config = Config(config_file) # make the cursor class function of the configured backend if config.backend == SQLITE_DB: cursor = make_cursor("sqlite_cursor", config.backend, config.sqlite_config) self.format_str = "?" elif config.backend == MYSQL_DB: cursor = make_cursor("mysql_cursor", config.backend, config.mysql_config) self.format_str = "%s" elif config.backend == PGSQL_DB: cursor = make_cursor("pgsql_cursor", config.backend, config.pgsql_config) self.format_str = "%s" else: raise ValueError("backend %s unknown" % config.backend) def make_directories(): """Create directory for pid and socket and chown if needed""" try: uid = pwd.getpwnam(config.user).pw_uid except KeyError: raise ValueError("User %s in config do not exists" % config.user) try: gid = grp.getgrnam(config.group).gr_gid except KeyError: raise ValueError("Group %s in config do not exists" % config.group) pid_dir = os.path.dirname(config.pidfile) if not os.path.exists(pid_dir): os.mkdir(pid_dir) if not os.listdir(pid_dir): os.chmod(pid_dir, 0o755) os.chown(pid_dir, uid, gid) if isinstance(config.SOCKET, str): socket_dir = os.path.dirname(config.SOCKET) if not os.path.exists(socket_dir): os.mkdir(socket_dir) if not os.listdir(socket_dir): os.chown(socket_dir, uid, gid) if config.backend == SQLITE_DB: try: db_dir = os.path.dirname(config.sqlite_config["database"]) if not os.path.exists(db_dir): os.mkdir(db_dir) if not os.listdir(db_dir): os.chmod(db_dir, 0o700) os.chown(db_dir, uid, gid) except KeyError: pass def drop_privileges(): """If current running use is root, drop privileges to user and group set in the config""" if os.getuid() != 0: # We're not root so, like, whatever dude return # Get the uid/gid from the name running_uid = pwd.getpwnam(config.user).pw_uid running_gid = grp.getgrnam(config.group).gr_gid # Remove group privileges os.setgroups([]) # Try setting the new uid/gid os.setgid(running_gid) os.setuid(running_uid) # Ensure a very conservative umask os.umask(0o077) def make_cursor(name, backend, config): """Create a cursor class usable as a context manager, binding to the backend selected""" if backend == MYSQL_DB: try: import MySQLdb except ImportError: raise ValueError( "You need to install the python3 module MySQLdb to use the mysql backend" ) methods = { '_db': collections.defaultdict(lambda: MySQLdb.connect(**config)), 'backend': MYSQL_DB, 'backend_module': MySQLdb, } elif backend == SQLITE_DB: import sqlite3 methods = { '_db': collections.defaultdict(lambda: sqlite3.connect(**config)), 'backend': SQLITE_DB, 'backend_module': sqlite3, } elif backend == PGSQL_DB: try: import psycopg2 except ImportError: raise ValueError( "You need to install the python3 module psycopg2 to use the postgresql backend" ) methods = { '_db': collections.defaultdict(lambda: psycopg2.connect(**config)), 'backend': PGSQL_DB, 'backend_module': psycopg2, } else: raise RuntimeError("backend %s unknown" % backend) newclass = type(name, (_cursor,), methods) return newclass class _cursor(object): """cursor template class""" backend = None backend_module = None @classmethod def get_db(cls): return cls._db[threading.current_thread()] @classmethod def set_db(cls, value): cls._db[threading.current_thread()] = value @classmethod def del_db(cls): try: cls._db[threading.current_thread()].close() except: pass try: del cls._db[threading.current_thread()] except KeyError: pass def __enter__(self): self.cur = self.get_db().cursor() if self.backend in [MYSQL_DB, PGSQL_DB]: try: if self.backend == MYSQL_DB: self.cur.execute("DO 0") else: self.cur.execute("SELECT 0") self.cur.fetchone() except self.backend_module.Error as error: # SQL server has gone away, probably a timeout, try to reconnect # else, query on the returned cursor will raise on exception if error.args[0] in [2002, 2003, 2006, 2013, 8000, 8001, 8003, 8004, 8006]: self.del_db() self.cur.close() self.cur = self.get_db().cursor() return self.cur def __exit__(self, exc_type, exc_value, traceback): self.cur.close() self.get_db().commit() def is_ip_limited(ip): """Check if ``ip`` is part of a network of ``config.limited_networks``""" try: ip = ipaddress.IPv4Address(ip) except ipaddress.AddressValueError: ip = ipaddress.IPv6Address(ip) for net in config.limited_networks: if ip in net: return True return False def print_fw(msg, length, filler=' ', align_left=True): msg = "%s" % msg if len(msg) > length: raise ValueError("%r must not be longer than %s" % (msg, length)) if align_left: return "%s%s" % (msg, filler * (length - len(msg))) else: return "%s%s" % (filler * (length - len(msg)), msg) def clean(): """Delete old records from the database""" max_delta = 0 for nb, delta in config.limits: max_delta = max(max_delta, delta) # remove old record older than 2*max_delta expired = int(time.time() - max_delta - max_delta) with cursor() as cur: cur.execute("DELETE FROM mail_count WHERE date <= %s" % config.format_str, (expired,)) print("%d records deleted" % cur.rowcount) # if report is True, generate a mail report if config.report and config.report_to: send_report(cur) # The mail report has been successfully send, flush limit_report cur.execute("DELETE FROM limit_report") try: if config.backend == PGSQL_DB: # setting autocommit to True disable the transations. This is needed to run VACUUM cursor.get_db().autocommit = True with cursor() as cur: if config.backend == PGSQL_DB: cur.execute("VACUUM ANALYZE") elif config.backend == SQLITE_DB: cur.execute("VACUUM") elif config.backend == MYSQL_DB: if config.report: cur.execute("OPTIMIZE TABLE mail_count, limit_report") else: cur.execute("OPTIMIZE TABLE mail_count") finally: if config.backend == PGSQL_DB: cursor.get_db().autocommit = False def send_report(cur): cur.execute("SELECT id, delta, hit FROM limit_report") # list to sort ids by hits report = list(cur.fetchall()) if not config.report_only_if_needed or report: if report: text = ["Below is the table of users who hit a limit since the last cleanup:", ""] # dist to groups deltas by ids report_d = collections.defaultdict(list) max_d = {'id': 2, 'delta': 5, 'hit': 3} for (id, delta, hit) in report: report_d[id].append((delta, hit)) max_d['id'] = max(max_d['id'], len(id)) max_d['delta'] = max(max_d['delta'], len(str(delta))) max_d['hit'] = max(max_d['hit'], len(str(hit))) # sort by hits report.sort(key=lambda x: x[2]) # table header text.append( "|%s|%s|%s|" % ( print_fw("id", max_d['id']), print_fw("delta", max_d['delta']), print_fw("hit", max_d['hit']) ) ) # table header/data separation text.append( "|%s+%s+%s|" % ( print_fw("", max_d['id'], filler='-'), print_fw("", max_d['delta'], filler='-'), print_fw("", max_d['hit'], filler='-') ) ) for (id, _, _) in report: # sort by delta report_d[id].sort() for (delta, hit) in report_d[id]: # add a table row text.append( "|%s|%s|%s|" % ( print_fw(id, max_d['id'], align_left=False), print_fw("%ss" % delta, max_d['delta'], align_left=False), print_fw(hit, max_d['hit'], align_left=False) ) ) else: text = ["No user hit a limit since the last cleanup"] text.extend(["", "-- ", "policyd-rate-limit"]) # Start building the mail report msg = MIMEMultipart() msg['Subject'] = config.report_subject or "" msg['From'] = config.report_from or "" msg['To'] = config.report_to msg.attach(MIMEText("\n".join(text), 'plain')) # check that smtp_server is wekk formated if isinstance(config.smtp_server, (list, tuple)): if len(config.smtp_server) >= 2: server = smtplib.SMTP(config.smtp_server[0], config.smtp_server[1]) elif len(config.smtp_server) == 1: server = smtplib.SMTP(config.smtp_server[0], 25) else: raise ValueError("bad smtp_server should be a tuple (server_adress, port)") else: raise ValueError("bad smtp_server should be a tuple (server_adress, port)") try: # should we use starttls ? if config.smtp_starttls: server.starttls() # should we use credentials ? if config.smtp_credentials: if ( isinstance(config.smtp_credentials, (list, tuple)) and len(config.smtp_credentials) >= 2 ): server.login(config.smtp_credentials[0], config.smtp_credentials[1]) else: ValueError("bad smtp_credentials should be a tuple (login, password)") server.sendmail(config.report_from or "", config.report_to, msg.as_string()) finally: server.quit() def database_init(): """Initialize database (create the table and index)""" with cursor() as cur: query = """CREATE TABLE IF NOT EXISTS mail_count ( id varchar(40) NOT NULL, date bigint NOT NULL );""" # if report is enable, also create the table for storing report datas if config.report: query_report = """CREATE TABLE IF NOT EXISTS limit_report ( id varchar(40) NOT NULL, delta int NOT NULL, hit int NOT NULL DEFAULT 0 );""" try: if cursor.backend == MYSQL_DB: # ignore possible warnings about the table already existing warnings.filterwarnings('ignore', category=cursor.backend_module.Warning) cur.execute(query) if config.report: cur.execute(query_report) finally: warnings.resetwarnings() try: cur.execute('CREATE INDEX %s mail_count_index ON mail_count(id, date)' % ( "" if cursor.backend == 1 else "IF NOT EXISTS" )) except cursor.backend_module.Error as error: # Duplicate key name for the mysql backend if error.args[0] not in [1061]: raise # if report is enable, create and unique index on (id, delta) if config.report: try: cur.execute( 'CREATE UNIQUE INDEX %s limit_report_index ON limit_report(id, delta)' % ( "" if cursor.backend == 1 else "IF NOT EXISTS" ) ) except cursor.backend_module.Error as error: # Duplicate key name for the mysql backend if error.args[0] not in [1061]: raise config.database_is_initialized = True def hit(cur, delta, id): # if no row is updated, (id, delta) do not exists and insert cur.execute( "UPDATE limit_report SET hit=hit+1 WHERE id = %s and delta = %s" % ( (config.format_str,)*2 ), (id, delta) ) if cur.rowcount <= 0: cur.execute( "INSERT INTO limit_report (id, delta, hit) VALUES (%s, %s, 1)" % ( (config.format_str,)*2 ), (id, delta) ) def write_pidfile(): """write current pid file to ``config.pidfile``""" try: with open(config.pidfile, 'w') as f: f.write("%s" % os.getpid()) except PermissionError as error: raise ValueError("Unable to write pid file, %s." % error) def remove_pidfile(): """Try to remove ``config.pidfile``""" try: os.remove(config.pidfile) except OSError: pass def get_config(dotted_string): """ Return the config parameter designated by ``dotted_string``. Dots are used as separator between dict and key. """ params = dotted_string.split('.') obj = getattr(config, params[0]) for param in params[1:]: obj = obj[param] return obj def exit_signal_handler(signal, frame): """SIGUSR1 signal handler. Cause the program to exit gracefully. Used for coverage computation""" raise Exit() config = LazyConfig() policyd-rate-limit-0.7.1/policyd_rate_limit/__init__.py0000644000175000017500000000076512741446214024713 0ustar valentinvalentin00000000000000# 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 version 3 for # more details. # # You should have received a copy of the GNU General Public License version 3 # along with this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # (c) 2015 Valentin Samir policyd-rate-limit-0.7.1/policyd_rate_limit/policyd-rate-limit.conf0000644000175000017500000000421412763310712027147 0ustar valentinvalentin00000000000000from policyd_rate_limit.const import SQLITE_DB, MYSQL_DB, PGSQL_DB debug = False user = "policyd-rate-limit" group = "policyd-rate-limit" pidfile = "/var/run/policyd-rate-limit/policyd-rate-limit.pid" mysql_config = { "user": "username", "passwd": "*****", "db": "database", "host": "localhost", "charset": 'utf8', } sqlite_config = { "database": "/var/lib/policyd-rate-limit/db.sqlite3", } pgsql_config = { "database": "database", "user": "username", "password": "*****", "host": "localhost", } backend = SQLITE_DB # SOCKET=("127.0.0.1", 8552) SOCKET = "/var/spool/postfix/ratelimit/policy" socket_permission = 0o666 # list of (number of mails, number of seconds) limits = [ (10, 60), # limit to 10 mails by minutes (150, 86400), # limits to 150 mails by days ] # dict of id -> limit list. Used to override limits and use custom limits for # a particular id. Use an empty list for no limits for a particular id. # ids are sasl usernames or ip addresses limits_by_id = {} limit_by_sasl = True limit_by_ip = False limited_networks = [] # actions return to postfix, see http://www.postfix.org/access.5.html for a list of actions. success_action = "dunno" fail_action = "defer_if_permit Rate limit reach, retry later" # action to return to postfix when we are unable to contect the database backend db_error_action = "dunno" # if True, send a report to report_email about users reaching limits each time --clean is called report = False # from who to send emails reports report_from = None # address to send emails reports to report_to = None # subject of the report email report_subject = "policyd-rate-limit report" # add number of seconds from the limits list for which you want to be reported report_limits = [86400] # only send a report if some users have reach a reported limit report_only_if_needed = True # The smtp server to use to send emails (host, port) smtp_server = ("localhost", 25) # Should we use starttls (you should set this to True if you use smtp_credentials) smtp_starttls = False # Should we use credentials to connect to smtp_server ? if yes set ("user", "password"), else None smtp_credentials = None policyd-rate-limit-0.7.1/policyd_rate_limit/policyd-rate-limit.yaml0000644000175000017500000000677212763310674027206 0ustar valentinvalentin00000000000000# Make policyd-rate-limit output logs to stderr debug: True # The user policyd-rate-limit will use to drop privileges. user: "policyd-rate-limit" # The group policyd-rate-limit will use to drop privileges. group: "policyd-rate-limit" # path where the program will try to write its pid to. pidfile: "/var/run/policyd-rate-limit/policyd-rate-limit.pid" # The config to connect to a mysql server. mysql_config: user: "username" passwd: "*****" db: "database" host: "localhost" charset: 'utf8' # The config to connect to a sqlite3 database. sqlite_config: database: "/var/lib/policyd-rate-limit/db.sqlite3" # The config to connect to a postgresql server. pgsql_config: database: "database" user: "username" password: "*****" host: "localhost" # Which data backend to use. Possible values are 0 for sqlite3, 1 for mysql and 2 for postgresql. backend: 0 # The socket to bind to. Can be a path to an unix socket or a couple [ip, port]. # SOCKET: ["127.0.0.1", 8552] SOCKET: "/var/spool/postfix/ratelimit/policy" # Permissions on the unix socket (if unix socket used). socket_permission: 0666 # A list of couple [number of emails, number of seconds]. If one of the element of the list is # exeeded (more than 'number of emails' on 'number of seconds' for an ip address or an sasl # username), postfix will return a temporary failure. limits: - [10, 60] # limit to 10 mails by minutes - [150, 86400] # limits to 150 mails by days # dict of id -> limit list. Used to override limits and use custom limits for # a particular id. Use an empty list for no limits for a particular id. # ids are sasl usernames or ip addresses # limits_by_id: # foo: [] # 192.168.0.254: # - [1000, 86400] # limits to 1000 mails by days # 2a01:240:fe3d:4:219:bbff:fe3c:4f76: [] limits_by_id: {} # Apply limits by sasl usernames. limit_by_sasl: True # If no sasl username is found, apply limits by ip addresses. limit_by_ip: False # A list of ip networks in cidr notation on which limits are applied. An empty list is equal # to limit_by_ip: False, put "0.0.0.0/0" and "::/0" for every ip addresses. limited_networks: [] # If no limits are reach, which action postfix should do. # see http://www.postfix.org/access.5.html for a list of actions. success_action: "dunno" # If a limit is reach, which action postfix should do. # see http://www.postfix.org/access.5.html for a list of actions. fail_action: "defer_if_permit Rate limit reach, retry later" # If we are unable to to contect the database backend, which action postfix should do. # see http://www.postfix.org/access.5.html for a list of actions. db_error_action: "dunno" # If True, send a report to report_to about users reaching limits each time --clean is called report: False # from who to send emails reports. Must be defined if report: True report_from: null # Address to send emails reports to. Must be defined if report: True report_to: null # Subject of the report email report_subject: "policyd-rate-limit report" # List of number of seconds from the limits list for which you want to be reported. report_limits: [86400] # Only send a report if some users have reach a reported limit. # Otherwise, empty reports may be sent. report_only_if_needed: True # The smtp server to use to send emails [host, port] smtp_server: ["localhost", 25] # Should we use starttls (you should set this to True if you use smtp_credentials) smtp_starttls: False # Should we use credentials to connect to smtp_server ? if yes set ["user", "password"], else null smtp_credentials: null policyd-rate-limit-0.7.1/policyd_rate_limit/tests/0000755000175000017500000000000012764505104023733 5ustar valentinvalentin00000000000000policyd-rate-limit-0.7.1/policyd_rate_limit/tests/utils.py0000644000175000017500000001273112764503415025454 0ustar valentinvalentin00000000000000# 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 version 3 for # more details. # # You should have received a copy of the GNU General Public License version 3 # along with this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # (c) 2015-2016 Valentin Samir import os import sys import socket import yaml import tempfile import subprocess import time from contextlib import contextmanager POSTFIX_TEMPLATE = """request=smtpd_access_policy protocol_state=%(protocol_state)s protocol_name=ESMTP client_address=%(client_address)s client_name=mail.example.com reverse_client_name=mail.example.com helo_name=mail.example.com sender=bar@example.com recipient=foo@example.com recipient_count=0 queue_id= instance=fd3.57cea9c4.143ea.0 size=0 etrn_domain= stress= sasl_method= sasl_username=%(sasl_username)s sasl_sender= ccert_subject= ccert_issuer= ccert_fingerprint= ccert_pubkey_fingerprint= encryption_protocol=TLSv1.2 encryption_cipher=ECDHE-RSA-AES256-GCM-SHA384 encryption_keysize=256 """ def postfix_request(sasl_username="", client_address="127.0.0.1", protocol_state="RCPT"): return (POSTFIX_TEMPLATE % { "sasl_username": sasl_username, "client_address": client_address, "protocol_state": protocol_state }).encode("utf-8") @contextmanager def sock(addr): if isinstance(addr, str): s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) elif '.' in addr[0]: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) elif ':' in addr[0]: s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: raise ValueError(addr) try: s.connect(addr) yield s finally: s.close() def send_policyd_request(addr, sasl_username="", client_address="127.0.0.1", protocol_state="RCPT"): with sock(addr) as s: s.send( postfix_request(sasl_username, client_address, protocol_state) ) data = s.recv(1024) return data def test_socket(addr): with sock(addr): return True def gen_config(new_config): default_config = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', 'policyd-rate-limit.yaml') ) with open(default_config) as f: config = yaml.load(f) config.update(new_config) cfg_path = tempfile.mktemp('.yaml') with open(cfg_path, 'w') as f: yaml.dump(config, f) return cfg_path def search_path(binary): for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"\'') bin_path = os.path.join(path, binary) if os.path.isfile(bin_path): return bin_path break else: return False def launch_instance(new_config, options=None, no_coverage=False): if new_config: cfg_path = gen_config(new_config) else: cfg_path = None bin_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', '..', 'policyd-rate-limit') ) # if bin_path do not exists, search in the PATH if not os.path.isfile(bin_path): bin_path = search_path('policyd-rate-limit') if bin_path: sys.stderr.write("Using %s\n" % bin_path) else: raise RuntimeError("The binary policyd-rate-limit was not found, impossible to test it") if no_coverage: cmd = [] else: coverage_path = search_path('coverage') if coverage_path: cmd = ["coverage", "run"] if launch_instance.i > 0: cmd.append("-a") else: cmd = [] sys.stderr.write("The coverage binary was not found, not computing coverage\n") cmd.append(bin_path) if new_config: cmd.extend(["--file", cfg_path]) if options is not None: cmd.extend(options) p = subprocess.Popen(cmd, stdout=subprocess.PIPE) launch_instance.i += 1 return (p, cfg_path) launch_instance.i = 0 @contextmanager def lauch(new_config, get_process=False, options=None, no_coverage=False, no_wait=False): (p, cfg_path) = launch_instance(new_config, options=options, no_coverage=no_coverage) try: if cfg_path: with open(cfg_path) as f: cfg = yaml.load(f) if not no_wait: time.sleep(0.01) for i in range(100): try: test_socket(cfg["SOCKET"]) break except (ConnectionRefusedError, FileNotFoundError): time.sleep(0.01) else: cfg = None if get_process: yield p else: yield cfg finally: p.stdout.close() try: os.kill(p.pid, 10) try: p.wait(timeout=1) except subprocess.TimeoutExpired: p.kill() p.wait(timeout=1) except OSError as error: if error.errno != 3: # No such process raise if cfg_path: os.remove(cfg_path) def test(**new_config): def wraps(funct): def f(*args, **kwargs): with lauch(new_config) as cfg: kwargs["cfg"] = cfg ret = funct(*args, **kwargs) return ret return f return wraps policyd-rate-limit-0.7.1/policyd_rate_limit/tests/__init__.py0000644000175000017500000000076512751626777026074 0ustar valentinvalentin00000000000000# 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 version 3 for # more details. # # You should have received a copy of the GNU General Public License version 3 # along with this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # (c) 2015 Valentin Samir policyd-rate-limit-0.7.1/policyd_rate_limit/tests/test_daemon.py0000644000175000017500000002525612763643032026623 0ustar valentinvalentin00000000000000# 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 version 3 for # more details. # # You should have received a copy of the GNU General Public License version 3 # along with this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # (c) 2016 Valentin Samir import os import tempfile from unittest import TestCase from policyd_rate_limit.tests import utils as test_utils class DaemonTestCase(TestCase): def setUp(self): self.base_config = dict( SOCKET=tempfile.mktemp('.sock'), sqlite_config={"database": tempfile.mktemp('.sqlite3')}, pidfile=tempfile.mktemp('.pid'), limit_by_sasl=True, limit_by_ip=True, limited_networks=["192.168.0.0/16", "ffee::/64"], debug=True, report=True, report_limits=[60, 86400], user="root", group="root", ) def tearDown(self): if os.path.isfile(self.base_config["sqlite_config"]["database"]): os.remove(self.base_config["sqlite_config"]["database"]) def test_main_unix_socket(self): with test_utils.lauch(self.base_config) as cfg: self.base_test(cfg) def test_main_afinet_socket(self): self.base_config["SOCKET"] = ("127.0.0.1", 27184) with test_utils.lauch(self.base_config) as cfg: self.base_test(cfg) def test_main_afinet6_socket(self): self.base_config["SOCKET"] = ("::1", 27184) with test_utils.lauch(self.base_config) as cfg: self.base_test(cfg) def test_no_debug_no_report(self): self.base_config["debug"] = False self.base_config["report"] = False with test_utils.lauch(self.base_config) as cfg: self.base_test(cfg) def test_slow_connection(self): with test_utils.lauch(self.base_config) as cfg: with test_utils.sock(cfg["SOCKET"]) as s: msg = test_utils.postfix_request(sasl_username="test") i = 0 s.send(msg[i:10]) i += 10 # run another request before the previous one is ended data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="test") self.assertEqual(data.strip(), b"action=dunno") s.send(msg[i:1]) i += 1 data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="test") self.assertEqual(data.strip(), b"action=dunno") s.send(msg[i:]) datal = [] datal.append(s.recv(2)) # run another request before the previous one is ended data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="test") self.assertEqual(data.strip(), b"action=dunno") datal.append(s.recv(1024)) data = b"".join(datal) self.assertEqual(data.strip(), b"action=dunno") def test_database_unavailable(self): # create the database with open(self.base_config["sqlite_config"]["database"], 'a'): pass # make it unavailable os.chmod(self.base_config["sqlite_config"]["database"], 0) # lauch policyd-rate-limit with the database navailable with test_utils.lauch(self.base_config) as cfg: # as long as the database is unavailable, all response should be dunno for i in range(20): data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="test") self.assertEqual(data.strip(), b"action=dunno") # make the database available, it should be initialized upon the next request os.chmod(self.base_config["sqlite_config"]["database"], 0o644) # these requests should be counted for i in range(10): data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="test") self.assertEqual(data.strip(), b"action=dunno") # the eleventh counted requests should fail data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="test") self.assertEqual(data.strip(), b"action=defer_if_permit Rate limit reach, retry later") def test_bad_config(self): self.base_config["backend"] = 1000 with test_utils.lauch(self.base_config, get_process=True) as p: self.assertEqual(p.wait(), 5) def test_get_config(self): with test_utils.lauch( self.base_config, get_process=True, options=["--get-config", "pidfile"] ) as p: self.assertEqual(p.wait(), 0) self.assertEqual(p.stdout.read(), self.base_config["pidfile"].encode()) with test_utils.lauch( self.base_config, get_process=True, options=["--get-config", "sqlite_config.database"] ) as p: self.assertEqual(p.wait(), 0) self.assertEqual( p.stdout.read(), self.base_config["sqlite_config"]["database"].encode() ) with test_utils.lauch( self.base_config, get_process=True, options=["--get-config", "foo"] ) as p: self.assertEqual(p.wait(), 1) with test_utils.lauch( None, get_process=True, options=["--get-config", "pidfile"] ) as p: self.assertEqual(p.wait(), 0) self.assertEqual( p.stdout.read(), b'/var/run/policyd-rate-limit/policyd-rate-limit.pid' ) def test_no_config_file_found(self): with test_utils.lauch(None, get_process=True) as p: self.assertEqual(p.wait(), 5) def test_already_running(self): with test_utils.lauch(self.base_config, no_coverage=True, get_process=True) as p1: pid = p1.pid with test_utils.lauch(self.base_config, get_process=True) as p2: self.assertEqual(p2.wait(), 3) with open(self.base_config["pidfile"], 'w') as f: f.write("%s" % pid) try: with test_utils.lauch(self.base_config, get_process=True) as p: pass self.assertEqual(p.wait(), 0) with open(self.base_config["pidfile"], 'w') as f: f.write("foo") with test_utils.lauch(self.base_config, get_process=True) as p: pass self.assertEqual(p.wait(), 0) with open(self.base_config["pidfile"], 'w') as f: f.write("") os.chmod(self.base_config["pidfile"], 0) with test_utils.lauch(self.base_config, get_process=True) as p: self.assertEqual(p.wait(), 6) finally: try: os.remove(self.base_config["pidfile"]) except OSError: pass def test_bad_socket_bind_address(self): self.base_config["SOCKET"] = ("toto", 1234) with test_utils.lauch(self.base_config, get_process=True, no_wait=True) as p: self.assertEqual(p.wait(), 4) self.base_config["SOCKET"] = ("192.168::1", 1234) with test_utils.lauch(self.base_config, get_process=True, no_wait=True) as p: self.assertEqual(p.wait(), 6) def test_clean(self): self.base_config["report_to"] = "foo@example.com" with test_utils.lauch(self.base_config, options=["--clean"], get_process=True) as p: self.assertEqual(p.wait(), 0) self.base_config["report_only_if_needed"] = False self.base_config["smtp_server"] = "localhost" with test_utils.lauch(self.base_config, options=["--clean"], get_process=True) as p: self.assertEqual(p.wait(), 8) def test_limits_by_id(self): self.base_config["limits_by_id"] = {'foo': [[2, 60]], 'bar': []} with test_utils.lauch(self.base_config) as cfg: self.base_test(cfg) for i in range(20): data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="bar") self.assertEqual(data.strip(), b"action=dunno") for i in range(2): data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="foo") self.assertEqual(data.strip(), b"action=dunno") data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="foo") self.assertEqual(data.strip(), b"action=defer_if_permit Rate limit reach, retry later") def base_test(self, cfg): # test limit by sasl username for i in range(10): data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="test") self.assertEqual(data.strip(), b"action=dunno") data = test_utils.send_policyd_request(cfg["SOCKET"], sasl_username="test") self.assertEqual(data.strip(), b"action=defer_if_permit Rate limit reach, retry later") # test limit by ip for i in range(10): data = test_utils.send_policyd_request(cfg["SOCKET"], client_address="192.168.0.1") self.assertEqual(data.strip(), b"action=dunno") data = test_utils.send_policyd_request(cfg["SOCKET"], client_address="192.168.0.1") self.assertEqual(data.strip(), b"action=defer_if_permit Rate limit reach, retry later") # test limit by ip in ipv6 for i in range(10): data = test_utils.send_policyd_request(cfg["SOCKET"], client_address="ffee::1") self.assertEqual(data.strip(), b"action=dunno") data = test_utils.send_policyd_request(cfg["SOCKET"], client_address="ffee::1") self.assertEqual(data.strip(), b"action=defer_if_permit Rate limit reach, retry later") # test limit by ip not limited for i in range(10): data = test_utils.send_policyd_request(cfg["SOCKET"], client_address="10.0.0.1") self.assertEqual(data.strip(), b"action=dunno") data = test_utils.send_policyd_request(cfg["SOCKET"], client_address="10.0.0.1") self.assertEqual(data.strip(), b"action=dunno") # test with bad protocol state for i in range(10): data = test_utils.send_policyd_request( cfg["SOCKET"], sasl_username="test", protocol_state="VRFY" ) self.assertEqual(data.strip(), b"action=dunno") data = test_utils.send_policyd_request( cfg["SOCKET"], sasl_username="test", protocol_state="VRFY" ) self.assertEqual(data.strip(), b"action=dunno") policyd-rate-limit-0.7.1/policyd_rate_limit/config.py0000644000175000017500000000522312763310702024407 0ustar valentinvalentin00000000000000# 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 version 3 for # more details. # # You should have received a copy of the GNU General Public License version 3 # along with this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # (c) 2015-2016 Valentin Samir from policyd_rate_limit.const import SQLITE_DB, MYSQL_DB, PGSQL_DB # noqa: F401 debug = True user = "policyd-rate-limit" group = "policyd-rate-limit" pidfile = "/var/run/policyd-rate-limit/policyd-rate-limit.pid" mysql_config = { "user": "username", "passwd": "*****", "db": "database", "host": "localhost", "charset": 'utf8', } sqlite_config = { "database": "/var/lib/policyd-rate-limit/db.sqlite3", } pgsql_config = { "database": "database", "user": "username", "password": "*****", "host": "localhost", } backend = SQLITE_DB # SOCKET=("127.0.0.1", 8552) SOCKET = "/var/spool/postfix/ratelimit/policy" socket_permission = 0o666 # list of (number of mails, number of seconds) limits = [ (10, 60), # limit to 10 mails by minutes (150, 86400), # limits to 150 mails by days ] # dict of id -> limit list. Used to override limits and use custom limits for # a particular id. Use an empty list for no limits for a particular id. # ids are sasl usernames or ip addresses limits_by_id = {} limit_by_sasl = True limit_by_ip = False limited_networks = [] # actions return to postfix, see http://www.postfix.org/access.5.html for a list of actions. success_action = "dunno" fail_action = "defer_if_permit Rate limit reach, retry later" # action to return to postfix when we are unable to contect the database backend db_error_action = "dunno" # if True, send a report to report_email about users reaching limits each time --clean is called report = False # from who to send emails reports report_from = None # address to send emails reports to report_to = None # subject of the report email report_subject = "policyd-rate-limit report" # add number of seconds from the limits list for which you want to be reported report_limits = [86400] # only send a report if some users have reach a reported limit report_only_if_needed = True # The smtp server to use to send emails (host, port) smtp_server = ("localhost", 25) # Should we use starttls (you should set this to True if you use smtp_credentials) smtp_starttls = False # Should we use credentials to connect to smtp_server ? if yes set ("user", "password"), else None smtp_credentials = None policyd-rate-limit-0.7.1/policyd_rate_limit/const.py0000644000175000017500000000103512741446214024271 0ustar valentinvalentin00000000000000# 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 version 3 for # more details. # # You should have received a copy of the GNU General Public License version 3 # along with this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # (c) 2015 Valentin Samir SQLITE_DB = 0 MYSQL_DB = 1 PGSQL_DB = 2 policyd-rate-limit-0.7.1/policyd_rate_limit/policyd.py0000644000175000017500000002377412763560700024625 0ustar valentinvalentin00000000000000# 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 version 3 for # more details. # # You should have received a copy of the GNU General Public License version 3 # along with this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # (c) 2015-2016 Valentin Samir import os import sys import socket import time import select from policyd_rate_limit import utils from policyd_rate_limit.utils import config class Pass(Exception): pass class Policyd(object): """The policy server class""" socket_data_read = {} socket_data_write = {} def socket(self): """initialize the socket from the config parameters""" # if socket is a string assume it is the path to an unix socket if isinstance(config.SOCKET, str): try: os.remove(config.SOCKET) except OSError: if os.path.exists(config.SOCKET): # pragma: no cover (should not happen) raise sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # else asume its a tuple (bind_ip, bind_port) elif ':' in config.SOCKET[0]: # assume ipv6 bind addresse sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) elif '.' in config.SOCKET[0]: # assume ipv4 bind addresse sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: raise ValueError("bad socket %s" % (config.SOCKET,)) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock = sock def close_socket(self): """close the socket depending of the config parameters""" self.sock.close() # if socket was an unix socket, delete it after closing. if isinstance(config.SOCKET, str): try: os.remove(config.SOCKET) except OSError as error: # pragma: no cover (should not happen) sys.stderr.write("%s\n" % error) sys.stderr.flush() def close_connection(self, connection): """close a connection and clean read/write dict""" # Clean up the connection try: del self.socket_data_read[connection] except KeyError: pass try: del self.socket_data_write[connection] except KeyError: pass connection.close() def run(self): """The main server loop""" try: sock = self.sock sock.bind(config.SOCKET) if isinstance(config.SOCKET, str): os.chmod(config.SOCKET, config.socket_permission) sock.listen(5) self.socket_data_read[sock] = [] if config.debug: sys.stderr.write('waiting for connections\n') sys.stderr.flush() while True: # wait for a socket to read to or to write to (rlist, wlist, _) = select.select( self.socket_data_read.keys(), self.socket_data_write.keys(), [] ) for socket in rlist: # if the socket is the main socket, there is a new connection to accept if socket == sock: connection, client_address = sock.accept() if config.debug: sys.stderr.write('connection from %s\n' % (client_address,)) sys.stderr.flush() self.socket_data_read[connection] = [] # else there is data to read on a client socket else: self.read(socket) for socket in wlist: try: data = self.socket_data_write[socket] sent = socket.send(data) data_not_sent = data[sent:] if data_not_sent: self.socket_data_write[socket] = data_not_sent else: self.close_connection(socket) # the socket has been closed during read except KeyError: pass except (KeyboardInterrupt, utils.Exit): for socket in list(self.socket_data_read.keys()): if socket != self.sock: self.close_connection(sock) raise def read(self, connection): """Called then a connection is ready for reads""" try: # get the current buffer of the connection buffer = self.socket_data_read[connection] # read data data = connection.recv(1024).decode('UTF-8') if not data: raise ValueError("connection closed") if config.debug: sys.stderr.write(data) sys.stderr.flush() # accumulate it in buffer buffer.append(data) # if data len too short to determine if we are on an empty line, we # concatene datas in buffer if len(data) < 2: data = u"".join(buffer) buffer = [data] # We reach on empty line so the client has finish to send and wait for a response if data[-2:] == "\n\n": data = u"".join(buffer) request = {} # read data are like one key=value per line for line in data.split("\n"): line = line.strip() try: key, value = line.split(u"=", 1) if value: request[key] = value # if value is empty, ignore it except ValueError: pass # process the collected data in the action method self.action(connection, request) else: self.socket_data_read[connection] = buffer except (KeyboardInterrupt, utils.Exit): self.close_connection(connection) raise except Exception as error: sys.stderr.write("%s\n" % error) sys.stderr.flush() self.close_connection(connection) def action(self, connection, request): """Called then the client has sent an empty line""" id = None # By default, we do not block emails action = config.success_action try: if not config.database_is_initialized: utils.database_init() with utils.cursor() as cur: try: # only care if the protocol states is RCTP. If the policy delegation in postfix # configuration is in smtpd_recipient_restrictions as said in the doc, # possible states are RCPT and VRFY. if 'protocol_state' in request and request['protocol_state'].upper() != "RCPT": raise Pass() # if user is authenticated, we filter by sasl username if config.limit_by_sasl and u'sasl_username' in request: id = request[u'sasl_username'] # else, if activated, we filter by ip source addresse elif ( config.limit_by_ip and u'client_address' in request and utils.is_ip_limited(request[u'client_address']) ): id = request[u'client_address'] # if the client neither send us client ip adresse nor sasl username, jump # to the next section else: raise Pass() # Here we are limiting agains sasl username or ip source addresses. # for each limit periods, we count the number of mails already send. # if the a limit is reach, we change action to fail (deny the mail). for mail_nb, delta in config.limits_by_id.get(id, config.limits): cur.execute( ( "SELECT COUNT(*) FROM mail_count " "WHERE id = %s AND date >= %s" ) % ((config.format_str,)*2), (id, int(time.time() - delta)) ) nb = cur.fetchone()[0] if config.debug: sys.stderr.write("%03d/%03d hit since %ss\n" % (nb, mail_nb, delta)) sys.stderr.flush() if nb >= mail_nb: action = config.fail_action if config.report and delta in config.report_limits: utils.hit(cur, delta, id) raise Pass() except Pass: pass # If action is a success, record in the database that a new mail has just been sent if action == config.success_action and id is not None: if config.debug: sys.stderr.write(u"insert id %s\n" % id) sys.stderr.flush() cur.execute( "INSERT INTO mail_count VALUES (%s, %s)" % ((config.format_str,)*2), (id, int(time.time())) ) except utils.cursor.backend_module.Error as error: utils.cursor.del_db() action = config.db_error_action sys.stderr.write("Database error: %r\n" % error) data = u"action=%s\n\n" % action if config.debug: sys.stderr.write(data) sys.stderr.flush() # return the result to the client self.socket_data_write[connection] = data.encode('UTF-8') policyd-rate-limit-0.7.1/policyd_rate_limit.egg-info/0000755000175000017500000000000012764505104024263 5ustar valentinvalentin00000000000000policyd-rate-limit-0.7.1/policyd_rate_limit.egg-info/dependency_links.txt0000644000175000017500000000000112764505104030331 0ustar valentinvalentin00000000000000 policyd-rate-limit-0.7.1/policyd_rate_limit.egg-info/SOURCES.txt0000644000175000017500000000142712764505104026153 0ustar valentinvalentin00000000000000LICENSE MANIFEST.in Makefile README.rst policyd-rate-limit setup.cfg setup.py docs/policyd-rate-limit.8.rst docs/policyd-rate-limit.yaml.5.rst init/policyd-rate-limit init/policyd-rate-limit.service policyd_rate_limit/__init__.py policyd_rate_limit/config.py policyd_rate_limit/const.py policyd_rate_limit/policyd-rate-limit.conf policyd_rate_limit/policyd-rate-limit.yaml policyd_rate_limit/policyd.py policyd_rate_limit/utils.py policyd_rate_limit.egg-info/PKG-INFO policyd_rate_limit.egg-info/SOURCES.txt policyd_rate_limit.egg-info/dependency_links.txt policyd_rate_limit.egg-info/not-zip-safe policyd_rate_limit.egg-info/requires.txt policyd_rate_limit.egg-info/top_level.txt policyd_rate_limit/tests/__init__.py policyd_rate_limit/tests/test_daemon.py policyd_rate_limit/tests/utils.pypolicyd-rate-limit-0.7.1/policyd_rate_limit.egg-info/PKG-INFO0000644000175000017500000002313012764505104025357 0ustar valentinvalentin00000000000000Metadata-Version: 1.1 Name: policyd-rate-limit Version: 0.7.1 Summary: Postfix rate limit policy server implemented in Python3. Home-page: https://github.com/nitmir/policyd-rate-limit Author: Valentin Samir Author-email: valentin.samir@crans.org License: GPLv3 Download-URL: https://github.com/nitmir/policyd-rate-limit/releases/latest Description: Policyd rate limit ================== |travis| |coverage| |github_version| |pypi_version| |license| Postfix policyd server allowing to limit the number of mails accepted by postfix over several time periods, by sasl usernames and/or ip addresses. Installation ------------ First, create the user that will run the daemon:: adduser --system --group --home /run/policyd-rate-limit --no-create-home policyd-rate-limit Since version 0.6.0, the configuration file is written using the yaml, so you need the following package: * `pyyaml `_ (``sudo apt-get install python3-yaml`` on debian like systems) Depending of the backend storage you planning to use, you may need to install additional packages. (The default settings use the sqlite3 bakends and do not need extra packages). * `mysqldb `_ (``sudo apt-get install python3-mysqldb`` on debian like systems) for the mysql backend. * `psycopg2 `_ (``sudo apt-get install python3-psycopg2`` on debian like systems) fot the postgresql backend Install with pip:: sudo pip3 install policyd-rate-limit or from source code:: sudo make install This will install the ``policyd_rate_limit`` module, the ``policyd-rate-limit`` binary, copy the default config to ``/etc/policyd-rate-limit.conf`` if the file do not exists, copy an init script to ``/etc/init.d/policyd-rate-limit`` and an unit file to ``/etc/systemd/system/policyd-rate-limit.service``. After the installation, you may need to run ``sudo systemctl daemon-reload`` for make the unit file visible by systemd. You should run ``policyd-rate-limit --clean`` on a regular basis to delete old records from the database. It could be wise to put it in a daily cron, for example:: 0 0 * * * policyd-rate-limit /usr/local/bin/policyd-rate-limit --clean >/dev/null Settings -------- ``policyd-rate-limit`` search for its config first in ``~/.config/policyd-rate-limit.conf`` If not found, then in ``/etc/policyd-rate-limit.conf``, and if not found use the default config. * ``debug``: make ``policyd-rate-limit`` output logs to stderr. The default is ``True``. * ``user``: The user ``policyd-rate-limit`` will use to drop privileges. The default is ``"policyd-rate-limit"``. * ``group``: The group ``policyd-rate-limit`` will use to drop privileges. The defaut is ``"policyd-rate-limit"``. * ``pidfile``: path where the program will try to write its pid to. The default is ``"/var/run/policyd-rate-limit/policyd-rate-limit.pid"``. ``policyd-rate-limit`` will try to create the parent directory and chown it if it do not exists. * ``mysql_config``: The config to connect to a mysql server * ``pgsql_config``: The config to connect to a postgresql server * ``sqlite_config``: The config to connect to a sqlite3 database. * ``backend``: Which data backend to use. Possible values are ``0`` for sqlite3, ``1`` for mysql and ``2`` for postgresql. The default is ``0``, use the sqlite3 backend. * ``SOCKET``: The socket to bind to. Can be a path to an unix socket or a couple [ip, port]. The default is ``"/var/spool/postfix/ratelimit/policy"``. ``policyd-rate-limit`` will try to create the parent directory and chown it if it do not exists. * ``socket_permission``: Permissions on the unix socket (if unix socket used). The default is ``0o666``. * ``limits``: A list of couple [number of emails, number of seconds]. If one of the element of the list is exeeded (more than 'number of emails' on 'number of seconds' for an ip address or an sasl username), postfix will return a temporary failure. * ``limits_by_id``: A dictionnary of id -> limit list (see limits). Used to override limits and use custom limits for a particular id. Use an empty list for no limits for a particular id. Ids are sasl usernames or ip addresses. The default is ``{}``. * ``limit_by_sasl``: Apply limits by sasl usernames. The default is ``True``. * ``limit_by_ip``: Apply limits by ip addresses if sasl username is not found. The default is ``False``. * ``limited_networks``: A list of ip networks in cidr notation on which limits are applied. An empty list is equal to ``limit_by_ip = False``, put ``"0.0.0.0/0"`` and ``::/0`` for every ip addresses. * ``success_action``: If not limits are reach, which action postfix should do. The default is ``"dunno"``. See http://www.postfix.org/access.5.html for possible actions. * ``fail_action``: If a limit is reach, which action postfix should do. The default is ``"defer_if_permit Rate limit reach, retry later"``. * ``db_error_action`` : If we are unable to to contect the database backend, which action postfix should do. The default is ``"dunno"``. See http://www.postfix.org/access.5.html for possible actions. See http://www.postfix.org/access.5.html for possible actions. * ``config_file``: This parameter is automatically set to the path of the configuration file currently in use. You can call it conjunction with **--get-config** to known which configuration file is used. * ``report``: if ``True``, send a report to ``report_to`` about users reaching limits each time --clean is called. The default is ``False``. * ``report_from``: From who to send emails reports. It must be defined when ``report`` is ``True``. * ``report_to``: Address to send emails reports to. It must be defined when ``report`` is ``True``. * ``report_subject``: Subject of the report email. The default is ``"policyd-rate-limit report"``. * ``report_limits``: List of number of seconds from the limits list for which you want to be reported. The default is ``[86400]``. * ``report_only_if_needed``: Only send a report if some users have reach a reported limit. The default is ``True``. * ``smtp_server``: The smtp server to use to send emails ``["host", port]``. The default is ``["localhost", 25]``. * ``smtp_starttls``: Should we use starttls to send mails ? (you should set this to ``True`` if you use ``smtp_credentials``). The default is ``False``. * ``smtp_credentials``: Should we use credentials to connect to smtp_server ? if yes set ``["user", "password"]``, else ``null``. The default is ``null``. Postfix settings ---------------- For postfix 3.0 and later I recommend using the example below. It ensure that if policyd-rate-limit become unavailable for any reason, postfix will ignore it and keep accepting mail as if the rule was not here. I find it nice has in my opinion, policyd-rate-limit is a "non-critical" policy service. /etc/postfix/main.cf:: smtpd_recipient_restrictions = ..., check_policy_service { unix:ratelimit/policy, default_action=DUNNO }, ... On previous postfix versions, you must use: /etc/postfix/main.cf:: smtpd_recipient_restrictions = ..., check_policy_service unix:ratelimit/policy, ... .. |travis| image:: https://badges.genua.fr/travis/nitmir/policyd-rate-limit/master.svg :target: https://travis-ci.org/nitmir/policyd-rate-limit .. |coverage| image:: https://badges.genua.fr/local/coverage/?project=policyd-rate-limit :target: https://badges.genua.fr/local/coverage/policyd-rate-limit/ .. |pypi_version| image:: https://badges.genua.fr/pypi/v/policyd-rate-limit.svg :target: https://pypi.python.org/pypi/policyd-rate-limit .. |github_version| image:: https://badges.genua.fr/github/tag/nitmir/policyd-rate-limit.svg?label=github :target: https://github.com/nitmir/policyd-rate-limit/releases/latest .. |license| image:: https://badges.genua.fr/pypi/l/policyd-rate-limit.svg :target: https://www.gnu.org/licenses/gpl-3.0.html Keywords: Postfix,rate,limit,email Platform: UNKNOWN Classifier: Environment :: No Input/Output (Daemon) Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: POSIX Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications :: Email :: Mail Transport Agents Classifier: Topic :: Communications :: Email :: Filters policyd-rate-limit-0.7.1/policyd_rate_limit.egg-info/not-zip-safe0000644000175000017500000000000112764311331026506 0ustar valentinvalentin00000000000000 policyd-rate-limit-0.7.1/policyd_rate_limit.egg-info/top_level.txt0000644000175000017500000000002312764505104027010 0ustar valentinvalentin00000000000000policyd_rate_limit policyd-rate-limit-0.7.1/policyd_rate_limit.egg-info/requires.txt0000644000175000017500000000001712764505104026661 0ustar valentinvalentin00000000000000PyYAML >= 3.11 policyd-rate-limit-0.7.1/Makefile0000644000175000017500000000335412763642370020370 0ustar valentinvalentin00000000000000.PHONY: clean build install dist uninstall VERSION=`python3 setup.py -V` build: python3 setup.py build install: dist pip3 -V [ ! -f /etc/policyd-rate-limit.yaml ] && cp -n policyd_rate_limit/policyd-rate-limit.yaml /etc/ || true cp -n init/policyd-rate-limit /etc/init.d cp -n init/policyd-rate-limit.service /etc/systemd/system/ || true pip3 install policyd-rate-limit -U --force-reinstall --no-deps --no-binary :all -f ./dist/policyd-rate-limit-${VERSION}.tar.gz systemctl daemon-reload uninstall: pip3 uninstall policyd-rate-limit || true reinstall: uninstall install purge: uninstall rm -f /etc/policyd-rate-limit.conf /etc/policyd-rate-limit.yaml rm -f /etc/init.d/policyd-rate-limit /etc/systemd/system/policyd-rate-limit.service rm -rf /var/lib/policyd-rate-limit/ clean_pyc: find ./ -name '*.pyc' -delete find ./ -name __pycache__ -delete clean_build: rm -rf build policyd_rate_limit.egg-info dist clean_coverage: rm -rf htmlcov .coverage coverage.xml clean_tox: rm -rf .tox tox_logs clean_test_venv: rm -rf test_venv clean: clean_pyc clean_build clean_coverage find ./ -name '*~' -delete clean_all: clean clean_tox clean_test_venv man_files: mkdir -p build/man/ rst2man docs/policyd-rate-limit.8.rst | sed 's/)(/(/g' > build/man/policyd-rate-limit.8 rst2man docs/policyd-rate-limit.yaml.5.rst | sed 's/)(/(/g' > build/man/policyd-rate-limit.yaml.5 dist: python3 setup.py sdist publish_pypi_release: python setup.py sdist upload --sign test_venv/bin/python: virtualenv -p python3 test_venv test_venv/bin/pip3 install -U -r requirements-dev.txt test_venv: test_venv/bin/python coverage: clean_coverage test_venv export PATH=test_venv/bin/:$$PATH; echo $$PATH; pytest test_venv/bin/coverage html test_venv/bin/coverage report