pax_global_header00006660000000000000000000000064143455651550014527gustar00rootroot0000000000000052 comment=93e7347dc42795c01864178ce40847462025b2ab desec-io-certbot-dns-desec-918fd41/000077500000000000000000000000001434556515500170645ustar00rootroot00000000000000desec-io-certbot-dns-desec-918fd41/.flake8000066400000000000000000000001021434556515500202300ustar00rootroot00000000000000[flake8] ignore = # E501: line longer than 79 chars E501, desec-io-certbot-dns-desec-918fd41/.github/000077500000000000000000000000001434556515500204245ustar00rootroot00000000000000desec-io-certbot-dns-desec-918fd41/.github/FUNDING.yml000066400000000000000000000012011434556515500222330ustar00rootroot00000000000000# These are supported funding model platforms github: [desec-io] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: deSEC issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: ['https://desec.io/donate'] desec-io-certbot-dns-desec-918fd41/.github/workflows/000077500000000000000000000000001434556515500224615ustar00rootroot00000000000000desec-io-certbot-dns-desec-918fd41/.github/workflows/e2e.yml000066400000000000000000000065601434556515500236660ustar00rootroot00000000000000name: Obtain Certificate on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest environment: desec-test-account strategy: # You can use PyPy versions in python-version. # For example, pypy2 and pypy3 matrix: python-version: [ '3.7', '3.8', '3.9', '3.10', '3.11', ] certbot-version: [ # TODO at the time of writing, versions earlier than 1.14, including '0.40.0', the latest version for Ubuntu # 20.04, are broken because ImportError: cannot import name 'IO' from 'acme.magic_typing' # (venv/lib/python3.8/site-packages/acme/magic_typing.py) '1.14.0', '1.32.0', '2.0.0', ] steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install run: | sudo apt-get install -y dnsutils pip3 install . if [[ $CERTBOT_VERSION != "latest" ]] then pip3 install --upgrade certbot~=$CERTBOT_VERSION pip3 install --upgrade acme~=$CERTBOT_VERSION fi env: CERTBOT_VERSION: ${{ matrix.certbot-version }} - name: Create domain shell: bash run: | PYTHON=$(echo $PYTHON | sed "s/\./-/g") CERTBOT=$(echo $CERTBOT | sed "s/\./-/g") curl -X POST https://desec.io/api/v1/domains/ \ --header "Authorization: Token $TOKEN" \ --header "Content-Type: application/json" --data @- <<< \ "{\"name\": \"certbot-$CERTBOT-python-$PYTHON-$DOMAIN\"}" sleep 80 # wait for deSEC to propagate changes env: DOMAIN: ${{secrets.DESEC_DOMAIN}} CERTBOT: ${{matrix.certbot-version}} PYTHON: ${{matrix.python-version}} TOKEN: ${{secrets.DESEC_TOKEN}} - name: Setup Credentials run: 'echo "dns_desec_token = $TOKEN" > desec-secret.ini' shell: bash env: TOKEN: ${{secrets.DESEC_TOKEN}} - name: Get Cert run: | PYTHON=$(echo $PYTHON | sed "s/\./-/g") CERTBOT=$(echo $CERTBOT | sed "s/\./-/g") certbot certonly \ --config-dir tmp/certbot/config \ --logs-dir tmp/certbot/logs \ --work-dir tmp/certbot/work \ --authenticator dns-desec \ --email $EMAIL \ --dns-desec-credentials desec-secret.ini \ --server https://acme-v02.api.letsencrypt.org/directory \ --agree-tos \ --dry-run \ -d "certbot-$CERTBOT-python-$PYTHON-$DOMAIN" \ -d "*.certbot-$CERTBOT-python-$PYTHON-$DOMAIN" shell: bash env: DOMAIN: ${{secrets.DESEC_DOMAIN}} EMAIL: ${{secrets.DESEC_EMAIL}} CERTBOT: ${{matrix.certbot-version}} PYTHON: ${{matrix.python-version}} - name: Query TXT record and show log if: ${{ failure() }} run: | PYTHON=$(echo $PYTHON | sed "s/\./-/g") CERTBOT=$(echo $CERTBOT | sed "s/\./-/g") dig @ns1.desec.io TXT _acme-challenge.certbot-$CERTBOT-python-$PYTHON-$DOMAIN dig @ns2.desec.org TXT _acme-challenge.certbot-$CERTBOT-python-$PYTHON-$DOMAIN cat tmp/certbot/logs/letsencrypt.log env: DOMAIN: ${{secrets.DESEC_DOMAIN}} CERTBOT: ${{matrix.certbot-version}} PYTHON: ${{matrix.python-version}} desec-io-certbot-dns-desec-918fd41/.github/workflows/main.yml000066400000000000000000000022761434556515500241370ustar00rootroot00000000000000name: Tests on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest strategy: # You can use PyPy versions in python-version. # For example, pypy2 and pypy3 matrix: python-version: [ '3.7', '3.8', '3.9', '3.10', '3.11', ] certbot-version: [ # '1.14.0', # tests use features not available in this version '1.32.0', '2.0.0', ] steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install Requirements run: | pip3 install -r requirements.txt pip3 install . if [[ $CERTBOT_VERSION != "latest" ]] then pip3 install --upgrade certbot~=$CERTBOT_VERSION pip3 install --upgrade acme~=$CERTBOT_VERSION fi pip3 freeze env: CERTBOT_VERSION: ${{ matrix.certbot-version }} - name: flake8 Linter run: python3 -m flake8 certbot_dns_desec - name: Unit tests run: python3 -m unittest certbot_dns_desec/dns_desec_test.py desec-io-certbot-dns-desec-918fd41/.gitignore000066400000000000000000000040271434556515500210570ustar00rootroot00000000000000# 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/ 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 *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # 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/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ .idea desec-secret.ini tmp/ venv/ desec-io-certbot-dns-desec-918fd41/LICENSE.txt000066400000000000000000000250421434556515500207120ustar00rootroot00000000000000 Copyright 2015 Electronic Frontier Foundation and others Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS desec-io-certbot-dns-desec-918fd41/README.md000066400000000000000000000115261434556515500203500ustar00rootroot00000000000000# certbot-dns-desec: Get Let's Encrypt Certificates for Domains Hosted at deSEC ![main branch CI test status](https://github.com/desec-io/certbot-dns-desec/workflows/Tests/badge.svg?branch=main) [![pypi badge](https://img.shields.io/pypi/v/certbot-dns-desec.svg)](https://pypi.org/project/certbot-dns-desec/) Certbot plugin to obtain TLS certificates from Let's Encrypt for domains hosted with deSEC.io, using the DNS challenge challenge mechanism. ## Installation To get certificates from Let's Encrypt, install certbot and this plugin. There are many ways to install certbot, this guide uses Python's `pip`: ```shell python3 -m pip install certbot certbot-dns-desec ``` ## Prerequisites To get a Let's Encrypt certificate for your domain `$DOMAIN`, you need a deSEC API token `$TOKEN` with sufficient permission for performing the required DNS changes on your domain. Also make sure that your domain name has been delegated to deSEC (in other words: make sure that the parent registry has the right NS records). If you don't have a token yet, an easy way to obtain one is by logging into your account at [deSEC.io](https://desec.io). Navigate to "Token Management" and create a new one. It's good practice to restrict the token permissions as much as possible, e.g. by setting the maximum unused period to four months. This way, the token will expire if it is not continuously used to renew your certificate. Tokens can also be created [using the deSEC API](https://desec.readthedocs.io/en/latest/auth/tokens.html#creating-a-token). ## Request Certificate To issue and renew certificates using `certbot-dns-desec`, an access token to your deSEC account is required. To store such a token in a secure location, use, e.g.: ```shell DOMAIN=example.com TOKEN=your-desec-access-token sudo mkdir -p /etc/letsencrypt/secrets/ sudo chmod 700 /etc/letsencrypt/secrets/ echo "dns_desec_token = $TOKEN" | sudo tee /etc/letsencrypt/secrets/$DOMAIN.ini sudo chmod 600 /etc/letsencrypt/secrets/$DOMAIN.ini ``` Adjust `$DOMAIN` and `$TOKEN` according to your domain and deSEC access token, respectively. The file location is just a suggestion and can be changed. With the credentials stored, you can request a wildcard certificate for your domain by using, e.g., ```shell certbot certonly \ --authenticator dns-desec \ --dns-desec-credentials /etc/letsencrypt/secrets/$DOMAIN.ini \ -d "$DOMAIN" \ -d "*.$DOMAIN" ``` In this command, `--authenticator dns-desec` activates the `certbot-dns-desec` plugin; the `--dns-desec-credentials` argument provides the deSEC access token location to the plugin. These flags can be combined with more sophisticated usages of certbot, e.g. to automatically reload servers after the renewal process. Such functionality is independent of this plugin; for details, see the certbot documentation. ## CLI Interface This plugin is activated by passing the ``--authenticator dns-desec`` argument to certbot. It accepts the following command line arguments: 1. ``--dns-desec-credentials `` Specifies the file holding the deSEC API credentials (required, see below). 1. ``--dns-desec-propagation-seconds`` Waiting time for DNS to propagate before asking the ACME server to verify the DNS record. ## Credentials File Format An example ``credentials.ini`` file: dns_desec_token = token Additionally, the URL of the deSEC API can be specified using the `dns_desec_endpoint` configuration option. `https://desec.io/api/v1/` is the default. ## Development and Testing To test certbot-dns-desec, create a virtual environment at `venv/` for this repository and activate it. Register a domain `$DOMAIN` with desec.io, and obtain a DNS management token `$TOKEN`. Then run ```shell python3 -m pip install . TOKEN=token-you-obtained-from-desec-io DOMAIN=domain-you-registered-at-desec-io EMAIL=youremail@example.com echo "dns_desec_token = $TOKEN" > desec-secret.ini chmod 600 desec-secret.ini ./venv/bin/certbot \ --config-dir tmp/certbot/config \ --logs-dir tmp/certbot/logs \ --work-dir tmp/certbot/work \ --test-cert \ -d $DOMAIN -d "*.$DOMAIN" \ --authenticator dns-desec \ --dns-desec-credentials desec-secret.ini \ --non-interactive --agree-tos \ --email $EMAIL \ certonly ``` ## Maintenance: Prepare New Release 1. Make sure tests are okay (see GitHub actions) 1. Commit all changes 1. Clean up `dist/` folder 1. Set up new release version: `RELEASE=x.y.z` 1. Update version to `x.y.z` in `setup.py` 1. Commit with message "Release Version vx.y.z": `git commit -p -m "Release Version v$RELEASE"` 1. Tag commit using `git tag -as v$RELEASE -m "Release Version v$RELEASE"` 1. Push 1. branch: `git push` 1. tag: `git push origin v$RELEASE` 1. Set environment variables `GITHUB_TOKEN` to a GitHub token, `TWINE_USERNAME` and `TWINE_PASSWORD` to PyPi credentials. 1. Publish using `python3 -m publish desec-io certbot-dns-desec` desec-io-certbot-dns-desec-918fd41/certbot_dns_desec/000077500000000000000000000000001434556515500225355ustar00rootroot00000000000000desec-io-certbot-dns-desec-918fd41/certbot_dns_desec/__init__.py000066400000000000000000000060741434556515500246550ustar00rootroot00000000000000""" The `~certbot_dns_desec.dns_desec` plugin automates the process of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently removing, TXT records using the deSEC REST API. Named Arguments --------------- ======================================== ===================================== ``--dns-desec-credentials`` deSEC Remote API credentials_ INI file. (Required) ``--dns-desec-propagation-seconds`` The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (Default: 120) # TODO default, needed? ======================================== ===================================== Credentials ----------- Use of this plugin requires a configuration file containing a deSEC DNS API access token obtained from the deSEC website. .. code-block:: ini :name: credentials.ini :caption: Example credentials file: # deSEC API token used by Certbot dns_desec_token = asdf dns_desec_endpoint = https://localhost:8080 The path to this file can be provided interactively or using the ``--dns-desec-credentials`` command-line argument. Certbot records the path to this file for use during renewal, but does not store the file's contents. .. caution:: You should protect these API credentials as you would a password. Users who can read this file can use these credentials to issue API calls on your behalf. Users who can cause Certbot to run using these credentials can complete a ``dns-01`` challenge to acquire new certificates or revoke existing certificates for associated domains, even if those domains aren't being managed by this server. Certbot will emit a warning if it detects that the credentials file can be accessed by other users on your system. The warning reads "Unsafe permissions on credentials configuration file", followed by the path to the credentials file. This warning will be emitted each time Certbot uses the credentials file, including for renewal, and cannot be silenced except by addressing the issue (e.g., by using a command like ``chmod 600`` to restrict access to the file). Examples -------- .. code-block:: bash :caption: To acquire a certificate for ``example.com`` certbot certonly \\ --dns-desec \\ --dns-desec-credentials ~/.secrets/certbot/desec.ini \\ -d example.com .. code-block:: bash :caption: To acquire a single certificate for both ``example.com`` and ``www.example.com`` certbot certonly \\ --dns-desec \\ --dns-desec-credentials ~/.secrets/certbot/desec.ini \\ -d example.com \\ -d www.example.com .. code-block:: bash :caption: To acquire a certificate for ``example.com``, waiting 240 seconds for DNS propagation certbot certonly \\ --dns-desec \\ --dns-desec-credentials ~/.secrets/certbot/desec.ini \\ --dns-desec-propagation-seconds 240 \\ # TODO -d example.com """ desec-io-certbot-dns-desec-918fd41/certbot_dns_desec/dns_desec.py000066400000000000000000000163271434556515500250470ustar00rootroot00000000000000"""DNS Authenticator for deSEC.""" import json import logging import time import requests from certbot import interfaces try: # needed for compatibility with older certbots, see #13 import zope.interface zope_interface_implementer = zope.interface.implementer zope_interface_provider = zope.interface.provider i_authenticator = interfaces.IAuthenticator i_plugin_factory = interfaces.IPluginFactory except ImportError: def get_noop_dec(*args): def noop_dec(obj): return obj return noop_dec zope_interface_implementer = zope_interface_provider = get_noop_dec i_authenticator = i_plugin_factory = None from certbot import errors from certbot.plugins import dns_common logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) @zope_interface_implementer(i_authenticator) # needed for compatibility with older certbots, see #13 @zope_interface_provider(i_plugin_factory) # needed for compatibility with older certbots, see #13 class Authenticator(dns_common.DNSAuthenticator): """DNS Authenticator for deSEC This Authenticator uses the deSEC REST API to fulfill a dns-01 challenge. """ description = "Obtain certificates using a DNS TXT record (if you are using deSEC.io for DNS)." DEFAULT_ENDPOINT = "https://desec.io/api/v1" def __init__(self, *args, **kwargs): super(Authenticator, self).__init__(*args, **kwargs) self.credentials = None @classmethod def add_parser_arguments(cls, add): # pylint: disable=arguments-differ super(Authenticator, cls).add_parser_arguments( add, default_propagation_seconds=80 # TODO decrease after deSEC fixed their NOTIFY problem ) add("credentials", help="deSEC credentials INI file.") def more_info(self): # pylint: disable=missing-docstring,no-self-use return ( "This plugin configures a DNS TXT record to respond to a dns-01 challenge using " "the deSEC Remote REST API." ) def _setup_credentials(self): self.credentials = self._configure_credentials( key="credentials", label="deSEC credentials INI file", required_variables={ "token": "Access token for deSEC API.", }, ) def _desec_work(self, domain, validation_name, validation, set_operator): client = self._get_desec_client() zone = client.get_authoritative_zone(validation_name) subname = validation_name.rsplit(zone['name'], 1)[0].rstrip('.') records = client.get_txt_rrset(zone, subname) logger.debug(f"Current TXT records: {records}") records = set_operator(records, {f'"{validation}"'}) logger.debug(f"Setting TXT records: {records}") client.set_txt_rrset(zone, subname, records) def _perform(self, domain, validation_name, validation): logger.debug(f"Authenticator._perform: {domain}, {validation_name}, {validation}") self._desec_work(domain, validation_name, validation, set.union) def _cleanup(self, domain, validation_name, validation): logger.debug(f"Authenticator._cleanup: {domain}, {validation_name}, {validation}") self._desec_work(domain, validation_name, validation, set.difference) def _get_desec_client(self): return _DesecConfigClient( self.credentials.conf("endpoint") or self.DEFAULT_ENDPOINT, self.credentials.conf("token"), ) class _DesecConfigClient(object): """ Encapsulates all communication with the deSEC REST API. """ def __init__(self, endpoint, token): logger.debug("creating _DesecConfigClient") self.endpoint = endpoint.rstrip('/') self.token = token self.session = requests.Session() self.session.headers["Authorization"] = f"Token {token}" self.session.headers["Content-Type"] = "application/json" @staticmethod def desec_request(method, **kwargs): for _ in range(3): response: requests.Response = method(**kwargs) if response.status_code == 429 and 'Retry-After' in response.headers: try: cooldown = int(response.headers['Retry-After']) except ValueError: return response logger.debug(f"deSEC API limit reached. Retrying request after {cooldown}s.") time.sleep(cooldown) else: return response return response def desec_get(self, **kwargs): return self.desec_request(self.session.get, **kwargs) def desec_put(self, **kwargs): return self.desec_request(self.session.put, **kwargs) def get_authoritative_zone(self, qname): response = self.desec_get(url=f"{self.endpoint}/domains/?owns_qname={qname}") self._check_response_status(response) data = self._response_json(response) try: return data[0] except IndexError: raise errors.PluginError(f"Could not find suitable domain in your account (did you create it?): {qname}") def get_txt_rrset(self, zone, subname): domain = zone['name'] response = self.desec_get( url=f"{self.endpoint}/domains/{domain}/rrsets/{subname}/TXT/", ) if response.status_code == 404: return set() self._check_response_status(response, domain=domain) return set(self._response_json(response).get('records', set())) def set_txt_rrset(self, zone, subname, records: set): domain = zone['name'] response = self.desec_put( url=f"{self.endpoint}/domains/{domain}/rrsets/", data=json.dumps([ {"subname": subname, "type": "TXT", "ttl": zone['minimum_ttl'], "records": list(records)}, ]), ) return self._check_response_status(response, domain=domain) def _check_response_status(self, response, **kwargs): if 200 <= response.status_code <= 299: return elif response.status_code in [401, 403]: raise errors.PluginError(f"Could not authenticate against deSEC API: {response.content}") elif response.status_code == 404: raise errors.PluginError(f"Not found ({kwargs}): {response.content}") elif response.status_code == 429: raise errors.PluginError(f"deSEC throttled your request even after we waited the prescribed cool-down " f"time. Did you use the API in parallel? {response.content}") elif response.status_code >= 500: raise errors.PluginError(f"deSEC API server error (status {response.status_code}): {response.content}") else: raise errors.PluginError(f"Unknown error when talking to deSEC (status {response.status_code}: " f"Request was on '{response.request.url}' with payload {response.request.body}. " f"Response was '{response.content}'.") def _response_json(self, response): try: return response.json() except json.JSONDecodeError: raise errors.PluginError(f"deSEC API sent non-JSON response (status {response.status_code}): " f"{response.content}") desec-io-certbot-dns-desec-918fd41/certbot_dns_desec/dns_desec_test.py000066400000000000000000000201441434556515500260760ustar00rootroot00000000000000"""Tests for certbot_dns_desec.dns_desec.""" import json import unittest from unittest.mock import patch import mock import requests_mock from certbot import errors from certbot.compat import os from certbot.plugins import dns_test_common from certbot.plugins.dns_test_common import DOMAIN from certbot.tests import util as test_util FAKE_TOKEN = "faketoken" FAKE_ENDPOINT = "mock://endpoint" class AuthenticatorTest( test_util.TempDirTestCase, dns_test_common.BaseAuthenticatorTest ): TXT = {'"preexisting" "TXT record 1/2"', '"preexisting TXT record 2/2"'} def setUp(self): super(AuthenticatorTest, self).setUp() from certbot_dns_desec.dns_desec import Authenticator path = os.path.join(self.tempdir, "file.ini") dns_test_common.write( { "desec_token": FAKE_TOKEN, "desec_endpoint": FAKE_ENDPOINT, }, path, ) super(AuthenticatorTest, self).setUp() self.config = mock.MagicMock( desec_credentials=path, desec_propagation_seconds=0 ) # don't wait during tests self.auth = Authenticator(self.config, "desec") self.mock_zone = {'name': DOMAIN, 'minimum_ttl': 42} self.mock_client = mock.MagicMock() self.mock_client.get_authoritative_zone.return_value = self.mock_zone self.mock_client.get_txt_rrset.return_value = self.TXT # _get_desec_client | pylint: disable=protected-access self.auth._get_desec_client = mock.MagicMock(return_value=self.mock_client) @test_util.patch_display_util() def test_perform(self, unused_mock_get_utility): self.auth.perform([self.achall]) validation = self.achall.validation(self.achall.account_key) self.mock_client.get_authoritative_zone.assert_called_once_with(f'_acme-challenge.{DOMAIN}') self.mock_client.get_txt_rrset.assert_called_once_with(self.mock_zone, "_acme-challenge") self.mock_client.set_txt_rrset.assert_called_once_with(self.mock_zone, "_acme-challenge", self.TXT | {f'"{validation}"'}) def test_cleanup(self): # _attempt_cleanup | pylint: disable=protected-access self.auth._attempt_cleanup = True self.auth.cleanup([self.achall]) self.mock_client.get_authoritative_zone.assert_called_once_with(f'_acme-challenge.{DOMAIN}') self.mock_client.get_txt_rrset.assert_called_once_with(self.mock_zone, "_acme-challenge") self.mock_client.set_txt_rrset.assert_called_once_with(self.mock_zone, "_acme-challenge", self.TXT) class DesecConfigClientTest(unittest.TestCase): record_name = "foo" record_content = ["bar"] record_ttl = 42 def setUp(self): from certbot_dns_desec.dns_desec import _DesecConfigClient self.adapter = requests_mock.Adapter() self.client = _DesecConfigClient(FAKE_ENDPOINT, FAKE_TOKEN) self.client.session.mount("mock", self.adapter) def _register_response(self, url, response=None, requires_token=True, status=200): def additional_matcher(request): okay = True okay &= request.headers["Content-Type"] == "application/json" if requires_token: okay &= request.headers["Authorization"] == f"Token {FAKE_TOKEN}" return okay self.adapter.register_uri( method=requests_mock.ANY, url=url, text=json.dumps(response), additional_matcher=additional_matcher, status_code=status, ) def test_get_authoritative_zone(self): self._register_response( url=f"{FAKE_ENDPOINT}/domains/?owns_qname=_acme-challenge.{DOMAIN}", response=[ { "created": "2021-06-14T14:30:35.463899Z", "minimum_ttl": 3600, "name": 'name.to.be.extracted', "published": "2021-06-14T14:30:35.772212Z", "touched": "2021-06-14T14:30:35.772212Z" } ] ) zone = self.client.get_authoritative_zone(f"_acme-challenge.{DOMAIN}") self.assertEqual(zone['name'], 'name.to.be.extracted') self.assertEqual(zone['minimum_ttl'], 3600) def test_set_txt_rrset(self): self._register_response( url=f"{FAKE_ENDPOINT}/domains/{DOMAIN}/rrsets/", response=[ { "created": "2021-05-13T09:38:41.576975Z", "domain": DOMAIN, "subname": "_acme_challenge", "name": self.record_name, "records": [self.record_content], "ttl": self.record_ttl, "type": "TXT", "touched": "2021-05-13T09:38:41.585257Z" } ] ) self.client.set_txt_rrset( {'name': DOMAIN, 'minimum_ttl': self.record_ttl}, self.record_name, self.record_content ) def test_set_txt_rrset_fail_to_find_domain(self): self._register_response( url=f"{FAKE_ENDPOINT}/domains/{DOMAIN}/rrsets/", response={"detail": "Not found."}, status=404, ) with self.assertRaises(errors.PluginError): self.client.set_txt_rrset( {'name': DOMAIN, 'minimum_ttl': self.record_ttl}, self.record_name, self.record_content ) def test_set_txt_rrset_fail_to_authenticate(self): self._register_response( url=f"{FAKE_ENDPOINT}/domains/{DOMAIN}/rrsets/", response={"detail": "Invalid token."}, status=403, ) with self.assertRaises(errors.PluginError): self.client.set_txt_rrset( {'name': DOMAIN, 'minimum_ttl': self.record_ttl}, self.record_name, self.record_content ) @patch('time.sleep', return_value=None) def test_set_txt_rrset_throttling_retry(self, patched_time_sleep): self.adapter.register_uri( 'PUT', f"{FAKE_ENDPOINT}/domains/{DOMAIN}/rrsets/", [ dict(status_code=429, headers={'Retry-After': '2'}), dict(status_code=429, headers={'Retry-After': '31'}), dict(status_code=200), ] ) self.client.set_txt_rrset( {'name': DOMAIN, 'minimum_ttl': self.record_ttl}, self.record_name, self.record_content ) self.assertEqual(patched_time_sleep.call_args_list, [mock.call(2), mock.call(31)]) @patch('time.sleep', return_value=None) def test_set_txt_rrset_throttling_retry_fail(self, patched_time_sleep): self.adapter.register_uri( 'PUT', f"{FAKE_ENDPOINT}/domains/{DOMAIN}/rrsets/", [ dict(status_code=429, headers={'Retry-After': '2'}), ] * 4 ) with self.assertRaises(errors.PluginError): self.client.set_txt_rrset( {'name': DOMAIN, 'minimum_ttl': self.record_ttl}, self.record_name, self.record_content ) self.assertEqual(patched_time_sleep.call_args_list, [mock.call(2)] * 3) def test_set_txt_rrset_throttling_no_retry(self): self.adapter.register_uri( 'PUT', f"{FAKE_ENDPOINT}/domains/{DOMAIN}/rrsets/", [ dict(status_code=429), # no Retry-After header ] ) with self.assertRaises(errors.PluginError): self.client.set_txt_rrset( {'name': DOMAIN, 'minimum_ttl': self.record_ttl}, self.record_name, self.record_content ) self.adapter.register_uri( 'PUT', f"{FAKE_ENDPOINT}/domains/{DOMAIN}/rrsets/", [ dict(status_code=429, headers={'Retry-After': 'asdf'}), # Retry-After header not int ] ) with self.assertRaises(errors.PluginError): self.client.set_txt_rrset( {'name': DOMAIN, 'minimum_ttl': self.record_ttl}, self.record_name, self.record_content ) if __name__ == "__main__": unittest.main() # pragma: no cover desec-io-certbot-dns-desec-918fd41/requirements.txt000066400000000000000000000000321434556515500223430ustar00rootroot00000000000000flake8 mock requests-mock desec-io-certbot-dns-desec-918fd41/setup.cfg000066400000000000000000000000341434556515500207020ustar00rootroot00000000000000[bdist_wheel] universal = 1 desec-io-certbot-dns-desec-918fd41/setup.py000066400000000000000000000020101434556515500205670ustar00rootroot00000000000000from setuptools import setup from setuptools import find_packages version = "1.2.1" install_requires = [ "certbot>=1.14.0", "setuptools", "requests", ] # read the contents of your README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, "README.md")) as f: long_description = f.read() setup( name="certbot-dns-desec", version=version, description="deSEC DNS Authenticator plugin for Certbot", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/desec-io/certbot-dns-desec", author="Nils Wisiol", author_email="nils@desec.io", license="Apache License 2.0", python_requires=">=3.7", packages=find_packages(), include_package_data=True, install_requires=install_requires, entry_points={ "certbot.plugins": [ "dns-desec = certbot_dns_desec.dns_desec:Authenticator" ] }, test_suite="certbot_dns_desec", )