From 0c24eb19f79c42a04ccb6e83f72c3166b1783cea Mon Sep 17 00:00:00 2001 From: Thomas Oettli Date: Sun, 18 Jan 2026 06:16:15 +0100 Subject: [PATCH] Initial commit --- .gitignore | 116 +++++++++ LICENSE | 232 ++++++++++++++++++ README.md | 364 +++++++++++++++++++++++++++ build.sh | 3 + config.example.toml | 76 ++++++ ddns-daemon.initd | 22 ++ ddns-daemon.service | 23 ++ pyproject.toml | 39 +++ src/ddns_daemon/__init__.py | 24 ++ src/ddns_daemon/app.py | 64 +++++ src/ddns_daemon/cleanup.py | 143 +++++++++++ src/ddns_daemon/cli.py | 306 +++++++++++++++++++++++ src/ddns_daemon/config.py | 192 +++++++++++++++ src/ddns_daemon/dns.py | 152 ++++++++++++ src/ddns_daemon/email.py | 104 ++++++++ src/ddns_daemon/logging.py | 141 +++++++++++ src/ddns_daemon/main.py | 182 ++++++++++++++ src/ddns_daemon/models.py | 172 +++++++++++++ src/ddns_daemon/ratelimit.py | 129 ++++++++++ src/ddns_daemon/server.py | 447 ++++++++++++++++++++++++++++++++++ src/ddns_daemon/validation.py | 138 +++++++++++ 21 files changed, 3069 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100755 build.sh create mode 100644 config.example.toml create mode 100644 ddns-daemon.initd create mode 100644 ddns-daemon.service create mode 100644 pyproject.toml create mode 100644 src/ddns_daemon/__init__.py create mode 100644 src/ddns_daemon/app.py create mode 100644 src/ddns_daemon/cleanup.py create mode 100644 src/ddns_daemon/cli.py create mode 100644 src/ddns_daemon/config.py create mode 100644 src/ddns_daemon/dns.py create mode 100644 src/ddns_daemon/email.py create mode 100644 src/ddns_daemon/logging.py create mode 100644 src/ddns_daemon/main.py create mode 100644 src/ddns_daemon/models.py create mode 100644 src/ddns_daemon/ratelimit.py create mode 100644 src/ddns_daemon/server.py create mode 100644 src/ddns_daemon/validation.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0447b8b --- /dev/null +++ b/.gitignore @@ -0,0 +1,116 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..aad7c5a --- /dev/null +++ b/LICENSE @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 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. + + dns-manager + Copyright (C) 2025 spacefreak + + 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: + + dns-manager Copyright (C) 2025 spacefreak + 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 . diff --git a/README.md b/README.md new file mode 100644 index 0000000..f56f8f8 --- /dev/null +++ b/README.md @@ -0,0 +1,364 @@ +# DDNS Daemon + +Dynamic DNS update service with CLI administration. Accepts HTTP(S) requests to update DNS A/AAAA records using the dns-manager library. + +## Features + +- HTTP(S) server for DynDNS-compatible updates +- Multiple endpoints with configurable parameter aliases +- Dual-stack IPv4/IPv6 support +- SQLite or MariaDB database backend +- Argon2 password hashing +- Rate limiting (separate limits for good/bad requests) +- TTL-based automatic record expiration +- Email notifications on expiry +- Syslog support with transaction IDs for request tracking +- Systemd integration +- Content negotiation (plain text / JSON responses) +- IDN/punycode hostname support + +## Project Structure + +``` +ddns-daemon/ +├── ddns-daemon # Main executable +├── ddns_daemon/ # Python package +│ ├── __init__.py # Version info +│ ├── cleanup.py # TTL expiry cleanup +│ ├── cli.py # CLI commands +│ ├── config.py # Configuration loading +│ ├── dns.py # DNS operations +│ ├── email.py # Email notifications +│ ├── logging.py # Centralized logging +│ ├── models.py # Database models +│ ├── ratelimit.py # Rate limiting +│ ├── server.py # HTTP server +│ └── validation.py # Hostname validation +├── config.example.toml +├── ddns-daemon.service +├── requirements.txt +└── README.md +``` + +## Installation + +```bash +pip install -r requirements.txt +``` + +### Dependencies + +- Python 3.11+ +- dns-manager +- peewee +- argon2-cffi +- pymysql (for MariaDB support) + +## Configuration + +Copy `config.example.toml` to `/etc/ddns-daemon/config.toml` or `./config.toml`: + +```toml +[daemon] +# host = "localhost" # default: "localhost" (use reverse proxy for public access) +# port = 8443 # default: 8443 +# log_level = "INFO" # default: "INFO" +# log_target = "stdout" # default: "stdout", or "syslog", "file" +# syslog_socket = "/dev/log" # default: "/dev/log" +# syslog_facility = "daemon" # default: "daemon" +# log_file = "/var/log/ddns-daemon.log" # default, used if log_target = "file" +# log_file_size = 52428800 # default: 52428800 (50 MB in bytes) +# log_versions = 5 # default: 5 backup files +# log_requests = false # default: false +# ssl = false # default: false +ssl_cert_file = "/etc/ddns-daemon/cert.pem" # required if ssl = true +ssl_key_file = "/etc/ddns-daemon/key.pem" # required if ssl = true +# proxy_header = "" # default: "" (disabled), e.g. "X-Forwarded-For" +# trusted_proxies = [] # default: [], e.g. ["127.0.0.1", "10.0.0.0/8"] + +[database] +# backend = "sqlite" # default: "sqlite", or "mariadb" +path = "/var/lib/ddns-daemon/ddns.db" # required for sqlite + +[dns_service] +# manager_config_file = "/etc/dns-manager/config.yml" # default +# cleanup_interval = 60 # default: 60 (seconds, expired records cleanup) + +[defaults] +# dns_ttl = 60 # default: 60 +# expiry_ttl = 3600 # default: 3600 + +[email] +# enabled = false # default: false +smtp_host = "localhost" # required if email.enabled +# smtp_port = 25 # default: 25 +# smtp_starttls = false # default: false +from_address = "ddns@example.com" # required if email.enabled + +[rate_limit] +# enabled = true # default: true +# good_window_seconds = 60 # default: 60 +# good_max_requests = 5 # default: 5 +# bad_window_seconds = 60 # default: 60 +# bad_max_requests = 3 # default: 3 +# cleanup_interval = 60 # default: 60 (seconds, rate limiter cleanup) +``` + +### Endpoints + +Configure one or more HTTP endpoints. If no endpoints are defined, a default endpoint at `/update` is created with standard parameter names. + +```toml +[[endpoints]] +path = "/update" +[endpoints.params] +hostname = ["hostname", "host"] +ipv4 = ["myip", "ipv4", "ip4"] +ipv6 = ["myip6", "ipv6", "ip6"] +username = ["username", "user"] +password = ["password", "pass", "token"] + +[[endpoints]] +path = "/nic/update" +[endpoints.params] +hostname = ["hostname"] +ipv4 = ["myip"] +ipv6 = ["myip6"] +username = ["username"] +password = ["password"] +``` + +**Default accepted parameter names** (first match wins): +| Value | Accepted Names | +|-------|----------------| +| Hostname (FQDN) | hostname, host | +| IPv4 address | myip, ipv4, ip4 | +| IPv6 address | myip6, ipv6, ip6 | +| Username | username, user | +| Password | password, pass, token | + +## CLI Usage + +### Initialize Database + +```bash +./ddns-daemon --init-db +``` + +### User Management + +```bash +# List users +./ddns-daemon user list + +# Add user (prompts for password) +./ddns-daemon user add myuser user@example.com + +# Delete user (fails if hostnames exist) +./ddns-daemon user delete myuser + +# Change password +./ddns-daemon user passwd myuser + +# Update email +./ddns-daemon user email myuser new@example.com +``` + +### Hostname Management + +```bash +# List all hostnames +./ddns-daemon hostname list + +# List hostnames for specific user +./ddns-daemon hostname list --user myuser + +# Add hostname +./ddns-daemon hostname add myuser mypc.dyn.example.com dyn.example.com + +# Add hostname with custom TTLs +./ddns-daemon hostname add myuser mypc.dyn.example.com dyn.example.com \ + --dns-ttl 60 --expiry-ttl 7200 + +# Modify hostname TTLs +./ddns-daemon hostname modify mypc.dyn.example.com --dns-ttl 120 + +# Delete hostname +./ddns-daemon hostname delete mypc.dyn.example.com +``` + +### Manual Cleanup + +```bash +./ddns-daemon cleanup +``` + +### Run Daemon + +```bash +./ddns-daemon --daemon + +# With debug logging +./ddns-daemon --daemon --debug +``` + +### Debug Mode + +Use `--debug` to enable debug logging for any command: + +```bash +./ddns-daemon --debug user list +./ddns-daemon --debug cleanup +``` + +## HTTP API + +### Request + +``` +GET /update?hostname=mypc.dyn.example.com[&myip=1.2.3.4][&myip6=2001:db8::1] +Authorization: Basic base64(username:password) +``` + +Authentication can also be provided as query parameters: +``` +GET /update?hostname=mypc.dyn.example.com&username=myuser&password=secret +``` + +### IP Detection + +- If `myip` or `myip6` provided: use those values +- If neither provided: use client's source IP +- IPv4 addresses create A records +- IPv6 addresses create AAAA records + +### Responses + +**Plain text (default, DynDNS-compatible):** +- `good ` - update successful +- `nochg ` - no change needed +- `badauth` - authentication failed +- `nohost` - hostname not found or not authorized +- `dnserr` - DNS update failed +- `abuse` - rate limit exceeded + +**JSON (with `Accept: application/json`):** +```json +{"status": "good", "ipv4": "1.2.3.4", "ipv6": "2001:db8::1"} +``` + +## Client Examples + +### curl + +```bash +curl -u "username:password" "https://ddns.example.com/update?hostname=mypc.dyn.example.com" +``` + +With explicit IP: +```bash +curl -u "username:password" "https://ddns.example.com/update?hostname=mypc.dyn.example.com&myip=1.2.3.4" +``` + +### wget + +```bash +wget -qO- --user=username --password=password \ + "https://ddns.example.com/update?hostname=mypc.dyn.example.com" +``` + +## Systemd Setup + +1. Create system user: +```bash +useradd -r -s /sbin/nologin ddns +``` + +2. Create directories: +```bash +mkdir -p /etc/ddns-daemon /var/lib/ddns-daemon +chown ddns:ddns /var/lib/ddns-daemon +``` + +3. Install files: +```bash +cp -r ddns_daemon /opt/ddns-daemon/ +cp ddns-daemon /opt/ddns-daemon/ +cp config.example.toml /etc/ddns-daemon/config.toml +cp ddns-daemon.service /etc/systemd/system/ +``` + +4. Configure and start: +```bash +# Edit config +vi /etc/ddns-daemon/config.toml + +# Initialize database +/opt/ddns-daemon/ddns_daemon.py --init-db + +# Enable and start +systemctl daemon-reload +systemctl enable ddns-daemon +systemctl start ddns-daemon +``` + +## Security Considerations + +- **Do not expose directly to the internet** - run behind a reverse proxy (e.g. nginx, caddy, apache) that handles TLS termination +- By default the daemon binds to localhost only; configure your reverse proxy to forward requests +- Passwords are hashed with Argon2 (memory-hard, resistant to GPU attacks) +- Rate limiting protects against brute-force attacks +- Database file should have restricted permissions +- Consider fail2ban for additional protection + +## TTL Behavior + +Each hostname has two TTL values: + +- **dns_ttl**: TTL value set on DNS records (default: 60 seconds) +- **expiry_ttl**: Time without updates before record is removed (default: 3600 seconds) + +Set `expiry_ttl = 0` to disable expiration entirely for a hostname. + +When a hostname expires: +1. DNS records (A and/or AAAA) are deleted +2. Email notification is sent to the user +3. Records can be restored by sending a new update request + +## Logging + +The daemon supports stdout and syslog logging targets. + +### Configuration Options + +| Option | Default | Description | +|--------|---------|-------------| +| `log_level` | INFO | DEBUG, INFO, WARNING, ERROR | +| `log_target` | stdout | stdout or syslog | +| `syslog_socket` | /dev/log | Path to syslog socket | +| `syslog_facility` | daemon | daemon, user, local0-7 | +| `log_requests` | false | Log HTTP request lines at INFO level | + +### Transaction IDs + +Each HTTP request is assigned a random 8-character transaction ID for log correlation. All log messages during request processing include this ID: + +``` +2025-01-17 12:34:56 [INFO] [a1b2c3d4] Updated: hostname=mypc.dyn.example.com ipv4=1.2.3.4 ipv6=N/A +``` + +### Syslog Format + +When using syslog, timestamps are omitted (syslog provides them): + +``` +ddns-daemon[12345]: [INFO] [a1b2c3d4] Updated: hostname=mypc.dyn.example.com ipv4=1.2.3.4 ipv6=N/A +``` + +### CLI Logging + +CLI commands run silently by default. Use `--debug` to enable logging output. + +## License + +GPL-3.0 diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..99c93db --- /dev/null +++ b/build.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +python -m build diff --git a/config.example.toml b/config.example.toml new file mode 100644 index 0000000..ab7ee93 --- /dev/null +++ b/config.example.toml @@ -0,0 +1,76 @@ +[daemon] +# host = "localhost" # default, use reverse proxy for public access! +# port = 8443 # default +# log_level = "INFO" # default +# log_target = "stdout" # default, "stdout", "syslog" or "file" +# syslog_socket = "/dev/log" # default +# syslog_facility = "daemon" # default +# log_file = "/var/log/ddns-daemon.log" # default, used if log_target = "file" +# log_file_size = 52428800 # default, 50 MB in bytes +# log_versions = 5 # default, 5 backup files +# log_requests = false # default +# ssl = false # default +ssl_cert_file = "/etc/ddns-daemon/cert.pem" # required if ssl = true +ssl_key_file = "/etc/ddns-daemon/key.pem" # required if ssl = true +# proxy_header = "" # default (disabled), header name e.g. "X-Forwarded-For" +# trusted_proxies = [] # default, list of trusted proxy IPs/CIDRs + +[database] +# backend = "sqlite" # default, "sqlite", or "mariadb" +path = "/var/lib/ddns-daemon/ddns.db" # required for sqlite +# host = "localhost" # required for mariadb +# port = 3306 # required for mariadb +# user = "ddns" # required for mariadb +# password = "secret" # required for mariadb +# database = "ddns" # required for mariadb + +[dns_service] +# manager_config_file = "/etc/dns-manager/config.yml" # default +# cleanup_interval = 60 # default, interval in seconds + +[defaults] +# dns_ttl = 60 # default, DNS record TTL in seconds +# expiry_ttl = 3600 # default, 0 to disable expiration + +[email] +# enabled = false # default +smtp_host = "localhost" # required if email.enabled +# smtp_port = 25 # default +# smtp_user = "" +# smtp_password = "" +# smtp_starttls = false +from_address = "ddns@example.com" # required if email.enabled + +[rate_limit] +# enabled = true # default +# good_window_seconds = 60 # default +# good_max_requests = 5 # default +# bad_window_seconds = 60 # default +# bad_max_requests = 3 # default +# cleanup_interval = 60 # default, interval in seconds + +# Endpoints (optional - defaults to single endpoint at /update) +# Default accepted parameter names: +# hostname (FQDN): hostname, host +# ipv4 (IPv4 address): myip, ipv4, ip4 +# ipv6 (IPv6 address): myip6, ipv6, ip6 +# username: username, user +# password: password, pass, token +# Multiple endpoints can be defined with custom parameter names +# [[endpoints]] +# path = "/update" +# [endpoints.params] +# hostname = ["hostname", "host"] +# ipv4 = ["myip", "ipv4", "ip4"] +# ipv6 = ["myip6", "ipv6", "ip6"] +# username = ["username", "user"] +# password = ["password", "pass", "token"] + +# [[endpoints]] +# path = "/nic/update" +# [endpoints.params] +# hostname = ["hostname"] +# ipv4 = ["myip"] +# ipv6 = ["myip6"] +# username = ["username"] +# password = ["password"] diff --git a/ddns-daemon.initd b/ddns-daemon.initd new file mode 100644 index 0000000..a0824fe --- /dev/null +++ b/ddns-daemon.initd @@ -0,0 +1,22 @@ +#!/sbin/openrc-run + +description="DDNS Daemon - Dynamic DNS Update Service" + +: ${USER:=ddns} +: ${GROUP:=ddns} +: ${OPTIONS:=} + +command="/usr/bin/ddns-daemon" +command_args="--daemon ${OPTIONS}" +command_user="${USER}:${GROUP}" +command_background="yes" +pidfile="/run/${RC_SVCNAME}.pid" + +depend() { + need net + after dns +} + +start_pre() { + checkpath --directory --owner ${USER}:${GROUP} --mode 0750 /var/lib/ddns-daemon +} diff --git a/ddns-daemon.service b/ddns-daemon.service new file mode 100644 index 0000000..f402246 --- /dev/null +++ b/ddns-daemon.service @@ -0,0 +1,23 @@ +[Unit] +Description=DDNS Daemon - Dynamic DNS Update Service +After=network.target + +[Service] +Type=simple +User=ddns +Group=ddns +WorkingDirectory=/opt/ddns-daemon +ExecStart=/usr/bin/ddns-daemon --daemon +ExecReload=/bin/kill -HUP $MAINPID +Restart=on-failure +RestartSec=5 + +# Security hardening +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +ReadWritePaths=/var/lib/ddns-daemon + +[Install] +WantedBy=multi-user.target diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..5c4dbc4 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,39 @@ +[build-system] +requires = ["setuptools >= 77.0.3"] +build-backend = "setuptools.build_meta" + +[tool.setuptools.dynamic] +version = {attr = "ddns_daemon.__version__"} + +[project] +name = "ddns_daemon" +dynamic = ["version"] +dependencies = [ + "dns-manager @ git+https://git.ccc-rheintal.ch/spacefreak/dns-manager.git", + "peewee>=3.17.0", + "argon2-cffi>=23.1.0", +] +requires-python = ">=3.11" +authors = [ + {name = "Thomas Oettli", email = "spacefreak@noop.ch"} +] +maintainers = [ + {name = "Thomas Oettli", email = "spacefreak@noop.ch"} +] +description = "Dynamic DNS update service with CLI administration." +readme = "README.md" +license = "GPL-3.0-only" +keywords = ["dns", "ddns", "daemon", "http", "https"] +classifiers = [ + "Development Status :: 4 - Beta", + "Topic :: Internet :: Name Service (DNS)", + "Intended Audience :: System Administrators", + "Programming Language :: Python :: 3" +] + +[project.optional-dependencies] +mysql = ["pymysql>=1.1.0"] + +[project.scripts] +ddns-daemon = "ddns_daemon.main:main" + diff --git a/src/ddns_daemon/__init__.py b/src/ddns_daemon/__init__.py new file mode 100644 index 0000000..fc351b0 --- /dev/null +++ b/src/ddns_daemon/__init__.py @@ -0,0 +1,24 @@ +""" +DDNS Daemon - Dynamic DNS update service. + +A daemon that accepts HTTP(S) requests to dynamically update DNS entries. +Includes CLI administration tools for user and hostname management. +""" + +__version__ = "1.0.0" +__author__ = "Thomas Oettli " + +__all__ = [ + "app", + "cleanup", + "cli", + "config", + "dns", + "email", + "logging", + "main", + "models", + "ratelimit", + "server", + "validation" +] diff --git a/src/ddns_daemon/app.py b/src/ddns_daemon/app.py new file mode 100644 index 0000000..fcada8a --- /dev/null +++ b/src/ddns_daemon/app.py @@ -0,0 +1,64 @@ +"""Application class - central dependency holder.""" + +import logging +import threading + +import argon2 + +from .dns import DNSService +from .email import EmailService +from .models import init_database +from .ratelimit import RateLimiter + + +class Application: + """ + Central application state holder. + + Holds configuration and all service instances. + """ + + def __init__(self, config): + """ + Initialize application with configuration. + + Args: + config: Configuration dictionary from TOML file. + """ + self.config = config + self.password_hasher = argon2.PasswordHasher() + self.shutdown_event = threading.Event() + + # Service instances (initialized separately) + self.dns_service = None + self.email_service = None + self.rate_limiter = None + + def init_database(self): + """Initialize database connection.""" + init_database(self.config) + logging.info("Database initialized") + + def init_dns(self): + """Initialize DNS service.""" + self.dns_service = DNSService(self.config) + logging.info("DNS service initialized") + + def init_email(self): + """Initialize email service.""" + self.email_service = EmailService(self.config) + logging.info("Email service initialized") + + def init_rate_limiter(self): + """Initialize rate limiter.""" + self.rate_limiter = RateLimiter(self.config) + logging.info("Rate limiter initialized") + + def signal_shutdown(self): + """Signal the application to shut down.""" + logging.info("Shutdown signaled") + self.shutdown_event.set() + + def is_shutting_down(self): + """Check if shutdown has been signaled.""" + return self.shutdown_event.is_set() diff --git a/src/ddns_daemon/cleanup.py b/src/ddns_daemon/cleanup.py new file mode 100644 index 0000000..d268492 --- /dev/null +++ b/src/ddns_daemon/cleanup.py @@ -0,0 +1,143 @@ +"""TTL cleanup functionality.""" + +import logging +import threading +from datetime import datetime, timedelta + +from .models import Hostname, User + + +def cleanup_expired(app): + """ + Clean up expired hostnames and return count of cleaned entries. + + Args: + app: Application instance with dns_service and email_service. + + Returns: + Number of expired hostnames processed. + """ + now = datetime.now() + expired_count = 0 + + for hostname in Hostname.select().join(User).where( + (Hostname.expiry_ttl != 0) & + ((Hostname.last_ipv4.is_null(False) & Hostname.last_ipv4_update.is_null(False)) | + (Hostname.last_ipv6.is_null(False) & Hostname.last_ipv6_update.is_null(False)))): + + ipv4_expired = False + ipv6_expired = False + + if hostname.last_ipv4: + expiry_time = hostname.last_ipv4_update + timedelta(seconds=hostname.expiry_ttl) + if now > expiry_time: + ipv4_expired = True + + if hostname.last_ipv6: + expiry_time = hostname.last_ipv6_update + timedelta(seconds=hostname.expiry_ttl) + if now > expiry_time: + ipv6_expired = True + + if not ipv4_expired and not ipv6_expired: + continue + + if app.dns_service: + if ipv4_expired: + logging.info( + f"Host expired: hostname={hostname.hostname} zone={hostname.zone} ip={hostname.last_ipv4}" + ) + app.dns_service.delete_record(hostname.hostname, hostname.zone, "A") + + if ipv6_expired: + logging.info( + f"Host expired: hostname={hostname.hostname} zone={hostname.zone} ip={hostname.last_ipv6}" + ) + app.dns_service.delete_record(hostname.hostname, hostname.zone, "AAAA") + + if app.email_service: + last_ipv4 = (hostname.last_ipv4, hostname.last_ipv4_update) if ipv4_expired else None + last_ipv6 = (hostname.last_ipv6, hostname.last_ipv6_update) if ipv6_expired else None + + app.email_service.send_expiry_notification( + hostname.user.email, + f"{hostname.hostname}.{hostname.zone}", + last_ipv4, + last_ipv6, + hostname.expiry_ttl + ) + + # Clear IP addresses + if ipv4_expired: + hostname.last_ipv4 = None + if ipv6_expired: + hostname.last_ipv6 = None + + if ipv4_expired or ipv6_expired: + hostname.save() + + expired_count += 1 + + return expired_count + + +class ExpiredRecordsCleanupThread(threading.Thread): + """Background thread for periodic expired records cleanup.""" + + def __init__(self, app): + """ + Initialize expired records cleanup thread. + + Args: + app: Application instance. + """ + super().__init__(daemon=True) + self.app = app + self.interval = app.config["dns_service"]["cleanup_interval"] + self.stop_event = threading.Event() + + def run(self): + """Run the cleanup loop.""" + logging.info(f"Expired records cleanup thread started: interval={self.interval}s") + + while not self.stop_event.wait(self.interval): + try: + count = cleanup_expired(self.app) + if count > 0: + logging.info(f"Expired records cleanup completed: count={count}") + except Exception as e: + logging.error(f"Expired records cleanup error: {e}") + + def stop(self): + """Signal the thread to stop.""" + self.stop_event.set() + + +class RateLimitCleanupThread(threading.Thread): + """Background thread for periodic rate limiter cleanup.""" + + def __init__(self, app): + """ + Initialize rate limiter cleanup thread. + + Args: + app: Application instance. + """ + super().__init__(daemon=True) + self.app = app + self.interval = app.config["rate_limit"]["cleanup_interval"] + self.stop_event = threading.Event() + + def run(self): + """Run the cleanup loop.""" + logging.info(f"Rate limit cleanup thread started: interval={self.interval}s") + + while not self.stop_event.wait(self.interval): + try: + if self.app.rate_limiter: + self.app.rate_limiter.cleanup() + except Exception as e: + logging.error(f"Rate limit cleanup error: {e}") + + def stop(self): + """Signal the thread to stop.""" + self.stop_event.set() diff --git a/src/ddns_daemon/cli.py b/src/ddns_daemon/cli.py new file mode 100644 index 0000000..0dd1789 --- /dev/null +++ b/src/ddns_daemon/cli.py @@ -0,0 +1,306 @@ +"""CLI commands for user and hostname management.""" + +import getpass +import logging + +from .cleanup import cleanup_expired +from .models import ( + create_tables, + DoesNotExist, + get_hostname, + get_user, + Hostname, + User, +) +from .validation import encode_hostname, encode_zone, ValidationError + + +def cmd_init_db(args, app): + """Initialize database tables.""" + create_tables() + print("Database tables created.") + return 0 + + +def cmd_user_list(args, app): + """List all users.""" + users = User.select() + if not users: + print("No users found.") + return 0 + + print(f"\n{'Username':<20} {'Email':<30} {'Hostnames':<10} {'Created'}") + print("-" * 82) + for user in users: + hostname_count = Hostname.select().where( + Hostname.user == user + ).count() + created_at = user.created_at.strftime("%Y-%m-%d %H:%M:%S") + + print( + f"{user.username:<20} {user.email:<30} " + f"{hostname_count:<10} {created_at}" + ) + return 0 + + +def cmd_user_add(args, app): + """Add a new user.""" + username = args.username + email = args.email + + # Check if user exists + if User.select().where(User.username == username).exists(): + print(f"Error: User '{username}' already exists.") + return 1 + + # Get password + password = getpass.getpass("Password: ") + password_confirm = getpass.getpass("Confirm password: ") + + if password != password_confirm: + print("Error: Passwords do not match.") + return 1 + + if len(password) < 8: + print("Error: Password must be at least 8 characters.") + return 1 + + # Hash password and create user + password_hash = app.password_hasher.hash(password) + User.create(username=username, email=email, password_hash=password_hash) + print(f"User '{username}' created.") + return 0 + + +def cmd_user_delete(args, app): + """Delete a user.""" + username = args.username + + try: + user = get_user(username) + except DoesNotExist: + print(f"Error: User '{username}' not found.") + return 1 + + # Check for hostnames + hostname_count = Hostname.select().where(Hostname.user == user).count() + if hostname_count > 0: + print(f"Error: User has {hostname_count} hostname(s). Delete them first.") + return 1 + + user.delete_instance() + print(f"User '{username}' deleted.") + return 0 + + +def cmd_user_passwd(args, app): + """Change user password.""" + username = args.username + + try: + user = get_user(username) + except DoesNotExist: + print(f"Error: User '{username}' not found.") + return 1 + + password = getpass.getpass("New password: ") + password_confirm = getpass.getpass("Confirm password: ") + + if password != password_confirm: + print("Error: Passwords do not match.") + return 1 + + if len(password) < 8: + print("Error: Password must be at least 8 characters.") + return 1 + + user.password_hash = app.password_hasher.hash(password) + user.save() + print(f"Password updated for '{username}'.") + return 0 + + +def cmd_user_email(args, app): + """Update user email.""" + username = args.username + email = args.email + + try: + user = get_user(username) + except DoesNotExist: + print(f"Error: User '{username}' not found.") + return 1 + + user.email = email + user.save() + print(f"Email updated for '{username}'.") + return 0 + + +def cmd_hostname_list(args, app): + """List hostnames.""" + query = Hostname.select().join(User) + + if args.user: + try: + user = get_user(args.user) + query = query.where(Hostname.user == user) + except DoesNotExist: + print(f"Error: User '{args.user}' not found.") + return 1 + + hostnames = list(query) + if not hostnames: + print("No hostnames found.") + return 0 + + print( + f"{'Hostname':<35} {'User':<15} {'Zone':<20} " + f"{'DNS-TTL':<8} {'Exp-TTL':<8} {'Last-Update IPv4':<21} {'Last-Update IPv6'}" + ) + print("-" * 132) + for h in hostnames: + last_ipv4_update = h.last_ipv4_update.strftime("%Y-%m-%d %H:%M:%S") if h.last_ipv4_update else "Never" + last_ipv6_update = h.last_ipv6_update.strftime("%Y-%m-%d %H:%M:%S") if h.last_ipv6_update else "Never" + print( + f"{h.hostname:<35} {h.user.username:<15} {h.zone:<20} " + f"{h.dns_ttl:<8} {h.expiry_ttl:<8} {last_ipv4_update:<21} {last_ipv6_update}" + ) + return 0 + + +def cmd_hostname_add(args, app): + """Add a hostname.""" + username = args.username + config = app.config + + # Validate and encode hostname/zone + try: + hostname_str = encode_hostname(args.hostname) + zone = encode_zone(args.zone) + except ValidationError as e: + print(f"Error: {e}") + return 1 + + # Get TTLs from args or config defaults + dns_ttl = args.dns_ttl + if dns_ttl is None: + dns_ttl = config["defaults"]["dns_ttl"] + expiry_ttl = args.expiry_ttl + if expiry_ttl is None: + expiry_ttl = config["defaults"]["expiry_ttl"] + + # Get user + try: + user = get_user(username) + except DoesNotExist: + print(f"Error: User '{username}' not found.") + return 1 + + # Check if hostname exists + if Hostname.select().where(Hostname.hostname == hostname_str).exists(): + print(f"Error: Hostname '{hostname_str}' already exists.") + return 1 + + # Create hostname + Hostname.create( + user=user, + hostname=hostname_str, + zone=zone, + dns_ttl=dns_ttl, + expiry_ttl=expiry_ttl + ) + print(f"Hostname '{hostname_str}' added for user '{username}'.") + return 0 + + +def cmd_hostname_delete(args, app): + """Delete a hostname.""" + # Validate and encode hostname + try: + hostname_str = encode_hostname(args.hostname) + except ValidationError as e: + print(f"Error: {e}") + return 1 + + try: + hostname = get_hostname(hostname_str) + except DoesNotExist: + print(f"Error: Hostname '{hostname_str}' not found.") + return 1 + + # Delete DNS records if active + if hostname.last_ipv4 or hostname.last_ipv6: + # Initialize DNS service if not already + if app.dns_service is None: + try: + app.init_dns() + except Exception as e: + logging.warning(f"DNS init failed: {e}") + + if app.dns_service: + if hostname.last_ipv4: + try: + app.dns_service.delete_record( + hostname.hostname, hostname.zone, "A" + ) + except Exception as e: + logging.warning(f"DNS delete failed: type=A error={e}") + if hostname.last_ipv6: + try: + app.dns_service.delete_record( + hostname.hostname, hostname.zone, "AAAA" + ) + except Exception as e: + logging.warning(f"DNS delete failed: type=AAAA error={e}") + + hostname.delete_instance() + print(f"Hostname '{hostname_str}' deleted.") + return 0 + + +def cmd_hostname_modify(args, app): + """Modify hostname settings.""" + # Validate and encode hostname + try: + hostname_str = encode_hostname(args.hostname) + except ValidationError as e: + print(f"Error: {e}") + return 1 + + try: + hostname = get_hostname(hostname_str) + except DoesNotExist: + print(f"Error: Hostname '{hostname_str}' not found.") + return 1 + + # Get new TTLs + dns_ttl = args.dns_ttl if args.dns_ttl is not None else hostname.dns_ttl + expiry_ttl = args.expiry_ttl if args.expiry_ttl is not None else hostname.expiry_ttl + + hostname.dns_ttl = dns_ttl + hostname.expiry_ttl = expiry_ttl + hostname.save() + print( + f"Hostname '{hostname_str}' updated: " + f"dns_ttl={dns_ttl}, expiry_ttl={expiry_ttl}" + ) + return 0 + + +def cmd_cleanup(args, app): + """Run cleanup manually.""" + # Initialize services if not already + if app.dns_service is None: + try: + app.init_dns() + except Exception as e: + logging.warning(f"DNS init failed: {e}") + + if app.email_service is None: + app.init_email() + + count = cleanup_expired(app) + print(f"Cleanup complete: {count} expired hostname(s) processed.") + return 0 diff --git a/src/ddns_daemon/config.py b/src/ddns_daemon/config.py new file mode 100644 index 0000000..6b64148 --- /dev/null +++ b/src/ddns_daemon/config.py @@ -0,0 +1,192 @@ +"""Configuration loading and management.""" + +import os + +try: + import tomllib +except ImportError: + import tomli as tomllib + + +# Default config paths (searched in order) +CONFIG_PATHS = [ + "/etc/ddns-daemon/config.toml", + "./config.toml", +] + +# Default endpoint parameter aliases +DEFAULT_ENDPOINT_PARAMS = { + "hostname": ["hostname", "host"], + "ipv4": ["myip", "ipv4", "ip4"], + "ipv6": ["myip6", "ipv6", "ip6"], + "username": ["username", "user"], + "password": ["password", "pass", "token"], +} + +VALID_PARAM_KEYS = frozenset(DEFAULT_ENDPOINT_PARAMS.keys()) + + +class ConfigError(Exception): + """Raised when configuration loading fails.""" + pass + + +def normalize_endpoint(endpoint): + """ + Normalize and validate endpoint configuration. + + Args: + endpoint: Raw endpoint dict from config. + + Returns: + Normalized endpoint dict with validated params. + + Raises: + ConfigError: If validation fails. + """ + if "path" not in endpoint: + raise ConfigError("Endpoint missing path") + + path = endpoint["path"] + if not isinstance(path, str) or not path.startswith("/"): + raise ConfigError("Endpoint path must start with /") + + # Start with defaults + params = {k: list(v) for k, v in DEFAULT_ENDPOINT_PARAMS.items()} + + # Override with user-defined params + if "params" in endpoint: + user_params = endpoint["params"] + if not isinstance(user_params, dict): + raise ConfigError("Endpoint params must be a dict") + + for key, aliases in user_params.items(): + if key not in VALID_PARAM_KEYS: + raise ConfigError("Unknown endpoint param: " + key) + + if not isinstance(aliases, list): + raise ConfigError("Param " + key + " aliases must be list") + + if not aliases: + raise ConfigError("Param " + key + " must have at least one alias") + + for alias in aliases: + if not isinstance(alias, str) or not alias: + raise ConfigError("Param " + key + " aliases must be non-empty strings") + + params[key] = aliases + + return {"path": path, "params": params} + + +def find_config_file(custom_path=None): + """ + Find and return the config file path. + + Args: + custom_path: Optional custom path to config file. + + Returns: + Path to config file. + + Raises: + ConfigError: If config file not found. + """ + if custom_path: + if os.path.isfile(custom_path): + return custom_path + raise ConfigError(f"Config file not found: {custom_path}") + + for path in CONFIG_PATHS: + if os.path.isfile(path): + return path + + raise ConfigError( + f"Config file not found. Searched: {', '.join(CONFIG_PATHS)}" + ) + + +def load_config(config_path): + """ + Load and validate configuration from TOML file. + + Args: + config_path: Path to config file. + + Returns: + Configuration dictionary with defaults applied. + + Raises: + ConfigError: If loading fails. + """ + try: + with open(config_path, "rb") as f: + cfg = tomllib.load(f) + except Exception as e: + raise ConfigError(f"Failed to load config: {e}") + + # Set defaults for missing sections + cfg.setdefault("daemon", {}) + cfg["daemon"].setdefault("host", "localhost") + cfg["daemon"].setdefault("port", 8443) + cfg["daemon"].setdefault("log_level", "INFO") + cfg["daemon"].setdefault("log_target", "stdout") + cfg["daemon"].setdefault("syslog_socket", "/dev/log") + cfg["daemon"].setdefault("syslog_facility", "daemon") + cfg["daemon"].setdefault("log_file", "/var/log/ddns-daemon.log") + cfg["daemon"].setdefault("log_file_size", 52428800) + cfg["daemon"].setdefault("log_versions", 5) + cfg["daemon"].setdefault("log_requests", False) + cfg["daemon"].setdefault("ssl", False) + cfg["daemon"].setdefault("proxy_header", "") + cfg["daemon"].setdefault("trusted_proxies", []) + + cfg.setdefault("database", {}) + cfg["database"].setdefault("backend", "sqlite") + + cfg.setdefault("dns_service", {}) + cfg["dns_service"].setdefault("manager_config_file", "/etc/dns-manager/config.yml") + cfg["dns_service"].setdefault("cleanup_interval", 60) + if cfg["dns_service"]["cleanup_interval"] < 1: + cfg["dns_service"]["cleanup_interval"] = 1 + + cfg.setdefault("defaults", {}) + cfg["defaults"].setdefault("dns_ttl", 60) + cfg["defaults"].setdefault("expiry_ttl", 3600) + + cfg.setdefault("email", {}) + cfg["email"].setdefault("enabled", False) + cfg["email"].setdefault("smtp_port", 25) + + cfg.setdefault("rate_limit", {}) + cfg["rate_limit"].setdefault("enabled", True) + cfg["rate_limit"].setdefault("good_window_seconds", 60) + cfg["rate_limit"].setdefault("good_max_requests", 5) + cfg["rate_limit"].setdefault("bad_window_seconds", 60) + cfg["rate_limit"].setdefault("bad_max_requests", 3) + cfg["rate_limit"].setdefault("cleanup_interval", 60) + if cfg["rate_limit"]["cleanup_interval"] < 1: + cfg["rate_limit"]["cleanup_interval"] = 1 + + # Process endpoints + if "endpoints" not in cfg: + # Create default endpoint + cfg["endpoints"] = [{ + "path": "/update", + "params": {k: list(v) for k, v in DEFAULT_ENDPOINT_PARAMS.items()}, + }] + else: + normalized = [] + paths_seen = set() + for ep in cfg["endpoints"]: + ep = normalize_endpoint(ep) + if ep["path"] in paths_seen: + raise ConfigError("Duplicate endpoint path: " + ep["path"]) + paths_seen.add(ep["path"]) + normalized.append(ep) + cfg["endpoints"] = normalized + + # Build path->endpoint lookup + cfg["_endpoint_map"] = {ep["path"]: ep for ep in cfg["endpoints"]} + + return cfg diff --git a/src/ddns_daemon/dns.py b/src/ddns_daemon/dns.py new file mode 100644 index 0000000..3308646 --- /dev/null +++ b/src/ddns_daemon/dns.py @@ -0,0 +1,152 @@ +"""DNS operations using dns-manager library.""" + +import ipaddress +import logging + +import dns.rdataset +import dns.rdatatype +from dnsmgr import DNSManager, name_from_text, rdata_from_text + + +def detect_ip_type(ip): + try: + addr = ipaddress.ip_address(ip) + if isinstance(addr, ipaddress.IPv4Address): + rdtype = 'A' + else: + rdtype = 'AAAA' + + return (rdtype, str(addr)) + + except ValueError: + raise ValueError(f"Invalid IP address: {ip}") + + +class DNSError(Exception): + """Raised when DNS operations fail.""" + pass + + +class DNSService: + """DNS service for managing DNS records.""" + + def __init__(self, config): + """ + Initialize DNS service. + + Args: + config: Application configuration dictionary. + + Raises: + DNSError: If initialization fails. + """ + try: + config_file = config["dns_service"]["manager_config_file"] + self.manager = DNSManager(config_file) + logging.debug(f"DNS manager initialized: config={config_file}") + except Exception as e: + raise DNSError(f"Failed to initialize DNS manager: {e}") + + def _get_zone(self, zone): + """Get zone object by name.""" + zones = self.manager.get_zones(zone) + if not zones: + raise DNSError(f"Zone not found: {zone}") + zone_obj = zones[0] + self.manager.get_zone_content(zone_obj) + return zone_obj + + def _get_relative_name(self, hostname, zone): + """Get hostname relative to zone.""" + if hostname.endswith("." + zone): + return hostname[:-len(zone) - 1] + return hostname + + def _delete_record(self, zone_obj, name, rdtype): + """Delete record if present.""" + deleted = False + zone_obj.filter_by_name(name, zone_obj.origin) + + node = zone_obj.get_node(name) + if not node: + return deleted + + for rdataset in zone_obj.get_node(name): + if rdataset.rdtype == rdtype: + self.manager.delete_zone_record(zone_obj, name, rdataset) + deleted = True + + return deleted + + def delete_record(self, hostname, zone, record_type): + """ + Delete DNS record(s) for the given hostname and record type. + + Args: + hostname: Fully qualified hostname. + zone: DNS zone name. + record_type: Record type (A or AAAA). + + Returns: + True if record was deleted. + + Raises: + DNSError: If delete fails. + """ + + try: + deleted = False + zone_obj = self._get_zone(zone) + name = name_from_text(hostname, zone_obj.origin) + rdtype = dns.rdatatype.from_text(record_type) + + if self._delete_record(zone_obj, name, rdtype): + logging.debug( + f"DNS record deleted: hostname={hostname} " + f"zone={zone_obj.origin} type={record_type}" + ) + + return deleted + + except Exception as e: + raise DNSError(f"Failed to delete DNS record for {hostname}: {e}") + + def update_record(self, hostname, zone, ip, ttl): + """ + Update a DNS record for the given hostname. + + Args: + hostname: Fully qualified hostname. + zone: DNS zone name. + ip: IP address to set. + ttl: DNS record TTL. + + Raises: + DNSError: If update fails. + """ + try: + record_type, normalized_ip = detect_ip_type(ip) + + zone_obj = self._get_zone(zone) + name = name_from_text(hostname, zone_obj.origin) + rdtype = dns.rdatatype.from_text(record_type) + + # Delete existing record if present + self._delete_record(zone_obj, name, rdtype) + + # Create new rdata + rdata = rdata_from_text(rdtype, normalized_ip, zone_obj.origin) + + # Create rdataset with TTL + rdataset = dns.rdataset.Rdataset(rdata.rdclass, rdata.rdtype) + rdataset.update_ttl(ttl) + rdataset.add(rdata) + + # Add the record + self.manager.add_zone_record(zone_obj, name, rdataset) + logging.debug( + f"DNS record updated: hostname={hostname} zone={zone_obj.origin} " + f"type={record_type} ip={normalized_ip} ttl={ttl}" + ) + except Exception as e: + raise DNSError(f"Failed to update DNS record for {hostname}: {e}") diff --git a/src/ddns_daemon/email.py b/src/ddns_daemon/email.py new file mode 100644 index 0000000..12088d9 --- /dev/null +++ b/src/ddns_daemon/email.py @@ -0,0 +1,104 @@ +"""Email notification functionality.""" + +import logging +import smtplib +from email.mime.text import MIMEText + + +class EmailService: + """Email service for sending notifications.""" + + def __init__(self, config): + """ + Initialize email service. + + Args: + config: Application configuration dictionary. + """ + self.config = config.get("email", {}) + self.enabled = self.config.get("enabled", False) + + def send(self, to, subject, body): + """ + Send email using configured SMTP server. + + Args: + to: Recipient email address. + subject: Email subject. + body: Email body text. + + Returns: + True if sent successfully, False otherwise. + """ + if not self.enabled: + logging.debug("Email disabled, skipping") + return False + + try: + msg = MIMEText(body) + msg["Subject"] = subject + msg["From"] = self.config["from_address"] + msg["To"] = to + + smtp_host = self.config["smtp_host"] + smtp_port = self.config["smtp_port"] + + server = smtplib.SMTP(smtp_host, smtp_port) + if self.config.get("smtp_starttls", False): + server.starttls() + + try: + if self.config.get("smtp_user"): + server.login( + self.config["smtp_user"], + self.config["smtp_password"] + ) + server.sendmail(msg["From"], [to], msg.as_string()) + logging.info(f"Email sent: to={to} subject={subject}") + return True + finally: + server.quit() + + except Exception as e: + logging.error(f"Email send failed: to={to} error={e}") + return False + + def send_expiry_notification( + self, + email, + hostname, + last_ipv4, + last_ipv6, + expiry_ttl + ): + """ + Send hostname expiry notification email. + + Args: + email: Recipient email. + hostname: Expired hostname. + last_ipv4: Tuple containing last IPv4 address and last update timestamp. + last_ipv6: Tuple containing last IPv6 address and last update timestamp. + expiry_ttl: Expiry TTL in seconds. + + Returns: + True if sent successfully. + """ + subject = f"DDNS hostname expired: {hostname}" + body = f"""Your dynamic DNS entry has expired due to inactivity. + +Hostname: {hostname} +""" + if last_ipv4: + ip = last_ipv4[0] + last_update = last_ipv4[1].strftime("%Y-%m-%d %H:%M:%S") + body += f"IPv4 address: {ip} (last update: {last_update})\n" + if last_ipv6: + ip = last_ipv6[0] + last_update = last_ipv6[1].strftime("%Y-%m-%d %H:%M:%S") + body += f"IPv6 address: {ip} (last update: {last_update})\n" + body += f"""Expiry TTL: {expiry_ttl} seconds + +The DNS records have been removed. Update your client to restore them. +""" + return self.send(email, subject, body) diff --git a/src/ddns_daemon/logging.py b/src/ddns_daemon/logging.py new file mode 100644 index 0000000..683459d --- /dev/null +++ b/src/ddns_daemon/logging.py @@ -0,0 +1,141 @@ +"""Centralized logging configuration.""" + +import logging +import logging.handlers +import secrets +from contextvars import ContextVar + +# Transaction ID context (thread-safe per-request) +_txn_id = ContextVar("txn_id", default="-") + +# Syslog facility mapping +SYSLOG_FACILITIES = { + "daemon": logging.handlers.SysLogHandler.LOG_DAEMON, + "user": logging.handlers.SysLogHandler.LOG_USER, + "local0": logging.handlers.SysLogHandler.LOG_LOCAL0, + "local1": logging.handlers.SysLogHandler.LOG_LOCAL1, + "local2": logging.handlers.SysLogHandler.LOG_LOCAL2, + "local3": logging.handlers.SysLogHandler.LOG_LOCAL3, + "local4": logging.handlers.SysLogHandler.LOG_LOCAL4, + "local5": logging.handlers.SysLogHandler.LOG_LOCAL5, + "local6": logging.handlers.SysLogHandler.LOG_LOCAL6, + "local7": logging.handlers.SysLogHandler.LOG_LOCAL7, +} + + +def get_txn_id(): + """Get current transaction ID.""" + return _txn_id.get() + + +def set_txn_id(txn_id=None): + """Set transaction ID, generate if not provided.""" + if txn_id is None: + txn_id = secrets.token_hex(4) + _txn_id.set(txn_id) + return txn_id + + +def clear_txn_id(): + """Reset transaction ID to default.""" + _txn_id.set("-") + + +class TxnIdFilter(logging.Filter): + """Inject txn_id into log records.""" + + def filter(self, record): + record.txn_id = get_txn_id() + return True + + +class TxnIdFormatter(logging.Formatter): + """Formatter that conditionally includes transaction ID.""" + + def __init__(self, fmt_with_txn, fmt_without_txn, datefmt=None): + super().__init__(fmt_with_txn, datefmt) + self.fmt_with_txn = fmt_with_txn + self.fmt_without_txn = fmt_without_txn + + def format(self, record): + if hasattr(record, "txn_id") and record.txn_id != "-": + self._style._fmt = self.fmt_with_txn + else: + self._style._fmt = self.fmt_without_txn + return super().format(record) + + +def setup_logging( + level="INFO", + target="stdout", + syslog_socket="/dev/log", + syslog_facility="daemon", + log_file="/var/log/ddns-daemon.log", + log_file_size=52428800, + log_versions=5, +): + """ + Configure global logging. + + Args: + level: Log level name (DEBUG, INFO, WARNING, ERROR) + target: "stdout", "syslog", or "file" + syslog_socket: Path to syslog socket + syslog_facility: Syslog facility name + log_file: Path to log file (for target="file") + log_file_size: Max log file size in bytes before rotation + log_versions: Number of backup files to keep + """ + root = logging.getLogger() + root.setLevel(getattr(logging, level.upper(), logging.INFO)) + + # Clear existing handlers + root.handlers.clear() + + txn_filter = TxnIdFilter() + + if target == "syslog": + facility = SYSLOG_FACILITIES.get( + syslog_facility.lower(), + logging.handlers.SysLogHandler.LOG_DAEMON, + ) + handler = logging.handlers.SysLogHandler( + address=syslog_socket, + facility=facility, + ) + formatter = TxnIdFormatter( + "ddns-daemon[%(process)d]: [%(levelname)s] [%(txn_id)s] %(message)s", + "ddns-daemon[%(process)d]: [%(levelname)s] %(message)s", + ) + elif target == "file": + handler = logging.handlers.RotatingFileHandler( + log_file, + maxBytes=log_file_size, + backupCount=log_versions, + ) + formatter = TxnIdFormatter( + "%(asctime)s [%(levelname)s] [%(txn_id)s] %(message)s", + "%(asctime)s [%(levelname)s] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + else: + handler = logging.StreamHandler() + formatter = TxnIdFormatter( + "%(asctime)s [%(levelname)s] [%(txn_id)s] %(message)s", + "%(asctime)s [%(levelname)s] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + handler.addFilter(txn_filter) + handler.setFormatter(formatter) + root.addHandler(handler) + + +def disable_logging(): + """Disable all logging (for CLI quiet mode).""" + logging.disable(logging.CRITICAL) + + +def enable_logging(): + """Re-enable logging.""" + logging.disable(logging.NOTSET) diff --git a/src/ddns_daemon/main.py b/src/ddns_daemon/main.py new file mode 100644 index 0000000..775ab61 --- /dev/null +++ b/src/ddns_daemon/main.py @@ -0,0 +1,182 @@ +""" +DDNS Daemon - Dynamic DNS update service. + +Main executable for CLI and daemon mode. +""" + +import argparse +import sys + +from . import __version__ +from .app import Application +from .cli import ( + cmd_cleanup, + cmd_hostname_add, + cmd_hostname_delete, + cmd_hostname_list, + cmd_hostname_modify, + cmd_init_db, + cmd_user_add, + cmd_user_delete, + cmd_user_email, + cmd_user_list, + cmd_user_passwd, +) +from .config import ConfigError, find_config_file, load_config +from .logging import disable_logging, setup_logging +from .server import run_daemon + + +def build_parser(): + """Build the argument parser.""" + parser = argparse.ArgumentParser( + description="DDNS Daemon - Dynamic DNS update service", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument( + "--version", action="version", version=f"%(prog)s {__version__}" + ) + parser.add_argument("-c", "--config", help="Path to config file") + parser.add_argument( + "-d", "--daemon", action="store_true", help="Run as daemon" + ) + parser.add_argument( + "--init-db", action="store_true", help="Initialize database" + ) + parser.add_argument( + "--debug", action="store_true", help="Enable debug logging" + ) + + subparsers = parser.add_subparsers(dest="command", title="commands") + + # User commands + user_parser = subparsers.add_parser("user", help="User management") + user_subparsers = user_parser.add_subparsers(dest="user_command") + + user_list = user_subparsers.add_parser("list", help="List users") + user_list.set_defaults(func=cmd_user_list) + + user_add = user_subparsers.add_parser("add", help="Add user") + user_add.add_argument("username", help="Username") + user_add.add_argument("email", help="Email address") + user_add.set_defaults(func=cmd_user_add) + + user_delete = user_subparsers.add_parser("delete", help="Delete user") + user_delete.add_argument("username", help="Username") + user_delete.set_defaults(func=cmd_user_delete) + + user_passwd = user_subparsers.add_parser("passwd", help="Change password") + user_passwd.add_argument("username", help="Username") + user_passwd.set_defaults(func=cmd_user_passwd) + + user_email = user_subparsers.add_parser("email", help="Update email") + user_email.add_argument("username", help="Username") + user_email.add_argument("email", help="New email address") + user_email.set_defaults(func=cmd_user_email) + + # Hostname commands + hostname_parser = subparsers.add_parser("hostname", help="Hostname management") + hostname_subparsers = hostname_parser.add_subparsers(dest="hostname_command") + + hostname_list = hostname_subparsers.add_parser("list", help="List hostnames") + hostname_list.add_argument("--user", help="Filter by username") + hostname_list.set_defaults(func=cmd_hostname_list) + + hostname_add = hostname_subparsers.add_parser("add", help="Add hostname") + hostname_add.add_argument("username", help="Username") + hostname_add.add_argument("hostname", help="Hostname (FQDN)") + hostname_add.add_argument("zone", help="DNS zone") + hostname_add.add_argument("--dns-ttl", type=int, help="DNS record TTL") + hostname_add.add_argument("--expiry-ttl", type=int, help="Expiry TTL") + hostname_add.set_defaults(func=cmd_hostname_add) + + hostname_delete = hostname_subparsers.add_parser( + "delete", help="Delete hostname" + ) + hostname_delete.add_argument("hostname", help="Hostname (FQDN)") + hostname_delete.set_defaults(func=cmd_hostname_delete) + + hostname_modify = hostname_subparsers.add_parser( + "modify", help="Modify hostname" + ) + hostname_modify.add_argument("hostname", help="Hostname (FQDN)") + hostname_modify.add_argument("--dns-ttl", type=int, help="DNS record TTL") + hostname_modify.add_argument("--expiry-ttl", type=int, help="Expiry TTL") + hostname_modify.set_defaults(func=cmd_hostname_modify) + + # Cleanup command + cleanup_parser = subparsers.add_parser("cleanup", help="Run cleanup manually") + cleanup_parser.set_defaults(func=cmd_cleanup) + + return parser + + +def main(): + """Main entry point.""" + parser = build_parser() + args = parser.parse_args() + + # Load config + try: + config_path = find_config_file(args.config) + config = load_config(config_path) + except ConfigError as e: + print(f"Error: {e}", file=sys.stderr) + return 1 + + # Setup logging based on mode + if args.daemon: + log_level = "DEBUG" if args.debug else config["daemon"]["log_level"] + setup_logging( + level=log_level, + target=config["daemon"]["log_target"], + syslog_socket=config["daemon"]["syslog_socket"], + syslog_facility=config["daemon"]["syslog_facility"], + log_file=config["daemon"]["log_file"], + log_file_size=config["daemon"]["log_file_size"], + log_versions=config["daemon"]["log_versions"], + ) + else: + if args.debug: + setup_logging(level="DEBUG", target="stdout") + else: + disable_logging() + + # Create application instance + app = Application(config) + + # Initialize database + try: + app.init_database() + except Exception as e: + print(f"Error: Database initialization failed: {e}", file=sys.stderr) + return 1 + + # Handle --init-db + if args.init_db: + return cmd_init_db(args, app) + + # Handle --daemon + if args.daemon: + try: + # Initialize all services for daemon mode + app.init_dns() + app.init_email() + app.init_rate_limiter() + run_daemon(app) + return 0 + except Exception as e: + print(f"Error: Daemon error: {e}", file=sys.stderr) + return 1 + + # Handle subcommands + if args.command and hasattr(args, "func"): + return args.func(args, app) + + # No command specified + parser.print_help() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/ddns_daemon/models.py b/src/ddns_daemon/models.py new file mode 100644 index 0000000..16d333a --- /dev/null +++ b/src/ddns_daemon/models.py @@ -0,0 +1,172 @@ +"""Database models and initialization.""" + +import logging +import os +from datetime import datetime + +from peewee import ( + AutoField, + CharField, + DateTimeField, + DoesNotExist, + ForeignKeyField, + IntegerField, + Model, + MySQLDatabase, + SqliteDatabase, +) + +# Database instance (initialized later) +db = SqliteDatabase(None) + + +class BaseModel(Model): + """Base model with database binding.""" + + class Meta: + database = db + + +class User(BaseModel): + """User model for authentication.""" + + id = AutoField() + username = CharField(max_length=64, unique=True) + password_hash = CharField(max_length=128) + email = CharField(max_length=255) + created_at = DateTimeField(default=datetime.now) + + class Meta: + table_name = "users" + + +class Hostname(BaseModel): + """Hostname model for DNS records.""" + + id = AutoField() + user = ForeignKeyField(User, backref="hostnames", on_delete="RESTRICT") + hostname = CharField(max_length=255, unique=True) + zone = CharField(max_length=255) + dns_ttl = IntegerField() + expiry_ttl = IntegerField() + last_ipv4 = CharField(max_length=15, null=True) + last_ipv4_update = DateTimeField(null=True) + last_ipv6 = CharField(max_length=45, null=True) + last_ipv6_update = DateTimeField(null=True) + + class Meta: + table_name = "hostnames" + + +def init_database(config: dict): + """ + Initialize database connection based on config. + + Args: + config: Configuration dictionary. + + Raises: + ValueError: If unknown database backend. + """ + global db + + backend = config["database"].get("backend", "sqlite") + + if backend == "sqlite": + db_path = config["database"].get("path", "./ddns.db") + db_dir = os.path.dirname(db_path) + if db_dir: + os.makedirs(db_dir, exist_ok=True) + db.init(db_path) + logging.info(f"Database backend: SQLite path={db_path}") + + elif backend == "mariadb": + new_db = MySQLDatabase( + config["database"]["database"], + host=config["database"].get("host", "localhost"), + port=config["database"].get("port", 3306), + user=config["database"]["user"], + password=config["database"]["password"], + ) + # Re-bind models to new database + User._meta.database = new_db + Hostname._meta.database = new_db + # Replace global db reference + db = new_db + logging.info(f"Database backend: MariaDB db={config['database']['database']}") + + else: + raise ValueError(f"Unknown database backend: {backend}") + + db.connect() + + +def create_tables(): + """Create database tables if they don't exist.""" + db.create_tables([User, Hostname]) + logging.info("Database tables created") + + +def get_user(username: str): + """ + Get user by username. + + Args: + username: Username to look up. + + Returns: + User instance. + + Raises: + DoesNotExist: If user not found. + """ + return User.get(User.username == username) + + +def get_hostname(hostname: str): + """ + Get hostname by name. + + Args: + hostname: Hostname to look up. + + Returns: + Hostname instance. + + Raises: + DoesNotExist: If hostname not found. + """ + return Hostname.get(Hostname.hostname == hostname) + + +def get_hostname_for_user(hostname: str, user: User): + """ + Get hostname owned by specific user. + + Args: + hostname: Hostname to look up. + user: User who should own the hostname. + + Returns: + Hostname instance. + + Raises: + DoesNotExist: If hostname not found or not owned by user. + """ + return Hostname.get( + ((Hostname.hostname + '.' + Hostname.zone) == hostname) & (Hostname.user == user) + ) + + +# Re-export DoesNotExist for convenience +__all__ = [ + 'db', + 'User', + 'Hostname', + 'init_database', + 'create_tables', + 'get_user', + 'get_hostname', + 'get_hostname_for_user', + 'DoesNotExist', +] diff --git a/src/ddns_daemon/ratelimit.py b/src/ddns_daemon/ratelimit.py new file mode 100644 index 0000000..5943e0a --- /dev/null +++ b/src/ddns_daemon/ratelimit.py @@ -0,0 +1,129 @@ +"""Rate limiting with sliding window.""" + +import threading +import time +from collections import defaultdict + + +class RateLimiter: + """Sliding window rate limiter with separate good/bad request tracking.""" + + def __init__(self, config): + """ + Initialize rate limiter from config. + + Args: + config: Full configuration dictionary. + """ + rl_config = config.get("rate_limit", {}) + self.enabled = rl_config.get("enabled", False) + self.good_window = rl_config.get("good_window_seconds", 60) + self.good_max = rl_config.get("good_max_requests", 30) + self.bad_window = rl_config.get("bad_window_seconds", 60) + self.bad_max = rl_config.get("bad_max_requests", 5) + + self.bad_requests = defaultdict(list) + self.good_requests = defaultdict(list) + self.bad_lock = threading.Lock() + self.good_lock = threading.Lock() + + def _cleanup_old(self, timestamps, window): + """Remove timestamps older than window.""" + cutoff = time.time() - window + return [t for t in timestamps if t > cutoff] + + def is_blocked_bad(self, ip): + """ + Check if IP is blocked by the bad request rate limiter with recording + when IP is already limited. + + Args: + ip: Client IP address. + + Returns: + Tuple of (blocked, retry_after_seconds). + """ + if not self.enabled: + return False, 0 + + now = time.time() + + with self.bad_lock: + # Check bad requests + self.bad_requests[ip] = self._cleanup_old( + self.bad_requests[ip], self.bad_window + ) + if len(self.bad_requests[ip]) >= self.bad_max: + self.bad_requests[ip].append(time.time()) + oldest = min(self.bad_requests[ip][-self.bad_max:]) + retry_after = int(oldest + self.bad_window - now) + 1 + return True, max(1, retry_after) + + return False, 0 + + def is_blocked_good(self, ip): + """ + Check if IP is blocked by the good request rate limiter without recording. + + Args: + ip: Client IP address. + + Returns: + Tuple of (blocked, retry_after_seconds). + """ + if not self.enabled: + return False, 0 + + now = time.time() + + with self.good_lock: + # Check good requests + self.good_requests[ip] = self._cleanup_old( + self.good_requests[ip], self.good_window + ) + if len(self.good_requests[ip]) >= self.good_max: + oldest = min(self.good_requests[ip]) + retry_after = int(oldest + self.good_window - now) + 1 + return True, max(1, retry_after) + + return False, 0 + + def record_bad(self, ip): + """Record a bad request (without checking).""" + if not self.enabled: + return + + with self.bad_lock: + self.bad_requests[ip] = self._cleanup_old( + self.bad_requests[ip], self.bad_window + ) + self.bad_requests[ip].append(time.time()) + + def record_good(self, ip): + """Record a good request (without checking).""" + if not self.enabled: + return + + with self.good_lock: + self.good_requests[ip] = self._cleanup_old( + self.good_requests[ip], self.good_window + ) + self.good_requests[ip].append(time.time()) + + def cleanup(self): + """Remove stale entries to prevent memory leak.""" + with self.good_lock: + for ip in list(self.good_requests.keys()): + self.good_requests[ip] = self._cleanup_old( + self.good_requests[ip], self.good_window + ) + if not self.good_requests[ip]: + del self.good_requests[ip] + + with self.bad_lock: + for ip in list(self.bad_requests.keys()): + self.bad_requests[ip] = self._cleanup_old( + self.bad_requests[ip], self.bad_window + ) + if not self.bad_requests[ip]: + del self.bad_requests[ip] diff --git a/src/ddns_daemon/server.py b/src/ddns_daemon/server.py new file mode 100644 index 0000000..37d2d56 --- /dev/null +++ b/src/ddns_daemon/server.py @@ -0,0 +1,447 @@ +"""HTTP(S) server for DDNS updates.""" + +from __future__ import annotations + +import base64 +import ipaddress +import json +import logging +import signal +import ssl +from datetime import datetime +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +import argon2 + +from .cleanup import ExpiredRecordsCleanupThread, RateLimitCleanupThread +from .dns import detect_ip_type +from .logging import clear_txn_id, set_txn_id +from .models import DoesNotExist, get_hostname_for_user, get_user +from .validation import encode_hostname, ValidationError + + +def extract_param(params, aliases): + """Extract first matching param from query params.""" + for alias in aliases: + val = params.get(alias, [None])[0] + if val is not None: + return val + return None + + +class ProxyHeaderError(Exception): + """Raised when expected proxy header is missing.""" + pass + + +def _parse_trusted_proxies(proxies): + """Parse list of IPs/networks into ip_network objects.""" + networks = [] + for proxy in proxies: + try: + if "/" not in proxy: + addr = ipaddress.ip_address(proxy) + if addr.version == 4: + proxy = proxy + "/32" + else: + proxy = proxy + "/128" + networks.append(ipaddress.ip_network(proxy, strict=False)) + except ValueError: + logging.warning(f"Invalid trusted proxy: {proxy}") + return networks + + +def _is_trusted_proxy(client_ip, trusted_networks): + """Check if client IP is in trusted proxy networks.""" + try: + addr = ipaddress.ip_address(client_ip) + for network in trusted_networks: + if addr in network: + return True + except ValueError: + pass + return False + + +class DDNSServer(ThreadingHTTPServer): + """HTTP server with Application instance.""" + + def __init__(self, app, address): + """ + Initialize server with application. + + Args: + app: Application instance. + address: (host, port) tuple. + """ + self.app = app + self.proxy_header = app.config["daemon"].get("proxy_header", "") + self.trusted_networks = _parse_trusted_proxies( + app.config["daemon"].get("trusted_proxies", []) + ) + super().__init__(address, DDNSRequestHandler) + + +class DDNSRequestHandler(BaseHTTPRequestHandler): + """HTTP request handler for DDNS updates.""" + + @property + def app(self): + """Get application instance from server.""" + return self.server.app + + def log_message(self, format_str, *args): + """Override to use our logger.""" + msg = f"{self.address_string()} - {format_str % args}" + if self.app.config["daemon"]["log_requests"]: + logging.info(msg) + else: + logging.debug(msg) + + def send_response_body(self, code, body, content_type="text/plain"): + """Send response with body.""" + self.send_response(code) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body.encode()) + + def wants_json(self): + """Check if client wants JSON response.""" + accept = self.headers.get("Accept", "") + return "application/json" in accept + + def respond(self, code, status, **kwargs): + """Send response in appropriate format.""" + if self.wants_json(): + data = {"status": status, **kwargs} + self.send_response_body(code, json.dumps(data), "application/json") + else: + # DynDNS-compatible plain text + parts = [status] + if "ipv4" in kwargs and kwargs["ipv4"]: + parts.append(kwargs["ipv4"]) + if "ipv6" in kwargs and kwargs["ipv6"]: + parts.append(kwargs["ipv6"]) + self.send_response_body(code, " ".join(parts)) + + def get_client_ip(self): + """Get client IP, considering configured proxy header if trusted.""" + direct_ip = self.client_address[0] + + proxy_header = self.server.proxy_header + if not proxy_header: + return direct_ip + + if not _is_trusted_proxy(direct_ip, self.server.trusted_networks): + return direct_ip + + forwarded = self.headers.get(proxy_header) + if not forwarded: + raise ProxyHeaderError( + f"Missing {proxy_header} header from trusted proxy" + ) + + return forwarded.split(",")[0].strip() + + def parse_basic_auth(self): + """Parse Basic Auth header.""" + auth = self.headers.get("Authorization", "") + if not auth.startswith("Basic "): + return None, None + try: + decoded = base64.b64decode(auth[6:]).decode("utf-8") + if ":" in decoded: + username, password = decoded.split(":", 1) + return username, password + except Exception: + pass + return None, None + + def do_GET(self): + """Handle GET requests.""" + set_txn_id() + try: + self._handle_get_request() + finally: + clear_txn_id() + + def _handle_get_request(self): + """Handle GET request logic.""" + try: + client_ip = self.get_client_ip() + except ProxyHeaderError as e: + logging.error(f"Proxy header error: {e}") + self.send_response_body(400, "Bad Request") + return + + # Bad rate limit check + if self.app.rate_limiter: + blocked, retry = self.app.rate_limiter.is_blocked_bad(client_ip) + if blocked: + logging.warning( + f"Rate limited (bad requests): client={client_ip}, " + f"retry_after={retry}") + self.respond(429, "abuse") + return + + # Parse URL + parsed = urlparse(self.path) + + # Find matching endpoint + endpoint = self.app.config["_endpoint_map"].get(parsed.path) + if endpoint is None: + self.send_response_body(404, "Not Found") + return + + # Parse query parameters + params = parse_qs(parsed.query) + + # Get credentials + username, password = self.parse_basic_auth() + if username is None: + username = extract_param(params, endpoint["params"]["username"]) + password = extract_param(params, endpoint["params"]["password"]) + + if not username or not password: + logging.warning(f"Auth failed: client={client_ip} user=anonymous") + self._handle_bad_request(client_ip, 401, "badauth") + return + + # Validate credentials + try: + user = get_user(username) + self.app.password_hasher.verify(user.password_hash, password) + except (DoesNotExist, argon2.exceptions.VerifyMismatchError): + logging.warning(f"Auth failed: client={client_ip} user={username}") + self._handle_bad_request(client_ip, 401, "badauth") + return + + # Get hostname parameter + hostname_param = extract_param(params, endpoint["params"]["hostname"]) + if not hostname_param: + logging.warning(f"Missing hostname: client={client_ip} user={username}") + self._handle_bad_request(client_ip, 400, "nohost") + return + + # Validate and encode hostname + try: + hostname_param = encode_hostname(hostname_param) + except ValidationError: + logging.warning( + f"Invalid hostname: client={client_ip}, " + f"hostname={hostname_param}") + self._handle_bad_request(client_ip, 400, "nohost") + return + + # Check hostname ownership + try: + hostname = get_hostname_for_user(hostname_param, user) + except DoesNotExist: + logging.warning( + f"Access denied: client={client_ip} user={username} " + f"hostname={hostname_param}" + ) + self._handle_bad_request(client_ip, 403, "nohost") + return + + # Good rate limit check + if self.app.rate_limiter: + blocked, retry = self.app.rate_limiter.is_blocked_good(client_ip) + if blocked: + logging.warning(f"Rate limited: client={client_ip}, retry_after={retry}") + self.respond(429, "abuse", retry_after=retry) + return + + # Record good request + if self.app.rate_limiter: + self.app.rate_limiter.record_good(client_ip) + + # Determine IPs to update + result = self._process_ip_update(hostname, params, endpoint, client_ip) + if result: + code, status, *kwargs = result + if kwargs: + self.respond(code, status, **kwargs[0]) + else: + self.respond(code, status) + + def _handle_bad_request(self, client_ip, code, status): + """Handle bad request and record in rate limiter.""" + if self.app.rate_limiter: + self.app.rate_limiter.record_bad(client_ip) + self.respond(code, status) + + def _process_ip_update(self, hostname, params, endpoint, client_ip): + """Process IP update for hostname.""" + myip = extract_param(params, endpoint["params"]["ipv4"]) + myip6 = extract_param(params, endpoint["params"]["ipv6"]) + + ipv4 = None + ipv6 = None + + # Process myip parameter + if myip: + try: + rtype, myip = detect_ip_type(myip) + if rtype == "A": + ipv4 = myip + else: + ipv6 = myip + except ValueError: + return (400, "badip") + + # Process myip6 parameter + if myip6: + try: + rtype, myip6 = detect_ip_type(myip6) + if rtype == "AAAA": + ipv6 = myip6 + else: + return (400, "badip") + except ValueError: + return (400, "badip") + + # Auto-detect from client IP if no params + if ipv4 is None and ipv6 is None: + try: + rtype, ip = detect_ip_type(client_ip) + if rtype == "A": + ipv4 = ip + else: + ipv6 = ip + except ValueError: + return (400, "badip") + + now = datetime.now() + + changed = False + if ipv4: + hostname.last_ipv4_update = now + if ipv4 != hostname.last_ipv4: + # Update DNS IPv4 record + try: + self.app.dns_service.update_record( + hostname.hostname, + hostname.zone, + ipv4, + hostname.dns_ttl + ) + hostname.last_ipv4 = ipv4 + changed = True + except Exception as e: + hostname.save() + logging.error( + f"DNS update failed: client={client_ip} hostname={hostname.hostname} " + f"zone={hostname.zone} ipv4={ipv4} error={e}" + ) + return (500, "dnserr") + + if ipv6: + hostname.last_ipv6_update = now + if ipv6 != hostname.last_ipv6: + # Update DNS IPv6 record + try: + self.app.dns_service.update_record( + hostname.hostname, + hostname.zone, + ipv6, + hostname.dns_ttl + ) + hostname.last_ipv6 = ipv6 + changed = True + except Exception as e: + hostname.save() + logging.error( + f"DNS update failed: client={client_ip} hostname={hostname.hostname} " + f"zone={hostname.zone} ipv6={ipv6} error={e}" + ) + return (500, "dnserr") + + # Update database + hostname.save() + + changed_addrs = "" + if ipv4: + changed_addrs += f"ipv4={ipv4}" + if ipv6: + changed_addrs += f" ipv6={ipv6}" + + if not changed: + logging.info( + f"No change: client={client_ip} hostname={hostname.hostname} " + f"zone={hostname.zone} {changed_addrs}" + ) + return ( + 200, "nochg", + {"ipv4": hostname.last_ipv4, "ipv6": hostname.last_ipv6} + ) + + logging.info( + f"Updated: client={client_ip} hostname={hostname.hostname} " + f"zone={hostname.zone} {changed_addrs}" + ) + return ( + 200, "good", + {"ipv4": hostname.last_ipv4, "ipv6": hostname.last_ipv6} + ) + + +def run_daemon(app): + """ + Run the DDNS daemon. + + Args: + app: Application instance with initialized services. + """ + config = app.config + + # Setup server + host = config["daemon"]["host"] + port = config["daemon"]["port"] + + server = DDNSServer(app, (host, port)) + + # Setup TLS if enabled + if config["daemon"]["ssl"]: + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain( + config["daemon"]["ssl_cert_file"], + config["daemon"]["ssl_key_file"] + ) + server.socket = context.wrap_socket(server.socket, server_side=True) + proto = "https" + else: + proto = "http" + + # Start cleanup threads + expired_cleanup_thread = ExpiredRecordsCleanupThread(app) + expired_cleanup_thread.start() + + ratelimit_cleanup_thread = RateLimitCleanupThread(app) + ratelimit_cleanup_thread.start() + + # Setup signal handlers + def signal_handler(signum, frame): + logging.info(f"Signal received: {signum}, shutting down") + app.signal_shutdown() + + signal.signal(signal.SIGTERM, signal_handler) + signal.signal(signal.SIGINT, signal_handler) + + paths = ", ".join(ep["path"] for ep in config["endpoints"]) + logging.info(f"Daemon started: {proto}://{host}:{port} endpoints=[{paths}]") + + # Run server + server.timeout = 1.0 + while not app.is_shutting_down(): + server.handle_request() + + # Cleanup + expired_cleanup_thread.stop() + ratelimit_cleanup_thread.stop() + expired_cleanup_thread.join(timeout=5) + ratelimit_cleanup_thread.join(timeout=5) + server.server_close() + logging.info("Daemon stopped") diff --git a/src/ddns_daemon/validation.py b/src/ddns_daemon/validation.py new file mode 100644 index 0000000..2048ead --- /dev/null +++ b/src/ddns_daemon/validation.py @@ -0,0 +1,138 @@ +"""Hostname and zone validation with punycode support.""" + +import re + + +# Valid hostname label pattern (after punycode encoding) +LABEL_PATTERN = re.compile(r'^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$', re.IGNORECASE) + + +class ValidationError(Exception): + """Raised when validation fails.""" + pass + + +def encode_hostname(hostname): + """ + Encode hostname to ASCII using punycode (IDNA). + + Args: + hostname: Hostname string, possibly with unicode characters. + + Returns: + ASCII-encoded hostname. + + Raises: + ValidationError: If hostname is invalid. + """ + hostname = hostname.lower().strip() + + if not hostname: + raise ValidationError("Hostname cannot be empty") + + # Remove trailing dot if present + if hostname.endswith('.'): + hostname = hostname[:-1] + + if len(hostname) > 253: + raise ValidationError("Hostname too long (max 253 characters)") + + try: + # Encode each label using IDNA + labels = hostname.split('.') + encoded_labels = [] + + for label in labels: + if not label: + raise ValidationError("Empty label in hostname") + + # Encode to punycode if needed + try: + encoded = label.encode('idna').decode('ascii') + except UnicodeError as e: + raise ValidationError(f"Invalid label '{label}': {e}") + + if len(encoded) > 63: + raise ValidationError( + f"Label '{label}' too long (max 63 characters)" + ) + + if not LABEL_PATTERN.match(encoded): + raise ValidationError(f"Invalid label format: '{label}'") + + encoded_labels.append(encoded) + + return '.'.join(encoded_labels) + + except ValidationError: + raise + except Exception as e: + raise ValidationError(f"Invalid hostname '{hostname}': {e}") + + +def encode_zone(zone): + """ + Encode zone name to ASCII using punycode (IDNA). + + Args: + zone: Zone name string, possibly with unicode characters. + + Returns: + ASCII-encoded zone name. + + Raises: + ValidationError: If zone is invalid. + """ + if not zone: + raise ValidationError("Zone cannot be empty") + + # Zone validation is same as hostname + return encode_hostname(zone) + + +def validate_hostname_in_zone(hostname, zone): + """ + Validate and encode hostname and zone, ensuring hostname is in zone. + + Args: + hostname: Hostname string. + zone: Zone string. + + Returns: + Tuple of (encoded_hostname, encoded_zone). + + Raises: + ValidationError: If validation fails. + """ + encoded_hostname = encode_hostname(hostname) + encoded_zone = encode_zone(zone) + + # Check hostname ends with zone + if not (encoded_hostname == encoded_zone or + encoded_hostname.endswith('.' + encoded_zone)): + raise ValidationError( + f"Hostname '{hostname}' is not in zone '{zone}'" + ) + + return encoded_hostname, encoded_zone + + +def get_relative_name(hostname, zone): + """ + Get the relative name (hostname without zone suffix). + + Args: + hostname: Encoded hostname. + zone: Encoded zone. + + Returns: + Relative name (e.g., 'mypc' from 'mypc.dyn.example.com'). + """ + if hostname == zone: + return '@' + + suffix = '.' + zone + if hostname.endswith(suffix): + return hostname[:-len(suffix)] + + return hostname