certbot-0.27.0/0002755000175000017500000000000013344054435013441 5ustar ericaerica00000000000000certbot-0.27.0/CONTRIBUTING.md0000644000175000017500000000257213344054434015675 0ustar ericaerica00000000000000 # Certbot Contributing Guide Hi! Welcome to the Certbot project. We look forward to collaborating with you. If you're reporting a bug in Certbot, please make sure to include: - The version of Certbot you're running. - The operating system you're running it on. - The commands you ran. - What you expected to happen, and - What actually happened. If you're a developer, we have some helpful information in our [Developer's Guide](https://certbot.eff.org/docs/contributing.html) to get you started. In particular, we recommend you read these sections - [Finding issues to work on](https://certbot.eff.org/docs/contributing.html#find-issues-to-work-on) - [Coding style](https://certbot.eff.org/docs/contributing.html#coding-style) - [Submitting a pull request](https://certbot.eff.org/docs/contributing.html#submitting-a-pull-request) certbot-0.27.0/setup.cfg0000644000175000017500000000014213344054435015255 0ustar ericaerica00000000000000[bdist_wheel] universal = 1 [easy_install] zip_ok = false [egg_info] tag_build = tag_date = 0 certbot-0.27.0/LICENSE.txt0000644000175000017500000002630013344054434015262 0ustar ericaerica00000000000000Certbot ACME Client Copyright (c) Electronic Frontier Foundation and others Licensed Apache Version 2.0 The nginx plugin incorporates code from nginxparser Copyright (c) 2014 Fatih Erikli Licensed MIT Text of Apache 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. Text of MIT License =================== Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. certbot-0.27.0/certbot.egg-info/0002755000175000017500000000000013344054435016575 5ustar ericaerica00000000000000certbot-0.27.0/certbot.egg-info/top_level.txt0000644000175000017500000000001013344054435021314 0ustar ericaerica00000000000000certbot certbot-0.27.0/certbot.egg-info/PKG-INFO0000644000175000017500000002337313344054435017700 0ustar ericaerica00000000000000Metadata-Version: 2.1 Name: certbot Version: 0.27.0 Summary: ACME client Home-page: https://github.com/letsencrypt/letsencrypt Author: Certbot Project Author-email: client-dev@letsencrypt.org License: Apache License 2.0 Description: .. This file contains a series of comments that are used to include sections of this README in other files. Do not modify these comments unless you know what you are doing. tag:intro-begin Certbot is part of EFF’s effort to encrypt the entire Internet. Secure communication over the Web relies on HTTPS, which requires the use of a digital certificate that lets browsers verify the identity of web servers (e.g., is that really google.com?). Web servers obtain their certificates from trusted third parties called certificate authorities (CAs). Certbot is an easy-to-use client that fetches a certificate from Let’s Encrypt—an open certificate authority launched by the EFF, Mozilla, and others—and deploys it to a web server. Anyone who has gone through the trouble of setting up a secure website knows what a hassle getting and maintaining a certificate is. Certbot and Let’s Encrypt can automate away the pain and let you turn on and manage HTTPS with simple commands. Using Certbot and Let's Encrypt is free, so there’s no need to arrange payment. How you use Certbot depends on the configuration of your web server. The best way to get started is to use our `interactive guide `_. It generates instructions based on your configuration settings. In most cases, you’ll need `root or administrator access `_ to your web server to run Certbot. If you’re using a hosted service and don’t have direct access to your web server, you might not be able to use Certbot. Check with your hosting provider for documentation about uploading certificates or using certificates issued by Let’s Encrypt. Certbot is a fully-featured, extensible client for the Let's Encrypt CA (or any other CA that speaks the `ACME `_ protocol) that can automate the tasks of obtaining certificates and configuring webservers to use them. This client runs on Unix-based operating systems. To see the changes made to Certbot between versions please refer to our `changelog `_. Until May 2016, Certbot was named simply ``letsencrypt`` or ``letsencrypt-auto``, depending on install method. Instructions on the Internet, and some pieces of the software, may still refer to this older name. Contributing ------------ If you'd like to contribute to this project please read `Developer Guide `_. .. _installation: Installation ------------ The easiest way to install Certbot is by visiting `certbot.eff.org`_, where you can find the correct installation instructions for many web server and OS combinations. For more information, see `Get Certbot `_. .. _certbot.eff.org: https://certbot.eff.org/ How to run the client --------------------- In many cases, you can just run ``certbot-auto`` or ``certbot``, and the client will guide you through the process of obtaining and installing certs interactively. For full command line help, you can type:: ./certbot-auto --help all You can also tell it exactly what you want it to do from the command line. For instance, if you want to obtain a cert for ``example.com``, ``www.example.com``, and ``other.example.net``, using the Apache plugin to both obtain and install the certs, you could do this:: ./certbot-auto --apache -d example.com -d www.example.com -d other.example.net (The first time you run the command, it will make an account, and ask for an email and agreement to the Let's Encrypt Subscriber Agreement; you can automate those with ``--email`` and ``--agree-tos``) If you want to use a webserver that doesn't have full plugin support yet, you can still use "standalone" or "webroot" plugins to obtain a certificate:: ./certbot-auto certonly --standalone --email admin@example.com -d example.com -d www.example.com -d other.example.net Understanding the client in more depth -------------------------------------- To understand what the client is doing in detail, it's important to understand the way it uses plugins. Please see the `explanation of plugins `_ in the User Guide. Links ===== .. Do not modify this comment unless you know what you're doing. tag:links-begin Documentation: https://certbot.eff.org/docs Software project: https://github.com/certbot/certbot Notes for developers: https://certbot.eff.org/docs/contributing.html Main Website: https://certbot.eff.org Let's Encrypt Website: https://letsencrypt.org IRC Channel: #letsencrypt on `Freenode`_ Community: https://community.letsencrypt.org ACME spec: http://ietf-wg-acme.github.io/acme/ ACME working area in github: https://github.com/ietf-wg-acme/acme |build-status| |coverage| |docs| |container| .. _Freenode: https://webchat.freenode.net?channels=%23letsencrypt .. |build-status| image:: https://travis-ci.org/certbot/certbot.svg?branch=master :target: https://travis-ci.org/certbot/certbot :alt: Travis CI status .. |coverage| image:: https://codecov.io/gh/certbot/certbot/branch/master/graph/badge.svg :target: https://codecov.io/gh/certbot/certbot :alt: Coverage status .. |docs| image:: https://readthedocs.org/projects/letsencrypt/badge/ :target: https://readthedocs.org/projects/letsencrypt/ :alt: Documentation status .. |container| image:: https://quay.io/repository/letsencrypt/letsencrypt/status :target: https://quay.io/repository/letsencrypt/letsencrypt :alt: Docker Repository on Quay.io .. Do not modify this comment unless you know what you're doing. tag:links-end System Requirements =================== See https://certbot.eff.org/docs/install.html#system-requirements. .. Do not modify this comment unless you know what you're doing. tag:intro-end .. Do not modify this comment unless you know what you're doing. tag:features-begin Current Features ===================== * Supports multiple web servers: - apache/2.x - nginx/0.8.48+ - webroot (adds files to webroot directories in order to prove control of domains and obtain certs) - standalone (runs its own simple webserver to prove you control a domain) - other server software via `third party plugins `_ * The private key is generated locally on your system. * Can talk to the Let's Encrypt CA or optionally to other ACME compliant services. * Can get domain-validated (DV) certificates. * Can revoke certificates. * Adjustable RSA key bit-length (2048 (default), 4096, ...). * Can optionally install a http -> https redirect, so your site effectively runs https only (Apache only) * Fully automated. * Configuration changes are logged and can be reverted. * Supports an interactive text UI, or can be driven entirely from the command line. * Free and Open Source Software, made with Python. .. Do not modify this comment unless you know what you're doing. tag:features-end For extensive documentation on using and contributing to Certbot, go to https://certbot.eff.org/docs. If you would like to contribute to the project or run the latest code from git, you should read our `developer guide `_. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Environment :: Console :: Curses Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Security Classifier: Topic :: System :: Installation/Setup Classifier: Topic :: System :: Networking Classifier: Topic :: System :: Systems Administration Classifier: Topic :: Utilities Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.* Provides-Extra: dev3 Provides-Extra: docs Provides-Extra: dev certbot-0.27.0/certbot.egg-info/requires.txt0000644000175000017500000000051413344054435021173 0ustar ericaerica00000000000000acme>=0.26.0 ConfigArgParse>=0.9.3 configobj cryptography>=1.2 josepy mock parsedatetime>=1.3 pyrfc3339 pytz setuptools zope.component zope.interface [dev] astroid==1.3.5 coverage ipdb pytest pytest-cov pytest-xdist pylint==1.4.2 tox twine wheel [dev3] mypy typing [docs] repoze.sphinx.autointerface Sphinx>=1.6 sphinx_rtd_theme certbot-0.27.0/certbot.egg-info/dependency_links.txt0000644000175000017500000000000113344054435022641 0ustar ericaerica00000000000000 certbot-0.27.0/certbot.egg-info/entry_points.txt0000644000175000017500000000037413344054435022075 0ustar ericaerica00000000000000[certbot.plugins] manual = certbot.plugins.manual:Authenticator null = certbot.plugins.null:Installer standalone = certbot.plugins.standalone:Authenticator webroot = certbot.plugins.webroot:Authenticator [console_scripts] certbot = certbot.main:main certbot-0.27.0/certbot.egg-info/SOURCES.txt0000644000175000017500000001232013344054435020455 0ustar ericaerica00000000000000CHANGES.rst CONTRIBUTING.md LICENSE.txt MANIFEST.in README.rst linter_plugin.py setup.cfg setup.py certbot/__init__.py certbot/account.py certbot/achallenges.py certbot/auth_handler.py certbot/cert_manager.py certbot/cli.py certbot/client.py certbot/configuration.py certbot/constants.py certbot/crypto_util.py certbot/eff.py certbot/error_handler.py certbot/errors.py certbot/hooks.py certbot/interfaces.py certbot/lock.py certbot/log.py certbot/main.py certbot/notify.py certbot/ocsp.py certbot/renewal.py certbot/reporter.py certbot/reverter.py certbot/ssl-dhparams.pem certbot/storage.py certbot/updater.py certbot/util.py certbot.egg-info/PKG-INFO certbot.egg-info/SOURCES.txt certbot.egg-info/dependency_links.txt certbot.egg-info/entry_points.txt certbot.egg-info/requires.txt certbot.egg-info/top_level.txt certbot/display/__init__.py certbot/display/completer.py certbot/display/dummy_readline.py certbot/display/enhancements.py certbot/display/ops.py certbot/display/util.py certbot/plugins/__init__.py certbot/plugins/common.py certbot/plugins/common_test.py certbot/plugins/disco.py certbot/plugins/disco_test.py certbot/plugins/dns_common.py certbot/plugins/dns_common_lexicon.py certbot/plugins/dns_common_lexicon_test.py certbot/plugins/dns_common_test.py certbot/plugins/dns_test_common.py certbot/plugins/dns_test_common_lexicon.py certbot/plugins/enhancements.py certbot/plugins/enhancements_test.py certbot/plugins/manual.py certbot/plugins/manual_test.py certbot/plugins/null.py certbot/plugins/null_test.py certbot/plugins/selection.py certbot/plugins/selection_test.py certbot/plugins/standalone.py certbot/plugins/standalone_test.py certbot/plugins/storage.py certbot/plugins/storage_test.py certbot/plugins/util.py certbot/plugins/util_test.py certbot/plugins/webroot.py certbot/plugins/webroot_test.py certbot/tests/__init__.py certbot/tests/account_test.py certbot/tests/acme_util.py certbot/tests/auth_handler_test.py certbot/tests/cert_manager_test.py certbot/tests/cli_test.py certbot/tests/client_test.py certbot/tests/configuration_test.py certbot/tests/crypto_util_test.py certbot/tests/eff_test.py certbot/tests/error_handler_test.py certbot/tests/errors_test.py certbot/tests/hook_test.py certbot/tests/lock_test.py certbot/tests/log_test.py certbot/tests/main_test.py certbot/tests/notify_test.py certbot/tests/ocsp_test.py certbot/tests/renewal_test.py certbot/tests/renewupdater_test.py certbot/tests/reporter_test.py certbot/tests/reverter_test.py certbot/tests/storage_test.py certbot/tests/util.py certbot/tests/util_test.py certbot/tests/display/__init__.py certbot/tests/display/completer_test.py certbot/tests/display/enhancements_test.py certbot/tests/display/ops_test.py certbot/tests/display/util_test.py certbot/tests/testdata/README certbot/tests/testdata/cert-5sans_512.pem certbot/tests/testdata/cert-nosans_nistp256.pem certbot/tests/testdata/cert-san_512.pem certbot/tests/testdata/cert_2048.pem certbot/tests/testdata/cert_512.pem certbot/tests/testdata/cert_512_bad.pem certbot/tests/testdata/cert_fullchain_2048.pem certbot/tests/testdata/cli.ini certbot/tests/testdata/csr-6sans_512.conf certbot/tests/testdata/csr-6sans_512.pem certbot/tests/testdata/csr-nonames_512.pem certbot/tests/testdata/csr-nosans_512.conf certbot/tests/testdata/csr-nosans_512.pem certbot/tests/testdata/csr-nosans_nistp256.pem certbot/tests/testdata/csr-san_512.pem certbot/tests/testdata/csr_512.der certbot/tests/testdata/csr_512.pem certbot/tests/testdata/nistp256_key.pem certbot/tests/testdata/os-release certbot/tests/testdata/rsa2048_key.pem certbot/tests/testdata/rsa256_key.pem certbot/tests/testdata/rsa512_key.pem certbot/tests/testdata/sample-renewal-ancient.conf certbot/tests/testdata/sample-renewal.conf certbot/tests/testdata/webrootconftest.ini certbot/tests/testdata/sample-archive/cert1.pem certbot/tests/testdata/sample-archive/chain1.pem certbot/tests/testdata/sample-archive/fullchain1.pem certbot/tests/testdata/sample-archive/privkey1.pem docs/.gitignore docs/Makefile docs/api.rst docs/challenges.rst docs/ciphers.rst docs/cli-help.txt docs/conf.py docs/contributing.rst docs/index.rst docs/install.rst docs/intro.rst docs/make.bat docs/packaging.rst docs/resources.rst docs/using.rst docs/what.rst docs/_static/.gitignore docs/_templates/footer.html docs/api/account.rst docs/api/achallenges.rst docs/api/auth_handler.rst docs/api/cert_manager.rst docs/api/cli.rst docs/api/client.rst docs/api/configuration.rst docs/api/constants.rst docs/api/crypto_util.rst docs/api/display.rst docs/api/eff.rst docs/api/error_handler.rst docs/api/errors.rst docs/api/hooks.rst docs/api/index.rst docs/api/interfaces.rst docs/api/lock.rst docs/api/log.rst docs/api/main.rst docs/api/notify.rst docs/api/ocsp.rst docs/api/renewal.rst docs/api/reporter.rst docs/api/reverter.rst docs/api/storage.rst docs/api/util.rst docs/api/plugins/common.rst docs/api/plugins/disco.rst docs/api/plugins/dns_common.rst docs/api/plugins/dns_common_lexicon.rst docs/api/plugins/manual.rst docs/api/plugins/selection.rst docs/api/plugins/standalone.rst docs/api/plugins/util.rst docs/api/plugins/webroot.rst docs/man/certbot.rst examples/.gitignore examples/cli.ini examples/dev-cli.ini examples/generate-csr.sh examples/openssl.cnf examples/plugins/certbot_example_plugins.py examples/plugins/setup.pycertbot-0.27.0/README.rst0000644000175000017500000001632313344054434015132 0ustar ericaerica00000000000000.. This file contains a series of comments that are used to include sections of this README in other files. Do not modify these comments unless you know what you are doing. tag:intro-begin Certbot is part of EFF’s effort to encrypt the entire Internet. Secure communication over the Web relies on HTTPS, which requires the use of a digital certificate that lets browsers verify the identity of web servers (e.g., is that really google.com?). Web servers obtain their certificates from trusted third parties called certificate authorities (CAs). Certbot is an easy-to-use client that fetches a certificate from Let’s Encrypt—an open certificate authority launched by the EFF, Mozilla, and others—and deploys it to a web server. Anyone who has gone through the trouble of setting up a secure website knows what a hassle getting and maintaining a certificate is. Certbot and Let’s Encrypt can automate away the pain and let you turn on and manage HTTPS with simple commands. Using Certbot and Let's Encrypt is free, so there’s no need to arrange payment. How you use Certbot depends on the configuration of your web server. The best way to get started is to use our `interactive guide `_. It generates instructions based on your configuration settings. In most cases, you’ll need `root or administrator access `_ to your web server to run Certbot. If you’re using a hosted service and don’t have direct access to your web server, you might not be able to use Certbot. Check with your hosting provider for documentation about uploading certificates or using certificates issued by Let’s Encrypt. Certbot is a fully-featured, extensible client for the Let's Encrypt CA (or any other CA that speaks the `ACME `_ protocol) that can automate the tasks of obtaining certificates and configuring webservers to use them. This client runs on Unix-based operating systems. To see the changes made to Certbot between versions please refer to our `changelog `_. Until May 2016, Certbot was named simply ``letsencrypt`` or ``letsencrypt-auto``, depending on install method. Instructions on the Internet, and some pieces of the software, may still refer to this older name. Contributing ------------ If you'd like to contribute to this project please read `Developer Guide `_. .. _installation: Installation ------------ The easiest way to install Certbot is by visiting `certbot.eff.org`_, where you can find the correct installation instructions for many web server and OS combinations. For more information, see `Get Certbot `_. .. _certbot.eff.org: https://certbot.eff.org/ How to run the client --------------------- In many cases, you can just run ``certbot-auto`` or ``certbot``, and the client will guide you through the process of obtaining and installing certs interactively. For full command line help, you can type:: ./certbot-auto --help all You can also tell it exactly what you want it to do from the command line. For instance, if you want to obtain a cert for ``example.com``, ``www.example.com``, and ``other.example.net``, using the Apache plugin to both obtain and install the certs, you could do this:: ./certbot-auto --apache -d example.com -d www.example.com -d other.example.net (The first time you run the command, it will make an account, and ask for an email and agreement to the Let's Encrypt Subscriber Agreement; you can automate those with ``--email`` and ``--agree-tos``) If you want to use a webserver that doesn't have full plugin support yet, you can still use "standalone" or "webroot" plugins to obtain a certificate:: ./certbot-auto certonly --standalone --email admin@example.com -d example.com -d www.example.com -d other.example.net Understanding the client in more depth -------------------------------------- To understand what the client is doing in detail, it's important to understand the way it uses plugins. Please see the `explanation of plugins `_ in the User Guide. Links ===== .. Do not modify this comment unless you know what you're doing. tag:links-begin Documentation: https://certbot.eff.org/docs Software project: https://github.com/certbot/certbot Notes for developers: https://certbot.eff.org/docs/contributing.html Main Website: https://certbot.eff.org Let's Encrypt Website: https://letsencrypt.org IRC Channel: #letsencrypt on `Freenode`_ Community: https://community.letsencrypt.org ACME spec: http://ietf-wg-acme.github.io/acme/ ACME working area in github: https://github.com/ietf-wg-acme/acme |build-status| |coverage| |docs| |container| .. _Freenode: https://webchat.freenode.net?channels=%23letsencrypt .. |build-status| image:: https://travis-ci.org/certbot/certbot.svg?branch=master :target: https://travis-ci.org/certbot/certbot :alt: Travis CI status .. |coverage| image:: https://codecov.io/gh/certbot/certbot/branch/master/graph/badge.svg :target: https://codecov.io/gh/certbot/certbot :alt: Coverage status .. |docs| image:: https://readthedocs.org/projects/letsencrypt/badge/ :target: https://readthedocs.org/projects/letsencrypt/ :alt: Documentation status .. |container| image:: https://quay.io/repository/letsencrypt/letsencrypt/status :target: https://quay.io/repository/letsencrypt/letsencrypt :alt: Docker Repository on Quay.io .. Do not modify this comment unless you know what you're doing. tag:links-end System Requirements =================== See https://certbot.eff.org/docs/install.html#system-requirements. .. Do not modify this comment unless you know what you're doing. tag:intro-end .. Do not modify this comment unless you know what you're doing. tag:features-begin Current Features ===================== * Supports multiple web servers: - apache/2.x - nginx/0.8.48+ - webroot (adds files to webroot directories in order to prove control of domains and obtain certs) - standalone (runs its own simple webserver to prove you control a domain) - other server software via `third party plugins `_ * The private key is generated locally on your system. * Can talk to the Let's Encrypt CA or optionally to other ACME compliant services. * Can get domain-validated (DV) certificates. * Can revoke certificates. * Adjustable RSA key bit-length (2048 (default), 4096, ...). * Can optionally install a http -> https redirect, so your site effectively runs https only (Apache only) * Fully automated. * Configuration changes are logged and can be reverted. * Supports an interactive text UI, or can be driven entirely from the command line. * Free and Open Source Software, made with Python. .. Do not modify this comment unless you know what you're doing. tag:features-end For extensive documentation on using and contributing to Certbot, go to https://certbot.eff.org/docs. If you would like to contribute to the project or run the latest code from git, you should read our `developer guide `_. certbot-0.27.0/PKG-INFO0000644000175000017500000002337313344054435014544 0ustar ericaerica00000000000000Metadata-Version: 2.1 Name: certbot Version: 0.27.0 Summary: ACME client Home-page: https://github.com/letsencrypt/letsencrypt Author: Certbot Project Author-email: client-dev@letsencrypt.org License: Apache License 2.0 Description: .. This file contains a series of comments that are used to include sections of this README in other files. Do not modify these comments unless you know what you are doing. tag:intro-begin Certbot is part of EFF’s effort to encrypt the entire Internet. Secure communication over the Web relies on HTTPS, which requires the use of a digital certificate that lets browsers verify the identity of web servers (e.g., is that really google.com?). Web servers obtain their certificates from trusted third parties called certificate authorities (CAs). Certbot is an easy-to-use client that fetches a certificate from Let’s Encrypt—an open certificate authority launched by the EFF, Mozilla, and others—and deploys it to a web server. Anyone who has gone through the trouble of setting up a secure website knows what a hassle getting and maintaining a certificate is. Certbot and Let’s Encrypt can automate away the pain and let you turn on and manage HTTPS with simple commands. Using Certbot and Let's Encrypt is free, so there’s no need to arrange payment. How you use Certbot depends on the configuration of your web server. The best way to get started is to use our `interactive guide `_. It generates instructions based on your configuration settings. In most cases, you’ll need `root or administrator access `_ to your web server to run Certbot. If you’re using a hosted service and don’t have direct access to your web server, you might not be able to use Certbot. Check with your hosting provider for documentation about uploading certificates or using certificates issued by Let’s Encrypt. Certbot is a fully-featured, extensible client for the Let's Encrypt CA (or any other CA that speaks the `ACME `_ protocol) that can automate the tasks of obtaining certificates and configuring webservers to use them. This client runs on Unix-based operating systems. To see the changes made to Certbot between versions please refer to our `changelog `_. Until May 2016, Certbot was named simply ``letsencrypt`` or ``letsencrypt-auto``, depending on install method. Instructions on the Internet, and some pieces of the software, may still refer to this older name. Contributing ------------ If you'd like to contribute to this project please read `Developer Guide `_. .. _installation: Installation ------------ The easiest way to install Certbot is by visiting `certbot.eff.org`_, where you can find the correct installation instructions for many web server and OS combinations. For more information, see `Get Certbot `_. .. _certbot.eff.org: https://certbot.eff.org/ How to run the client --------------------- In many cases, you can just run ``certbot-auto`` or ``certbot``, and the client will guide you through the process of obtaining and installing certs interactively. For full command line help, you can type:: ./certbot-auto --help all You can also tell it exactly what you want it to do from the command line. For instance, if you want to obtain a cert for ``example.com``, ``www.example.com``, and ``other.example.net``, using the Apache plugin to both obtain and install the certs, you could do this:: ./certbot-auto --apache -d example.com -d www.example.com -d other.example.net (The first time you run the command, it will make an account, and ask for an email and agreement to the Let's Encrypt Subscriber Agreement; you can automate those with ``--email`` and ``--agree-tos``) If you want to use a webserver that doesn't have full plugin support yet, you can still use "standalone" or "webroot" plugins to obtain a certificate:: ./certbot-auto certonly --standalone --email admin@example.com -d example.com -d www.example.com -d other.example.net Understanding the client in more depth -------------------------------------- To understand what the client is doing in detail, it's important to understand the way it uses plugins. Please see the `explanation of plugins `_ in the User Guide. Links ===== .. Do not modify this comment unless you know what you're doing. tag:links-begin Documentation: https://certbot.eff.org/docs Software project: https://github.com/certbot/certbot Notes for developers: https://certbot.eff.org/docs/contributing.html Main Website: https://certbot.eff.org Let's Encrypt Website: https://letsencrypt.org IRC Channel: #letsencrypt on `Freenode`_ Community: https://community.letsencrypt.org ACME spec: http://ietf-wg-acme.github.io/acme/ ACME working area in github: https://github.com/ietf-wg-acme/acme |build-status| |coverage| |docs| |container| .. _Freenode: https://webchat.freenode.net?channels=%23letsencrypt .. |build-status| image:: https://travis-ci.org/certbot/certbot.svg?branch=master :target: https://travis-ci.org/certbot/certbot :alt: Travis CI status .. |coverage| image:: https://codecov.io/gh/certbot/certbot/branch/master/graph/badge.svg :target: https://codecov.io/gh/certbot/certbot :alt: Coverage status .. |docs| image:: https://readthedocs.org/projects/letsencrypt/badge/ :target: https://readthedocs.org/projects/letsencrypt/ :alt: Documentation status .. |container| image:: https://quay.io/repository/letsencrypt/letsencrypt/status :target: https://quay.io/repository/letsencrypt/letsencrypt :alt: Docker Repository on Quay.io .. Do not modify this comment unless you know what you're doing. tag:links-end System Requirements =================== See https://certbot.eff.org/docs/install.html#system-requirements. .. Do not modify this comment unless you know what you're doing. tag:intro-end .. Do not modify this comment unless you know what you're doing. tag:features-begin Current Features ===================== * Supports multiple web servers: - apache/2.x - nginx/0.8.48+ - webroot (adds files to webroot directories in order to prove control of domains and obtain certs) - standalone (runs its own simple webserver to prove you control a domain) - other server software via `third party plugins `_ * The private key is generated locally on your system. * Can talk to the Let's Encrypt CA or optionally to other ACME compliant services. * Can get domain-validated (DV) certificates. * Can revoke certificates. * Adjustable RSA key bit-length (2048 (default), 4096, ...). * Can optionally install a http -> https redirect, so your site effectively runs https only (Apache only) * Fully automated. * Configuration changes are logged and can be reverted. * Supports an interactive text UI, or can be driven entirely from the command line. * Free and Open Source Software, made with Python. .. Do not modify this comment unless you know what you're doing. tag:features-end For extensive documentation on using and contributing to Certbot, go to https://certbot.eff.org/docs. If you would like to contribute to the project or run the latest code from git, you should read our `developer guide `_. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Environment :: Console :: Curses Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Security Classifier: Topic :: System :: Installation/Setup Classifier: Topic :: System :: Networking Classifier: Topic :: System :: Systems Administration Classifier: Topic :: Utilities Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.* Provides-Extra: dev3 Provides-Extra: docs Provides-Extra: dev certbot-0.27.0/certbot/0002755000175000017500000000000013344054435015103 5ustar ericaerica00000000000000certbot-0.27.0/certbot/lock.py0000644000175000017500000001015113344054434016400 0ustar ericaerica00000000000000"""Implements file locks for locking files and directories in UNIX.""" import errno import fcntl import logging import os from certbot import errors logger = logging.getLogger(__name__) def lock_dir(dir_path): """Place a lock file on the directory at dir_path. The lock file is placed in the root of dir_path with the name .certbot.lock. :param str dir_path: path to directory :returns: the locked LockFile object :rtype: LockFile :raises errors.LockError: if unable to acquire the lock """ return LockFile(os.path.join(dir_path, '.certbot.lock')) class LockFile(object): """A UNIX lock file. This lock file is released when the locked file is closed or the process exits. It cannot be used to provide synchronization between threads. It is based on the lock_file package by Martin Horcicka. """ def __init__(self, path): """Initialize and acquire the lock file. :param str path: path to the file to lock :raises errors.LockError: if unable to acquire the lock """ super(LockFile, self).__init__() self._path = path self._fd = None self.acquire() def acquire(self): """Acquire the lock file. :raises errors.LockError: if lock is already held :raises OSError: if unable to open or stat the lock file """ while self._fd is None: # Open the file fd = os.open(self._path, os.O_CREAT | os.O_WRONLY, 0o600) try: self._try_lock(fd) if self._lock_success(fd): self._fd = fd finally: # Close the file if it is not the required one if self._fd is None: os.close(fd) def _try_lock(self, fd): """Try to acquire the lock file without blocking. :param int fd: file descriptor of the opened file to lock """ try: fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError as err: if err.errno in (errno.EACCES, errno.EAGAIN): logger.debug( "A lock on %s is held by another process.", self._path) raise errors.LockError( "Another instance of Certbot is already running.") raise def _lock_success(self, fd): """Did we successfully grab the lock? Because this class deletes the locked file when the lock is released, it is possible another process removed and recreated the file between us opening the file and acquiring the lock. :param int fd: file descriptor of the opened file to lock :returns: True if the lock was successfully acquired :rtype: bool """ try: stat1 = os.stat(self._path) except OSError as err: if err.errno == errno.ENOENT: return False raise stat2 = os.fstat(fd) # If our locked file descriptor and the file on disk refer to # the same device and inode, they're the same file. return stat1.st_dev == stat2.st_dev and stat1.st_ino == stat2.st_ino def __repr__(self): repr_str = '{0}({1}) <'.format(self.__class__.__name__, self._path) if self._fd is None: repr_str += 'released>' else: repr_str += 'acquired>' return repr_str def release(self): """Remove, close, and release the lock file.""" # It is important the lock file is removed before it's released, # otherwise: # # process A: open lock file # process B: release lock file # process A: lock file # process A: check device and inode # process B: delete file # process C: open and lock a different file at the same path # # Calling os.remove on a file that's in use doesn't work on # Windows, but neither does locking with fcntl. try: os.remove(self._path) finally: try: os.close(self._fd) finally: self._fd = None certbot-0.27.0/certbot/reporter.py0000644000175000017500000000673313344054434017325 0ustar ericaerica00000000000000"""Collects and displays information to the user.""" from __future__ import print_function import collections import logging import sys import textwrap from six.moves import queue # type: ignore # pylint: disable=import-error import zope.interface from certbot import interfaces from certbot import util logger = logging.getLogger(__name__) @zope.interface.implementer(interfaces.IReporter) class Reporter(object): """Collects and displays information to the user. :ivar `queue.PriorityQueue` messages: Messages to be displayed to the user. """ HIGH_PRIORITY = 0 """High priority constant. See `add_message`.""" MEDIUM_PRIORITY = 1 """Medium priority constant. See `add_message`.""" LOW_PRIORITY = 2 """Low priority constant. See `add_message`.""" _msg_type = collections.namedtuple('ReporterMsg', 'priority text on_crash') def __init__(self, config): self.messages = queue.PriorityQueue() self.config = config def add_message(self, msg, priority, on_crash=True): """Adds msg to the list of messages to be printed. :param str msg: Message to be displayed to the user. :param int priority: One of `HIGH_PRIORITY`, `MEDIUM_PRIORITY`, or `LOW_PRIORITY`. :param bool on_crash: Whether or not the message should be printed if the program exits abnormally. """ assert self.HIGH_PRIORITY <= priority <= self.LOW_PRIORITY self.messages.put(self._msg_type(priority, msg, on_crash)) logger.debug("Reporting to user: %s", msg) def print_messages(self): """Prints messages to the user and clears the message queue. If there is an unhandled exception, only messages for which ``on_crash`` is ``True`` are printed. """ bold_on = False if not self.messages.empty(): no_exception = sys.exc_info()[0] is None bold_on = sys.stdout.isatty() if not self.config.quiet: if bold_on: print(util.ANSI_SGR_BOLD) print('IMPORTANT NOTES:') first_wrapper = textwrap.TextWrapper( initial_indent=' - ', subsequent_indent=(' ' * 3), break_long_words=False, break_on_hyphens=False) next_wrapper = textwrap.TextWrapper( initial_indent=first_wrapper.subsequent_indent, subsequent_indent=first_wrapper.subsequent_indent, break_long_words=False, break_on_hyphens=False) while not self.messages.empty(): msg = self.messages.get() if self.config.quiet: # In --quiet mode, we only print high priority messages that # are flagged for crash cases if not (msg.priority == self.HIGH_PRIORITY and msg.on_crash): continue if no_exception or msg.on_crash: if bold_on and msg.priority > self.HIGH_PRIORITY: if not self.config.quiet: sys.stdout.write(util.ANSI_SGR_RESET) bold_on = False lines = msg.text.splitlines() print(first_wrapper.fill(lines[0])) if len(lines) > 1: print("\n".join( next_wrapper.fill(line) for line in lines[1:])) if bold_on and not self.config.quiet: sys.stdout.write(util.ANSI_SGR_RESET) certbot-0.27.0/certbot/errors.py0000644000175000017500000000513713344054434016774 0ustar ericaerica00000000000000"""Certbot client errors.""" class Error(Exception): """Generic Certbot client error.""" class AccountStorageError(Error): """Generic `.AccountStorage` error.""" class AccountNotFound(AccountStorageError): """Account not found error.""" class ReverterError(Error): """Certbot Reverter error.""" class SubprocessError(Error): """Subprocess handling error.""" class CertStorageError(Error): """Generic `.CertStorage` error.""" class HookCommandNotFound(Error): """Failed to find a hook command in the PATH.""" class SignalExit(Error): """A Unix signal was received while in the ErrorHandler context manager.""" class OverlappingMatchFound(Error): """Multiple lineages matched what should have been a unique result.""" class LockError(Error): """File locking error.""" # Auth Handler Errors class AuthorizationError(Error): """Authorization error.""" class FailedChallenges(AuthorizationError): """Failed challenges error. :ivar set failed_achalls: Failed `.AnnotatedChallenge` instances. """ def __init__(self, failed_achalls): assert failed_achalls self.failed_achalls = failed_achalls super(FailedChallenges, self).__init__() def __str__(self): return "Failed authorization procedure. {0}".format( ", ".join( "{0} ({1}): {2}".format(achall.domain, achall.typ, achall.error) for achall in self.failed_achalls if achall.error is not None)) # Plugin Errors class PluginError(Error): """Certbot Plugin error.""" class PluginEnhancementAlreadyPresent(Error): """ Enhancement was already set """ class PluginSelectionError(Error): """A problem with plugin/configurator selection or setup""" class NoInstallationError(PluginError): """Certbot No Installation error.""" class MisconfigurationError(PluginError): """Certbot Misconfiguration error.""" class NotSupportedError(PluginError): """Certbot Plugin function not supported error.""" class PluginStorageError(PluginError): """Certbot Plugin Storage error.""" class StandaloneBindError(Error): """Standalone plugin bind error.""" def __init__(self, socket_error, port): super(StandaloneBindError, self).__init__( "Problem binding to port {0}: {1}".format(port, socket_error)) self.socket_error = socket_error self.port = port class ConfigurationError(Error): """Configuration sanity error.""" # NoninteractiveDisplay iDisplay plugin error: class MissingCommandlineFlag(Error): """A command line argument was missing in noninteractive usage""" certbot-0.27.0/certbot/log.py0000644000175000017500000003055613344054434016244 0ustar ericaerica00000000000000"""Logging utilities for Certbot. The best way to use this module is through `pre_arg_parse_setup` and `post_arg_parse_setup`. `pre_arg_parse_setup` configures a minimal terminal logger and ensures a detailed log is written to a secure temporary file if Certbot exits before `post_arg_parse_setup` is called. `post_arg_parse_setup` relies on the parsed command line arguments and does the full logging setup with terminal and rotating file handling as configured by the user. Any logged messages before `post_arg_parse_setup` is called are sent to the rotating file handler. Special care is taken by both methods to ensure all errors are logged and properly flushed before program exit. """ from __future__ import print_function import functools import logging import logging.handlers import os import sys import tempfile import traceback from acme import messages from certbot import constants from certbot import errors from certbot import util # Logging format CLI_FMT = "%(message)s" FILE_FMT = "%(asctime)s:%(levelname)s:%(name)s:%(message)s" logger = logging.getLogger(__name__) def pre_arg_parse_setup(): """Setup logging before command line arguments are parsed. Terminal logging is setup using `certbot.constants.QUIET_LOGGING_LEVEL` so Certbot is as quiet as possible. File logging is setup so that logging messages are buffered in memory. If Certbot exits before `post_arg_parse_setup` is called, these buffered messages are written to a temporary file. If Certbot doesn't exit, `post_arg_parse_setup` writes the messages to the normal log files. This function also sets `logging.shutdown` to be called on program exit which automatically flushes logging handlers and `sys.excepthook` to properly log/display fatal exceptions. """ temp_handler = TempHandler() temp_handler.setFormatter(logging.Formatter(FILE_FMT)) temp_handler.setLevel(logging.DEBUG) memory_handler = MemoryHandler(temp_handler) stream_handler = ColoredStreamHandler() stream_handler.setFormatter(logging.Formatter(CLI_FMT)) stream_handler.setLevel(constants.QUIET_LOGGING_LEVEL) root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) # send all records to handlers root_logger.addHandler(memory_handler) root_logger.addHandler(stream_handler) # logging.shutdown will flush the memory handler because flush() and # close() are explicitly called util.atexit_register(logging.shutdown) sys.excepthook = functools.partial( pre_arg_parse_except_hook, memory_handler, debug='--debug' in sys.argv, log_path=temp_handler.path) def post_arg_parse_setup(config): """Setup logging after command line arguments are parsed. This function assumes `pre_arg_parse_setup` was called earlier and the root logging configuration has not been modified. A rotating file logging handler is created and the buffered log messages are sent to that handler. Terminal logging output is set to the level requested by the user. :param certbot.interface.IConfig config: Configuration object """ file_handler, file_path = setup_log_file_handler( config, 'letsencrypt.log', FILE_FMT) logs_dir = os.path.dirname(file_path) root_logger = logging.getLogger() memory_handler = stderr_handler = None for handler in root_logger.handlers: if isinstance(handler, ColoredStreamHandler): stderr_handler = handler elif isinstance(handler, MemoryHandler): memory_handler = handler msg = 'Previously configured logging handlers have been removed!' assert memory_handler is not None and stderr_handler is not None, msg root_logger.addHandler(file_handler) root_logger.removeHandler(memory_handler) temp_handler = memory_handler.target memory_handler.setTarget(file_handler) memory_handler.flush(force=True) memory_handler.close() temp_handler.close() if config.quiet: level = constants.QUIET_LOGGING_LEVEL else: level = -config.verbose_count * 10 stderr_handler.setLevel(level) logger.debug('Root logging level set at %d', level) logger.info('Saving debug log to %s', file_path) sys.excepthook = functools.partial( post_arg_parse_except_hook, debug=config.debug, log_path=logs_dir) def setup_log_file_handler(config, logfile, fmt): """Setup file debug logging. :param certbot.interface.IConfig config: Configuration object :param str logfile: basename for the log file :param str fmt: logging format string :returns: file handler and absolute path to the log file :rtype: tuple """ # TODO: logs might contain sensitive data such as contents of the # private key! #525 util.set_up_core_dir( config.logs_dir, 0o700, os.geteuid(), config.strict_permissions) log_file_path = os.path.join(config.logs_dir, logfile) try: handler = logging.handlers.RotatingFileHandler( log_file_path, maxBytes=2 ** 20, backupCount=config.max_log_backups) except IOError as error: raise errors.Error(util.PERM_ERR_FMT.format(error)) # rotate on each invocation, rollover only possible when maxBytes # is nonzero and backupCount is nonzero, so we set maxBytes as big # as possible not to overrun in single CLI invocation (1MB). handler.doRollover() # TODO: creates empty letsencrypt.log.1 file handler.setLevel(logging.DEBUG) handler_formatter = logging.Formatter(fmt=fmt) handler.setFormatter(handler_formatter) return handler, log_file_path class ColoredStreamHandler(logging.StreamHandler): """Sends colored logging output to a stream. If the specified stream is not a tty, the class works like the standard `logging.StreamHandler`. Default red_level is `logging.WARNING`. :ivar bool colored: True if output should be colored :ivar bool red_level: The level at which to output """ def __init__(self, stream=None): super(ColoredStreamHandler, self).__init__(stream) self.colored = (sys.stderr.isatty() if stream is None else stream.isatty()) self.red_level = logging.WARNING def format(self, record): """Formats the string representation of record. :param logging.LogRecord record: Record to be formatted :returns: Formatted, string representation of record :rtype: str """ out = super(ColoredStreamHandler, self).format(record) if self.colored and record.levelno >= self.red_level: return ''.join((util.ANSI_SGR_RED, out, util.ANSI_SGR_RESET)) else: return out class MemoryHandler(logging.handlers.MemoryHandler): """Buffers logging messages in memory until the buffer is flushed. This differs from `logging.handlers.MemoryHandler` in that flushing only happens when flush(force=True) is called. """ def __init__(self, target=None, capacity=10000): # capacity doesn't matter because should_flush() is overridden super(MemoryHandler, self).__init__(capacity, target=target) def close(self): """Close the memory handler, but don't set the target to None.""" # This allows the logging module which may only have a weak # reference to the target handler to properly flush and close it. target = self.target super(MemoryHandler, self).close() self.target = target def flush(self, force=False): # pylint: disable=arguments-differ """Flush the buffer if force=True. If force=False, this call is a noop. :param bool force: True if the buffer should be flushed. """ # This method allows flush() calls in logging.shutdown to be a # noop so we can control when this handler is flushed. if force: super(MemoryHandler, self).flush() def shouldFlush(self, record): """Should the buffer be automatically flushed? :param logging.LogRecord record: log record to be considered :returns: False because the buffer should never be auto-flushed :rtype: bool """ return False class TempHandler(logging.StreamHandler): """Safely logs messages to a temporary file. The file is created with permissions 600. If no log records are sent to this handler, the temporary file is deleted when the handler is closed. :ivar str path: file system path to the temporary log file """ def __init__(self): stream = tempfile.NamedTemporaryFile('w', delete=False) super(TempHandler, self).__init__(stream) self.path = stream.name self._delete = True def emit(self, record): """Log the specified logging record. :param logging.LogRecord record: Record to be formatted """ self._delete = False super(TempHandler, self).emit(record) def close(self): """Close the handler and the temporary log file. The temporary log file is deleted if it wasn't used. """ self.acquire() try: # StreamHandler.close() doesn't close the stream to allow a # stream like stderr to be used self.stream.close() if self._delete: os.remove(self.path) self._delete = False super(TempHandler, self).close() finally: self.release() def pre_arg_parse_except_hook(memory_handler, *args, **kwargs): """A simple wrapper around post_arg_parse_except_hook. The additional functionality provided by this wrapper is the memory handler will be flushed before Certbot exits. This allows us to write logging messages to a temporary file if we crashed before logging was fully configured. Since sys.excepthook isn't called on SystemExit exceptions, the memory handler will not be flushed in this case which prevents us from creating temporary log files when argparse exits because a command line argument was invalid or -h, --help, or --version was provided on the command line. :param MemoryHandler memory_handler: memory handler to flush :param tuple args: args for post_arg_parse_except_hook :param dict kwargs: kwargs for post_arg_parse_except_hook """ try: post_arg_parse_except_hook(*args, **kwargs) finally: # flush() is called here so messages logged during # post_arg_parse_except_hook are also flushed. memory_handler.flush(force=True) def post_arg_parse_except_hook(exc_type, exc_value, trace, debug, log_path): """Logs fatal exceptions and reports them to the user. If debug is True, the full exception and traceback is shown to the user, otherwise, it is suppressed. sys.exit is always called with a nonzero status. :param type exc_type: type of the raised exception :param BaseException exc_value: raised exception :param traceback trace: traceback of where the exception was raised :param bool debug: True if the traceback should be shown to the user :param str log_path: path to file or directory containing the log """ exc_info = (exc_type, exc_value, trace) # constants.QUIET_LOGGING_LEVEL or higher should be used to # display message the user, otherwise, a lower level like # logger.DEBUG should be used if debug or not issubclass(exc_type, Exception): assert constants.QUIET_LOGGING_LEVEL <= logging.ERROR logger.error('Exiting abnormally:', exc_info=exc_info) else: logger.debug('Exiting abnormally:', exc_info=exc_info) if issubclass(exc_type, errors.Error): sys.exit(exc_value) logger.error('An unexpected error occurred:') if messages.is_acme_error(exc_value): # Remove the ACME error prefix from the exception _, _, exc_str = str(exc_value).partition(':: ') logger.error(exc_str) else: traceback.print_exception(exc_type, exc_value, None) exit_with_log_path(log_path) def exit_with_log_path(log_path): """Print a message about the log location and exit. The message is printed to stderr and the program will exit with a nonzero status. :param str log_path: path to file or directory containing the log """ msg = 'Please see the ' if os.path.isdir(log_path): msg += 'logfiles in {0} '.format(log_path) else: msg += "logfile '{0}' ".format(log_path) msg += 'for more details.' sys.exit(msg) certbot-0.27.0/certbot/hooks.py0000644000175000017500000002070713344054434016603 0ustar ericaerica00000000000000"""Facilities for implementing hooks that call shell commands.""" from __future__ import print_function import logging import os from subprocess import Popen, PIPE from acme.magic_typing import Set, List # pylint: disable=unused-import, no-name-in-module from certbot import errors from certbot import util from certbot.plugins import util as plug_util logger = logging.getLogger(__name__) def validate_hooks(config): """Check hook commands are executable.""" validate_hook(config.pre_hook, "pre") validate_hook(config.post_hook, "post") validate_hook(config.deploy_hook, "deploy") validate_hook(config.renew_hook, "renew") def _prog(shell_cmd): """Extract the program run by a shell command. :param str shell_cmd: command to be executed :returns: basename of command or None if the command isn't found :rtype: str or None """ if not util.exe_exists(shell_cmd): plug_util.path_surgery(shell_cmd) if not util.exe_exists(shell_cmd): return None return os.path.basename(shell_cmd) def validate_hook(shell_cmd, hook_name): """Check that a command provided as a hook is plausibly executable. :raises .errors.HookCommandNotFound: if the command is not found """ if shell_cmd: cmd = shell_cmd.split(None, 1)[0] if not _prog(cmd): path = os.environ["PATH"] if os.path.exists(cmd): msg = "{1}-hook command {0} exists, but is not executable.".format(cmd, hook_name) else: msg = "Unable to find {2}-hook command {0} in the PATH.\n(PATH is {1})".format( cmd, path, hook_name) raise errors.HookCommandNotFound(msg) def pre_hook(config): """Run pre-hooks if they exist and haven't already been run. When Certbot is running with the renew subcommand, this function runs any hooks found in the config.renewal_pre_hooks_dir (if they have not already been run) followed by any pre-hook in the config. If hooks in config.renewal_pre_hooks_dir are run and the pre-hook in the config is a path to one of these scripts, it is not run twice. :param configuration.NamespaceConfig config: Certbot settings """ if config.verb == "renew" and config.directory_hooks: for hook in list_hooks(config.renewal_pre_hooks_dir): _run_pre_hook_if_necessary(hook) cmd = config.pre_hook if cmd: _run_pre_hook_if_necessary(cmd) executed_pre_hooks = set() # type: Set[str] def _run_pre_hook_if_necessary(command): """Run the specified pre-hook if we haven't already. If we've already run this exact command before, a message is logged saying the pre-hook was skipped. :param str command: pre-hook to be run """ if command in executed_pre_hooks: logger.info("Pre-hook command already run, skipping: %s", command) else: logger.info("Running pre-hook command: %s", command) _run_hook(command) executed_pre_hooks.add(command) def post_hook(config): """Run post-hooks if defined. This function also registers any executables found in config.renewal_post_hooks_dir to be run when Certbot is used with the renew subcommand. If the verb is renew, we delay executing any post-hooks until :func:`run_saved_post_hooks` is called. In this case, this function registers all hooks found in config.renewal_post_hooks_dir to be called followed by any post-hook in the config. If the post-hook in the config is a path to an executable in the post-hook directory, it is not scheduled to be run twice. :param configuration.NamespaceConfig config: Certbot settings """ cmd = config.post_hook # In the "renew" case, we save these up to run at the end if config.verb == "renew": if config.directory_hooks: for hook in list_hooks(config.renewal_post_hooks_dir): _run_eventually(hook) if cmd: _run_eventually(cmd) # certonly / run elif cmd: logger.info("Running post-hook command: %s", cmd) _run_hook(cmd) post_hooks = [] # type: List[str] def _run_eventually(command): """Registers a post-hook to be run eventually. All commands given to this function will be run exactly once in the order they were given when :func:`run_saved_post_hooks` is called. :param str command: post-hook to register to be run """ if command not in post_hooks: post_hooks.append(command) def run_saved_post_hooks(): """Run any post hooks that were saved up in the course of the 'renew' verb""" for cmd in post_hooks: logger.info("Running post-hook command: %s", cmd) _run_hook(cmd) def deploy_hook(config, domains, lineage_path): """Run post-issuance hook if defined. :param configuration.NamespaceConfig config: Certbot settings :param domains: domains in the obtained certificate :type domains: `list` of `str` :param str lineage_path: live directory path for the new cert """ if config.deploy_hook: _run_deploy_hook(config.deploy_hook, domains, lineage_path, config.dry_run) def renew_hook(config, domains, lineage_path): """Run post-renewal hooks. This function runs any hooks found in config.renewal_deploy_hooks_dir followed by any renew-hook in the config. If the renew-hook in the config is a path to a script in config.renewal_deploy_hooks_dir, it is not run twice. If Certbot is doing a dry run, no hooks are run and messages are logged saying that they were skipped. :param configuration.NamespaceConfig config: Certbot settings :param domains: domains in the obtained certificate :type domains: `list` of `str` :param str lineage_path: live directory path for the new cert """ executed_dir_hooks = set() if config.directory_hooks: for hook in list_hooks(config.renewal_deploy_hooks_dir): _run_deploy_hook(hook, domains, lineage_path, config.dry_run) executed_dir_hooks.add(hook) if config.renew_hook: if config.renew_hook in executed_dir_hooks: logger.info("Skipping deploy-hook '%s' as it was already run.", config.renew_hook) else: _run_deploy_hook(config.renew_hook, domains, lineage_path, config.dry_run) def _run_deploy_hook(command, domains, lineage_path, dry_run): """Run the specified deploy-hook (if not doing a dry run). If dry_run is True, command is not run and a message is logged saying that it was skipped. If dry_run is False, the hook is run after setting the appropriate environment variables. :param str command: command to run as a deploy-hook :param domains: domains in the obtained certificate :type domains: `list` of `str` :param str lineage_path: live directory path for the new cert :param bool dry_run: True iff Certbot is doing a dry run """ if dry_run: logger.warning("Dry run: skipping deploy hook command: %s", command) return os.environ["RENEWED_DOMAINS"] = " ".join(domains) os.environ["RENEWED_LINEAGE"] = lineage_path logger.info("Running deploy-hook command: %s", command) _run_hook(command) def _run_hook(shell_cmd): """Run a hook command. :returns: stderr if there was any""" err, _ = execute(shell_cmd) return err def execute(shell_cmd): """Run a command. :returns: `tuple` (`str` stderr, `str` stdout)""" # universal_newlines causes Popen.communicate() # to return str objects instead of bytes in Python 3 cmd = Popen(shell_cmd, shell=True, stdout=PIPE, stderr=PIPE, universal_newlines=True) out, err = cmd.communicate() base_cmd = os.path.basename(shell_cmd.split(None, 1)[0]) if out: logger.info('Output from %s:\n%s', base_cmd, out) if cmd.returncode != 0: logger.error('Hook command "%s" returned error code %d', shell_cmd, cmd.returncode) if err: logger.error('Error output from %s:\n%s', base_cmd, err) return (err, out) def list_hooks(dir_path): """List paths to all hooks found in dir_path in sorted order. :param str dir_path: directory to search :returns: `list` of `str` :rtype: sorted list of absolute paths to executables in dir_path """ paths = (os.path.join(dir_path, f) for f in os.listdir(dir_path)) return sorted(path for path in paths if util.is_exe(path)) certbot-0.27.0/certbot/auth_handler.py0000644000175000017500000005046513344054434020122 0ustar ericaerica00000000000000"""ACME AuthHandler.""" import collections import logging import time import six import zope.component from acme import challenges from acme import messages # pylint: disable=unused-import, no-name-in-module from acme.magic_typing import DefaultDict, Dict, List, Set, Collection # pylint: enable=unused-import, no-name-in-module from certbot import achallenges from certbot import errors from certbot import error_handler from certbot import interfaces logger = logging.getLogger(__name__) AnnotatedAuthzr = collections.namedtuple("AnnotatedAuthzr", ["authzr", "achalls"]) """Stores an authorization resource and its active annotated challenges.""" class AuthHandler(object): """ACME Authorization Handler for a client. :ivar auth: Authenticator capable of solving :class:`~acme.challenges.Challenge` types :type auth: :class:`certbot.interfaces.IAuthenticator` :ivar acme.client.BackwardsCompatibleClientV2 acme: ACME client API. :ivar account: Client's Account :type account: :class:`certbot.account.Account` :ivar list pref_challs: sorted user specified preferred challenges type strings with the most preferred challenge listed first """ def __init__(self, auth, acme, account, pref_challs): self.auth = auth self.acme = acme self.account = account self.pref_challs = pref_challs def handle_authorizations(self, orderr, best_effort=False): """Retrieve all authorizations for challenges. :param acme.messages.OrderResource orderr: must have authorizations filled in :param bool best_effort: Whether or not all authorizations are required (this is useful in renewal) :returns: List of authorization resources :rtype: list :raises .AuthorizationError: If unable to retrieve all authorizations """ aauthzrs = [AnnotatedAuthzr(authzr, []) for authzr in orderr.authorizations] self._choose_challenges(aauthzrs) config = zope.component.getUtility(interfaces.IConfig) notify = zope.component.getUtility(interfaces.IDisplay).notification # While there are still challenges remaining... while self._has_challenges(aauthzrs): with error_handler.ExitHandler(self._cleanup_challenges, aauthzrs): resp = self._solve_challenges(aauthzrs) logger.info("Waiting for verification...") if config.debug_challenges: notify('Challenges loaded. Press continue to submit to CA. ' 'Pass "-v" for more info about challenges.', pause=True) # Send all Responses - this modifies achalls self._respond(aauthzrs, resp, best_effort) # Just make sure all decisions are complete. self.verify_authzr_complete(aauthzrs) # Only return valid authorizations retVal = [aauthzr.authzr for aauthzr in aauthzrs if aauthzr.authzr.body.status == messages.STATUS_VALID] if not retVal: raise errors.AuthorizationError( "Challenges failed for all domains") return retVal def _choose_challenges(self, aauthzrs): """Retrieve necessary challenges to satisfy server.""" logger.info("Performing the following challenges:") for aauthzr in aauthzrs: aauthzr_challenges = aauthzr.authzr.body.challenges if self.acme.acme_version == 1: combinations = aauthzr.authzr.body.combinations else: combinations = tuple((i,) for i in range(len(aauthzr_challenges))) path = gen_challenge_path( aauthzr_challenges, self._get_chall_pref(aauthzr.authzr.body.identifier.value), combinations) aauthzr_achalls = self._challenge_factory( aauthzr.authzr, path) aauthzr.achalls.extend(aauthzr_achalls) def _has_challenges(self, aauthzrs): """Do we have any challenges to perform?""" return any(aauthzr.achalls for aauthzr in aauthzrs) def _solve_challenges(self, aauthzrs): """Get Responses for challenges from authenticators.""" resp = [] # type: Collection[acme.challenges.ChallengeResponse] all_achalls = self._get_all_achalls(aauthzrs) try: if all_achalls: resp = self.auth.perform(all_achalls) except errors.AuthorizationError: logger.critical("Failure in setting up challenges.") logger.info("Attempting to clean up outstanding challenges...") raise assert len(resp) == len(all_achalls) return resp def _get_all_achalls(self, aauthzrs): """Return all active challenges.""" all_achalls = [] # type: Collection[challenges.ChallengeResponse] for aauthzr in aauthzrs: all_achalls.extend(aauthzr.achalls) return all_achalls def _respond(self, aauthzrs, resp, best_effort): """Send/Receive confirmation of all challenges. .. note:: This method also cleans up the auth_handler state. """ # TODO: chall_update is a dirty hack to get around acme-spec #105 chall_update = dict() \ # type: Dict[int, List[achallenges.KeyAuthorizationAnnotatedChallenge]] self._send_responses(aauthzrs, resp, chall_update) # Check for updated status... self._poll_challenges(aauthzrs, chall_update, best_effort) def _send_responses(self, aauthzrs, resps, chall_update): """Send responses and make sure errors are handled. :param aauthzrs: authorizations and the selected annotated challenges to try and perform :type aauthzrs: `list` of `AnnotatedAuthzr` :param resps: challenge responses from the authenticator where each response at index i corresponds to the annotated challenge at index i in the list returned by :func:`_get_all_achalls` :type resps: `collections.abc.Iterable` of :class:`~acme.challenges.ChallengeResponse` or `False` or `None` :param dict chall_update: parameter that is updated to hold aauthzr index to list of outstanding solved annotated challenges """ active_achalls = [] resps_iter = iter(resps) for i, aauthzr in enumerate(aauthzrs): for achall in aauthzr.achalls: # This line needs to be outside of the if block below to # ensure failed challenges are cleaned up correctly active_achalls.append(achall) resp = next(resps_iter) # Don't send challenges for None and False authenticator responses if resp: self.acme.answer_challenge(achall.challb, resp) # TODO: answer_challenge returns challr, with URI, # that can be used in _find_updated_challr # comparisons... chall_update.setdefault(i, []).append(achall) return active_achalls def _poll_challenges(self, aauthzrs, chall_update, best_effort, min_sleep=3, max_rounds=30): """Wait for all challenge results to be determined.""" indices_to_check = set(chall_update.keys()) comp_indices = set() rounds = 0 while indices_to_check and rounds < max_rounds: # TODO: Use retry-after... time.sleep(min_sleep) all_failed_achalls = set() # type: Set[achallenges.KeyAuthorizationAnnotatedChallenge] for index in indices_to_check: comp_achalls, failed_achalls = self._handle_check( aauthzrs, index, chall_update[index]) if len(comp_achalls) == len(chall_update[index]): comp_indices.add(index) elif not failed_achalls: for achall, _ in comp_achalls: chall_update[index].remove(achall) # We failed some challenges... damage control else: if best_effort: comp_indices.add(index) logger.warning( "Challenge failed for domain %s", aauthzrs[index].authzr.body.identifier.value) else: all_failed_achalls.update( updated for _, updated in failed_achalls) if all_failed_achalls: _report_failed_challs(all_failed_achalls) raise errors.FailedChallenges(all_failed_achalls) indices_to_check -= comp_indices comp_indices.clear() rounds += 1 def _handle_check(self, aauthzrs, index, achalls): """Returns tuple of ('completed', 'failed').""" completed = [] failed = [] original_aauthzr = aauthzrs[index] updated_authzr, _ = self.acme.poll(original_aauthzr.authzr) aauthzrs[index] = AnnotatedAuthzr(updated_authzr, original_aauthzr.achalls) if updated_authzr.body.status == messages.STATUS_VALID: return achalls, [] # Note: if the whole authorization is invalid, the individual failed # challenges will be determined here... for achall in achalls: updated_achall = achall.update(challb=self._find_updated_challb( updated_authzr, achall)) # This does nothing for challenges that have yet to be decided yet. if updated_achall.status == messages.STATUS_VALID: completed.append((achall, updated_achall)) elif updated_achall.status == messages.STATUS_INVALID: failed.append((achall, updated_achall)) return completed, failed def _find_updated_challb(self, authzr, achall): # pylint: disable=no-self-use """Find updated challenge body within Authorization Resource. .. warning:: This assumes only one instance of type of challenge in each challenge resource. :param .AuthorizationResource authzr: Authorization Resource :param .AnnotatedChallenge achall: Annotated challenge for which to get status """ for authzr_challb in authzr.body.challenges: if type(authzr_challb.chall) is type(achall.challb.chall): # noqa return authzr_challb raise errors.AuthorizationError( "Target challenge not found in authorization resource") def _get_chall_pref(self, domain): """Return list of challenge preferences. :param str domain: domain for which you are requesting preferences """ chall_prefs = [] # Make sure to make a copy... plugin_pref = self.auth.get_chall_pref(domain) if self.pref_challs: plugin_pref_types = set(chall.typ for chall in plugin_pref) for typ in self.pref_challs: if typ in plugin_pref_types: chall_prefs.append(challenges.Challenge.TYPES[typ]) if chall_prefs: return chall_prefs raise errors.AuthorizationError( "None of the preferred challenges " "are supported by the selected plugin") chall_prefs.extend(plugin_pref) return chall_prefs def _cleanup_challenges(self, aauthzrs, achalls=None): """Cleanup challenges. :param aauthzrs: authorizations and their selected annotated challenges :type aauthzrs: `list` of `AnnotatedAuthzr` :param achalls: annotated challenges to cleanup :type achalls: `list` of :class:`certbot.achallenges.AnnotatedChallenge` """ logger.info("Cleaning up challenges") if achalls is None: achalls = self._get_all_achalls(aauthzrs) if achalls: self.auth.cleanup(achalls) for achall in achalls: for aauthzr in aauthzrs: if achall in aauthzr.achalls: aauthzr.achalls.remove(achall) break def verify_authzr_complete(self, aauthzrs): """Verifies that all authorizations have been decided. :param aauthzrs: authorizations and their selected annotated challenges :type aauthzrs: `list` of `AnnotatedAuthzr` :returns: Whether all authzr are complete :rtype: bool """ for aauthzr in aauthzrs: authzr = aauthzr.authzr if (authzr.body.status != messages.STATUS_VALID and authzr.body.status != messages.STATUS_INVALID): raise errors.AuthorizationError("Incomplete authorizations") def _challenge_factory(self, authzr, path): """Construct Namedtuple Challenges :param messages.AuthorizationResource authzr: authorization :param list path: List of indices from `challenges`. :returns: achalls, list of challenge type :class:`certbot.achallenges.Indexed` :rtype: list :raises .errors.Error: if challenge type is not recognized """ achalls = [] for index in path: challb = authzr.body.challenges[index] achalls.append(challb_to_achall( challb, self.account.key, authzr.body.identifier.value)) return achalls def challb_to_achall(challb, account_key, domain): """Converts a ChallengeBody object to an AnnotatedChallenge. :param .ChallengeBody challb: ChallengeBody :param .JWK account_key: Authorized Account Key :param str domain: Domain of the challb :returns: Appropriate AnnotatedChallenge :rtype: :class:`certbot.achallenges.AnnotatedChallenge` """ chall = challb.chall logger.info("%s challenge for %s", chall.typ, domain) if isinstance(chall, challenges.KeyAuthorizationChallenge): return achallenges.KeyAuthorizationAnnotatedChallenge( challb=challb, domain=domain, account_key=account_key) elif isinstance(chall, challenges.DNS): return achallenges.DNS(challb=challb, domain=domain) else: raise errors.Error( "Received unsupported challenge of type: %s", chall.typ) def gen_challenge_path(challbs, preferences, combinations): """Generate a plan to get authority over the identity. .. todo:: This can be possibly be rewritten to use resolved_combinations. :param tuple challbs: A tuple of challenges (:class:`acme.messages.Challenge`) from :class:`acme.messages.AuthorizationResource` to be fulfilled by the client in order to prove possession of the identifier. :param list preferences: List of challenge preferences for domain (:class:`acme.challenges.Challenge` subclasses) :param tuple combinations: A collection of sets of challenges from :class:`acme.messages.Challenge`, each of which would be sufficient to prove possession of the identifier. :returns: tuple of indices from ``challenges``. :rtype: tuple :raises certbot.errors.AuthorizationError: If a path cannot be created that satisfies the CA given the preferences and combinations. """ if combinations: return _find_smart_path(challbs, preferences, combinations) else: return _find_dumb_path(challbs, preferences) def _find_smart_path(challbs, preferences, combinations): """Find challenge path with server hints. Can be called if combinations is included. Function uses a simple ranking system to choose the combo with the lowest cost. """ chall_cost = {} max_cost = 1 for i, chall_cls in enumerate(preferences): chall_cost[chall_cls] = i max_cost += i # max_cost is now equal to sum(indices) + 1 best_combo = None # Set above completing all of the available challenges best_combo_cost = max_cost combo_total = 0 for combo in combinations: for challenge_index in combo: combo_total += chall_cost.get(challbs[ challenge_index].chall.__class__, max_cost) if combo_total < best_combo_cost: best_combo = combo best_combo_cost = combo_total combo_total = 0 if not best_combo: _report_no_chall_path(challbs) return best_combo def _find_dumb_path(challbs, preferences): """Find challenge path without server hints. Should be called if the combinations hint is not included by the server. This function either returns a path containing all challenges provided by the CA or raises an exception. """ path = [] for i, challb in enumerate(challbs): # supported is set to True if the challenge type is supported supported = next((True for pref_c in preferences if isinstance(challb.chall, pref_c)), False) if supported: path.append(i) else: _report_no_chall_path(challbs) return path def _report_no_chall_path(challbs): """Logs and raises an error that no satisfiable chall path exists. :param challbs: challenges from the authorization that can't be satisfied """ msg = ("Client with the currently selected authenticator does not support " "any combination of challenges that will satisfy the CA.") if len(challbs) == 1 and isinstance(challbs[0].chall, challenges.DNS01): msg += ( " You may need to use an authenticator " "plugin that can do challenges over DNS.") logger.critical(msg) raise errors.AuthorizationError(msg) _ERROR_HELP_COMMON = ( "To fix these errors, please make sure that your domain name was entered " "correctly and the DNS A/AAAA record(s) for that domain contain(s) the " "right IP address.") _ERROR_HELP = { "connection": _ERROR_HELP_COMMON + " Additionally, please check that your computer " "has a publicly routable IP address and that no firewalls are preventing " "the server from communicating with the client. If you're using the " "webroot plugin, you should also verify that you are serving files " "from the webroot path you provided.", "dnssec": _ERROR_HELP_COMMON + " Additionally, if you have DNSSEC enabled for " "your domain, please ensure that the signature is valid.", "malformed": "To fix these errors, please make sure that you did not provide any " "invalid information to the client, and try running Certbot " "again.", "serverInternal": "Unfortunately, an error on the ACME server prevented you from completing " "authorization. Please try again later.", "tls": _ERROR_HELP_COMMON + " Additionally, please check that you have an " "up-to-date TLS configuration that allows the server to communicate " "with the Certbot client.", "unauthorized": _ERROR_HELP_COMMON, "unknownHost": _ERROR_HELP_COMMON, } def _report_failed_challs(failed_achalls): """Notifies the user about failed challenges. :param set failed_achalls: A set of failed :class:`certbot.achallenges.AnnotatedChallenge`. """ problems = collections.defaultdict(list)\ # type: DefaultDict[str, List[achallenges.KeyAuthorizationAnnotatedChallenge]] for achall in failed_achalls: if achall.error: problems[achall.error.typ].append(achall) reporter = zope.component.getUtility(interfaces.IReporter) for achalls in six.itervalues(problems): reporter.add_message( _generate_failed_chall_msg(achalls), reporter.MEDIUM_PRIORITY) def _generate_failed_chall_msg(failed_achalls): """Creates a user friendly error message about failed challenges. :param list failed_achalls: A list of failed :class:`certbot.achallenges.AnnotatedChallenge` with the same error type. :returns: A formatted error message for the client. :rtype: str """ error = failed_achalls[0].error typ = error.typ if messages.is_acme_error(error): typ = error.code msg = ["The following errors were reported by the server:"] for achall in failed_achalls: msg.append("\n\nDomain: %s\nType: %s\nDetail: %s" % ( achall.domain, typ, achall.error.detail)) if typ in _ERROR_HELP: msg.append("\n\n") msg.append(_ERROR_HELP[typ]) return "".join(msg) certbot-0.27.0/certbot/ocsp.py0000644000175000017500000001014013344054434016412 0ustar ericaerica00000000000000"""Tools for checking certificate revocation.""" import logging import re from subprocess import Popen, PIPE from certbot import errors from certbot import util logger = logging.getLogger(__name__) class RevocationChecker(object): "This class figures out OCSP checking on this system, and performs it." def __init__(self): self.broken = False if not util.exe_exists("openssl"): logger.info("openssl not installed, can't check revocation") self.broken = True return # New versions of openssl want -header var=val, old ones want -header var val test_host_format = Popen(["openssl", "ocsp", "-header", "var", "val"], stdout=PIPE, stderr=PIPE, universal_newlines=True) _out, err = test_host_format.communicate() if "Missing =" in err: self.host_args = lambda host: ["Host=" + host] else: self.host_args = lambda host: ["Host", host] def ocsp_revoked(self, cert_path, chain_path): """Get revoked status for a particular cert version. .. todo:: Make this a non-blocking call :param str cert_path: Path to certificate :param str chain_path: Path to intermediate cert :rtype bool or None: :returns: True if revoked; False if valid or the check failed """ if self.broken: return False url, host = self.determine_ocsp_server(cert_path) if not host: return False # jdkasten thanks "Bulletproof SSL and TLS - Ivan Ristic" for documenting this! cmd = ["openssl", "ocsp", "-no_nonce", "-issuer", chain_path, "-cert", cert_path, "-url", url, "-CAfile", chain_path, "-verify_other", chain_path, "-trust_other", "-header"] + self.host_args(host) logger.debug("Querying OCSP for %s", cert_path) logger.debug(" ".join(cmd)) try: output, err = util.run_script(cmd, log=logger.debug) except errors.SubprocessError: logger.info("OCSP check failed for %s (are we offline?)", cert_path) return False return _translate_ocsp_query(cert_path, output, err) def determine_ocsp_server(self, cert_path): """Extract the OCSP server host from a certificate. :param str cert_path: Path to the cert we're checking OCSP for :rtype tuple: :returns: (OCSP server URL or None, OCSP server host or None) """ try: url, _err = util.run_script( ["openssl", "x509", "-in", cert_path, "-noout", "-ocsp_uri"], log=logger.debug) except errors.SubprocessError: logger.info("Cannot extract OCSP URI from %s", cert_path) return None, None url = url.rstrip() host = url.partition("://")[2].rstrip("/") if host: return url, host else: logger.info("Cannot process OCSP host from URL (%s) in cert at %s", url, cert_path) return None, None def _translate_ocsp_query(cert_path, ocsp_output, ocsp_errors): """Parse openssl's weird output to work out what it means.""" states = ("good", "revoked", "unknown") patterns = [r"{0}: (WARNING.*)?{1}".format(cert_path, s) for s in states] good, revoked, unknown = (re.search(p, ocsp_output, flags=re.DOTALL) for p in patterns) warning = good.group(1) if good else None if (not "Response verify OK" in ocsp_errors) or (good and warning) or unknown: logger.info("Revocation status for %s is unknown", cert_path) logger.debug("Uncertain output:\n%s\nstderr:\n%s", ocsp_output, ocsp_errors) return False elif good and not warning: return False elif revoked: warning = revoked.group(1) if warning: logger.info("OCSP revocation warning: %s", warning) return True else: logger.warn("Unable to properly parse OCSP output: %s\nstderr:%s", ocsp_output, ocsp_errors) return False certbot-0.27.0/certbot/util.py0000644000175000017500000005051413344054434016434 0ustar ericaerica00000000000000"""Utilities for all Certbot.""" import argparse import atexit import collections # distutils.version under virtualenv confuses pylint # For more info, see: https://github.com/PyCQA/pylint/issues/73 import distutils.version # pylint: disable=import-error,no-name-in-module import errno import logging import os import platform import re import six import socket import stat import subprocess import sys from collections import OrderedDict import configargparse from acme.magic_typing import Tuple, Union # pylint: disable=unused-import, no-name-in-module from certbot import constants from certbot import errors from certbot import lock logger = logging.getLogger(__name__) Key = collections.namedtuple("Key", "file pem") # Note: form is the type of data, "pem" or "der" CSR = collections.namedtuple("CSR", "file data form") # ANSI SGR escape codes # Formats text as bold or with increased intensity ANSI_SGR_BOLD = '\033[1m' # Colors text red ANSI_SGR_RED = "\033[31m" # Resets output format ANSI_SGR_RESET = "\033[0m" PERM_ERR_FMT = os.linesep.join(( "The following error was encountered:", "{0}", "Either run as root, or set --config-dir, " "--work-dir, and --logs-dir to writeable paths.")) # Stores importing process ID to be used by atexit_register() _INITIAL_PID = os.getpid() # Maps paths to locked directories to their lock object. All locks in # the dict are attempted to be cleaned up at program exit. If the # program exits before the lock is cleaned up, it is automatically # released, but the file isn't deleted. _LOCKS = OrderedDict() # type: OrderedDict[str, lock.LockFile] def run_script(params, log=logger.error): """Run the script with the given params. :param list params: List of parameters to pass to Popen :param logging.Logger log: Logger to use for errors """ try: proc = subprocess.Popen(params, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) except (OSError, ValueError): msg = "Unable to run the command: %s" % " ".join(params) log(msg) raise errors.SubprocessError(msg) stdout, stderr = proc.communicate() if proc.returncode != 0: msg = "Error while running %s.\n%s\n%s" % ( " ".join(params), stdout, stderr) # Enter recovery routine... log(msg) raise errors.SubprocessError(msg) return stdout, stderr def is_exe(path): """Is path an executable file? :param str path: path to test :returns: True iff path is an executable file :rtype: bool """ return os.path.isfile(path) and os.access(path, os.X_OK) def exe_exists(exe): """Determine whether path/name refers to an executable. :param str exe: Executable path or name :returns: If exe is a valid executable :rtype: bool """ path, _ = os.path.split(exe) if path: return is_exe(exe) else: for path in os.environ["PATH"].split(os.pathsep): if is_exe(os.path.join(path, exe)): return True return False def lock_dir_until_exit(dir_path): """Lock the directory at dir_path until program exit. :param str dir_path: path to directory :raises errors.LockError: if the lock is held by another process """ if not _LOCKS: # this is the first lock to be released at exit atexit_register(_release_locks) if dir_path not in _LOCKS: _LOCKS[dir_path] = lock.lock_dir(dir_path) def _release_locks(): for dir_lock in six.itervalues(_LOCKS): try: dir_lock.release() except: # pylint: disable=bare-except msg = 'Exception occurred releasing lock: {0!r}'.format(dir_lock) logger.debug(msg, exc_info=True) def set_up_core_dir(directory, mode, uid, strict): """Ensure directory exists with proper permissions and is locked. :param str directory: Path to a directory. :param int mode: Directory mode. :param int uid: Directory owner. :param bool strict: require directory to be owned by current user :raises .errors.LockError: if the directory cannot be locked :raises .errors.Error: if the directory cannot be made or verified """ try: make_or_verify_dir(directory, mode, uid, strict) lock_dir_until_exit(directory) except OSError as error: logger.debug("Exception was:", exc_info=True) raise errors.Error(PERM_ERR_FMT.format(error)) def make_or_verify_dir(directory, mode=0o755, uid=0, strict=False): """Make sure directory exists with proper permissions. :param str directory: Path to a directory. :param int mode: Directory mode. :param int uid: Directory owner. :param bool strict: require directory to be owned by current user :raises .errors.Error: if a directory already exists, but has wrong permissions or owner :raises OSError: if invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. """ try: os.makedirs(directory, mode) except OSError as exception: if exception.errno == errno.EEXIST: if strict and not check_permissions(directory, mode, uid): raise errors.Error( "%s exists, but it should be owned by user %d with" "permissions %s" % (directory, uid, oct(mode))) else: raise def check_permissions(filepath, mode, uid=0): """Check file or directory permissions. :param str filepath: Path to the tested file (or directory). :param int mode: Expected file mode. :param int uid: Expected file owner. :returns: True if `mode` and `uid` match, False otherwise. :rtype: bool """ file_stat = os.stat(filepath) return stat.S_IMODE(file_stat.st_mode) == mode and file_stat.st_uid == uid def safe_open(path, mode="w", chmod=None, buffering=None): """Safely open a file. :param str path: Path to a file. :param str mode: Same os `mode` for `open`. :param int chmod: Same as `mode` for `os.open`, uses Python defaults if ``None``. :param int buffering: Same as `bufsize` for `os.fdopen`, uses Python defaults if ``None``. """ # pylint: disable=star-args open_args = () # type: Union[Tuple[()], Tuple[int]] if chmod is not None: open_args = (chmod,) fdopen_args = () # type: Union[Tuple[()], Tuple[int]] if buffering is not None: fdopen_args = (buffering,) return os.fdopen( os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, *open_args), mode, *fdopen_args) def _unique_file(path, filename_pat, count, chmod, mode): while True: current_path = os.path.join(path, filename_pat(count)) try: return safe_open(current_path, chmod=chmod, mode=mode),\ os.path.abspath(current_path) except OSError as err: # "File exists," is okay, try a different name. if err.errno != errno.EEXIST: raise count += 1 def unique_file(path, chmod=0o777, mode="w"): """Safely finds a unique file. :param str path: path/filename.ext :param int chmod: File mode :param str mode: Open mode :returns: tuple of file object and file name """ path, tail = os.path.split(path) return _unique_file( path, filename_pat=(lambda count: "%04d_%s" % (count, tail)), count=0, chmod=chmod, mode=mode) def unique_lineage_name(path, filename, chmod=0o644, mode="w"): """Safely finds a unique file using lineage convention. :param str path: directory path :param str filename: proposed filename :param int chmod: file mode :param str mode: open mode :returns: tuple of file object and file name (which may be modified from the requested one by appending digits to ensure uniqueness) :raises OSError: if writing files fails for an unanticipated reason, such as a full disk or a lack of permission to write to specified location. """ preferred_path = os.path.join(path, "%s.conf" % (filename)) try: return safe_open(preferred_path, chmod=chmod), preferred_path except OSError as err: if err.errno != errno.EEXIST: raise return _unique_file( path, filename_pat=(lambda count: "%s-%04d.conf" % (filename, count)), count=1, chmod=chmod, mode=mode) def safely_remove(path): """Remove a file that may not exist.""" try: os.remove(path) except OSError as err: if err.errno != errno.ENOENT: raise def get_filtered_names(all_names): """Removes names that aren't considered valid by Let's Encrypt. :param set all_names: all names found in the configuration :returns: all found names that are considered valid by LE :rtype: set """ filtered_names = set() for name in all_names: try: filtered_names.add(enforce_le_validity(name)) except errors.ConfigurationError: logger.debug('Not suggesting name "%s"', name, exc_info=True) return filtered_names def get_os_info(filepath="/etc/os-release"): """ Get OS name and version :param str filepath: File path of os-release file :returns: (os_name, os_version) :rtype: `tuple` of `str` """ if os.path.isfile(filepath): # Systemd os-release parsing might be viable os_name, os_version = get_systemd_os_info(filepath=filepath) if os_name: return (os_name, os_version) # Fallback to platform module return get_python_os_info() def get_os_info_ua(filepath="/etc/os-release"): """ Get OS name and version string for User Agent :param str filepath: File path of os-release file :returns: os_ua :rtype: `str` """ if os.path.isfile(filepath): os_ua = get_var_from_file("PRETTY_NAME", filepath=filepath) if not os_ua: os_ua = get_var_from_file("NAME", filepath=filepath) if os_ua: return os_ua # Fallback return " ".join(get_python_os_info()) def get_systemd_os_info(filepath="/etc/os-release"): """ Parse systemd /etc/os-release for distribution information :param str filepath: File path of os-release file :returns: (os_name, os_version) :rtype: `tuple` of `str` """ os_name = get_var_from_file("ID", filepath=filepath) os_version = get_var_from_file("VERSION_ID", filepath=filepath) return (os_name, os_version) def get_systemd_os_like(filepath="/etc/os-release"): """ Get a list of strings that indicate the distribution likeness to other distributions. :param str filepath: File path of os-release file :returns: List of distribution acronyms :rtype: `list` of `str` """ return get_var_from_file("ID_LIKE", filepath).split(" ") def get_var_from_file(varname, filepath="/etc/os-release"): """ Get single value from systemd /etc/os-release :param str varname: Name of variable to fetch :param str filepath: File path of os-release file :returns: requested value :rtype: `str` """ var_string = varname+"=" if not os.path.isfile(filepath): return "" with open(filepath, 'r') as fh: contents = fh.readlines() for line in contents: if line.strip().startswith(var_string): # Return the value of var, normalized return _normalize_string(line.strip()[len(var_string):]) return "" def _normalize_string(orig): """ Helper function for get_var_from_file() to remove quotes and whitespaces """ return orig.replace('"', '').replace("'", "").strip() def get_python_os_info(): """ Get Operating System type/distribution and major version using python platform module :returns: (os_name, os_version) :rtype: `tuple` of `str` """ info = platform.system_alias( platform.system(), platform.release(), platform.version() ) os_type, os_ver, _ = info os_type = os_type.lower() if os_type.startswith('linux'): info = platform.linux_distribution() # On arch, platform.linux_distribution() is reportedly ('','',''), # so handle it defensively if info[0]: os_type = info[0] if info[1]: os_ver = info[1] elif os_type.startswith('darwin'): try: proc = subprocess.Popen( ["/usr/bin/sw_vers", "-productVersion"], stdout=subprocess.PIPE, universal_newlines=True, ) except OSError: proc = subprocess.Popen( ["sw_vers", "-productVersion"], stdout=subprocess.PIPE, universal_newlines=True, ) os_ver = proc.communicate()[0].rstrip('\n') elif os_type.startswith('freebsd'): # eg "9.3-RC3-p1" os_ver = os_ver.partition("-")[0] os_ver = os_ver.partition(".")[0] elif platform.win32_ver()[1]: os_ver = platform.win32_ver()[1] else: # Cases known to fall here: Cygwin python os_ver = '' return os_type, os_ver # Just make sure we don't get pwned... Make sure that it also doesn't # start with a period or have two consecutive periods <- this needs to # be done in addition to the regex EMAIL_REGEX = re.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+$") def safe_email(email): """Scrub email address before using it.""" if EMAIL_REGEX.match(email) is not None: return not email.startswith(".") and ".." not in email else: logger.warning("Invalid email address: %s.", email) return False class _ShowWarning(argparse.Action): """Action to log a warning when an argument is used.""" def __call__(self, unused1, unused2, unused3, option_string=None): sys.stderr.write( "Use of {0} is deprecated.\n".format(option_string)) def add_deprecated_argument(add_argument, argument_name, nargs): """Adds a deprecated argument with the name argument_name. Deprecated arguments are not shown in the help. If they are used on the command line, a warning is shown stating that the argument is deprecated and no other action is taken. :param callable add_argument: Function that adds arguments to an argument parser/group. :param str argument_name: Name of deprecated argument. :param nargs: Value for nargs when adding the argument to argparse. """ if _ShowWarning not in configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE: # In version 0.12.0 ACTION_TYPES_THAT_DONT_NEED_A_VALUE was # changed from a set to a tuple. if isinstance(configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE, set): # pylint: disable=no-member configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE.add( _ShowWarning) else: configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE += ( _ShowWarning,) add_argument(argument_name, action=_ShowWarning, help=argparse.SUPPRESS, nargs=nargs) def enforce_le_validity(domain): """Checks that Let's Encrypt will consider domain to be valid. :param str domain: FQDN to check :type domain: `str` or `unicode` :returns: The domain cast to `str`, with ASCII-only contents :rtype: str :raises ConfigurationError: for invalid domains and cases where Let's Encrypt currently will not issue certificates """ domain = enforce_domain_sanity(domain) if not re.match("^[A-Za-z0-9.-]*$", domain): raise errors.ConfigurationError( "{0} contains an invalid character. " "Valid characters are A-Z, a-z, 0-9, ., and -.".format(domain)) labels = domain.split(".") if len(labels) < 2: raise errors.ConfigurationError( "{0} needs at least two labels".format(domain)) for label in labels: if label.startswith("-"): raise errors.ConfigurationError( 'label "{0}" in domain "{1}" cannot start with "-"'.format( label, domain)) if label.endswith("-"): raise errors.ConfigurationError( 'label "{0}" in domain "{1}" cannot end with "-"'.format( label, domain)) return domain def enforce_domain_sanity(domain): """Method which validates domain value and errors out if the requirements are not met. :param domain: Domain to check :type domain: `str` or `unicode` :raises ConfigurationError: for invalid domains and cases where Let's Encrypt currently will not issue certificates :returns: The domain cast to `str`, with ASCII-only contents :rtype: str """ # Unicode try: if isinstance(domain, six.binary_type): domain = domain.decode('utf-8') domain.encode('ascii') except UnicodeError: raise errors.ConfigurationError("Non-ASCII domain names not supported. " "To issue for an Internationalized Domain Name, use Punycode.") domain = domain.lower() # Remove trailing dot domain = domain[:-1] if domain.endswith(u'.') else domain # Separately check for odd "domains" like "http://example.com" to fail # fast and provide a clear error message for scheme in ["http", "https"]: # Other schemes seem unlikely if domain.startswith("{0}://".format(scheme)): raise errors.ConfigurationError( "Requested name {0} appears to be a URL, not a FQDN. " "Try again without the leading \"{1}://\".".format( domain, scheme ) ) # Explain separately that IP addresses aren't allowed (apart from not # being FQDNs) because hope springs eternal concerning this point try: socket.inet_aton(domain) raise errors.ConfigurationError( "Requested name {0} is an IP address. The Let's Encrypt " "certificate authority will not issue certificates for a " "bare IP address.".format(domain)) except socket.error: # It wasn't an IP address, so that's good pass # FQDN checks according to RFC 2181: domain name should be less than 255 # octets (inclusive). And each label is 1 - 63 octets (inclusive). # https://tools.ietf.org/html/rfc2181#section-11 msg = "Requested domain {0} is not a FQDN because".format(domain) if len(domain) > 255: raise errors.ConfigurationError("{0} it is too long.".format(msg)) labels = domain.split('.') for l in labels: if not l: raise errors.ConfigurationError("{0} it contains an empty label.".format(msg)) elif len(l) > 63: raise errors.ConfigurationError("{0} label {1} is too long.".format(msg, l)) return domain def is_wildcard_domain(domain): """"Is domain a wildcard domain? :param domain: domain to check :type domain: `bytes` or `str` or `unicode` :returns: True if domain is a wildcard, otherwise, False :rtype: bool """ if isinstance(domain, six.text_type): wildcard_marker = u"*." else: wildcard_marker = b"*." return domain.startswith(wildcard_marker) def get_strict_version(normalized): """Converts a normalized version to a strict version. :param str normalized: normalized version string :returns: An equivalent strict version :rtype: distutils.version.StrictVersion """ # strict version ending with "a" and a number designates a pre-release # pylint: disable=no-member return distutils.version.StrictVersion(normalized.replace(".dev", "a")) def is_staging(srv): """ Determine whether a given ACME server is a known test / staging server. :param str srv: the URI for the ACME server :returns: True iff srv is a known test / staging server :rtype bool: """ return srv == constants.STAGING_URI or "staging" in srv def atexit_register(func, *args, **kwargs): """Sets func to be called before the program exits. Special care is taken to ensure func is only called when the process that first imports this module exits rather than any child processes. :param function func: function to be called in case of an error """ atexit.register(_atexit_call, func, *args, **kwargs) def _atexit_call(func, *args, **kwargs): if _INITIAL_PID == os.getpid(): func(*args, **kwargs) certbot-0.27.0/certbot/client.py0000644000175000017500000006751413344054434016745 0ustar ericaerica00000000000000"""Certbot client API.""" import datetime import logging import os import platform from cryptography.hazmat.backends import default_backend # https://github.com/python/typeshed/blob/master/third_party/ # 2/cryptography/hazmat/primitives/asymmetric/rsa.pyi from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key # type: ignore import josepy as jose import OpenSSL import zope.component from acme import client as acme_client from acme import crypto_util as acme_crypto_util from acme import errors as acme_errors from acme import messages from acme.magic_typing import Optional # pylint: disable=unused-import,no-name-in-module import certbot from certbot import account from certbot import auth_handler from certbot import cli from certbot import constants from certbot import crypto_util from certbot import eff from certbot import error_handler from certbot import errors from certbot import interfaces from certbot import reverter from certbot import storage from certbot import util from certbot.display import ops as display_ops from certbot.display import enhancements from certbot.plugins import selection as plugin_selection logger = logging.getLogger(__name__) def acme_from_config_key(config, key, regr=None): "Wrangle ACME client construction" # TODO: Allow for other alg types besides RS256 net = acme_client.ClientNetwork(key, account=regr, verify_ssl=(not config.no_verify_ssl), user_agent=determine_user_agent(config)) return acme_client.BackwardsCompatibleClientV2(net, key, config.server) def determine_user_agent(config): """ Set a user_agent string in the config based on the choice of plugins. (this wasn't knowable at construction time) :returns: the client's User-Agent string :rtype: `str` """ # WARNING: To ensure changes are in line with Certbot's privacy # policy, talk to a core Certbot team member before making any # changes here. if config.user_agent is None: ua = ("CertbotACMEClient/{0} ({1}; {2}{8}) Authenticator/{3} Installer/{4} " "({5}; flags: {6}) Py/{7}") if os.environ.get("CERTBOT_DOCS") == "1": cli_command = "certbot(-auto)" os_info = "OS_NAME OS_VERSION" python_version = "major.minor.patchlevel" else: cli_command = cli.cli_command os_info = util.get_os_info_ua() python_version = platform.python_version() ua = ua.format(certbot.__version__, cli_command, os_info, config.authenticator, config.installer, config.verb, ua_flags(config), python_version, "; " + config.user_agent_comment if config.user_agent_comment else "") else: ua = config.user_agent return ua def ua_flags(config): "Turn some very important CLI flags into clues in the user agent." if isinstance(config, DummyConfig): return "FLAGS" flags = [] if config.duplicate: flags.append("dup") if config.renew_by_default: flags.append("frn") if config.allow_subset_of_names: flags.append("asn") if config.noninteractive_mode: flags.append("n") hook_names = ("pre", "post", "renew", "manual_auth", "manual_cleanup") hooks = [getattr(config, h + "_hook") for h in hook_names] if any(hooks): flags.append("hook") return " ".join(flags) class DummyConfig(object): "Shim for computing a sample user agent." def __init__(self): self.authenticator = "XXX" self.installer = "YYY" self.user_agent = None self.verb = "SUBCOMMAND" def __getattr__(self, name): "Any config properties we might have are None." return None def sample_user_agent(): "Document what this Certbot's user agent string will be like." return determine_user_agent(DummyConfig()) def register(config, account_storage, tos_cb=None): """Register new account with an ACME CA. This function takes care of generating fresh private key, registering the account, optionally accepting CA Terms of Service and finally saving the account. It should be called prior to initialization of `Client`, unless account has already been created. :param .IConfig config: Client configuration. :param .AccountStorage account_storage: Account storage where newly registered account will be saved to. Save happens only after TOS acceptance step, so any account private keys or `.RegistrationResource` will not be persisted if `tos_cb` returns ``False``. :param tos_cb: If ACME CA requires the user to accept a Terms of Service before registering account, client action is necessary. For example, a CLI tool would prompt the user acceptance. `tos_cb` must be a callable that should accept `.RegistrationResource` and return a `bool`: ``True`` iff the Terms of Service present in the contained `.Registration.terms_of_service` is accepted by the client, and ``False`` otherwise. ``tos_cb`` will be called only if the client action is necessary, i.e. when ``terms_of_service is not None``. This argument is optional, if not supplied it will default to automatic acceptance! :raises certbot.errors.Error: In case of any client problems, in particular registration failure, or unaccepted Terms of Service. :raises acme.errors.Error: In case of any protocol problems. :returns: Newly registered and saved account, as well as protocol API handle (should be used in `Client` initialization). :rtype: `tuple` of `.Account` and `acme.client.Client` """ # Log non-standard actions, potentially wrong API calls if account_storage.find_all(): logger.info("There are already existing accounts for %s", config.server) if config.email is None: if not config.register_unsafely_without_email: msg = ("No email was provided and " "--register-unsafely-without-email was not present.") logger.warning(msg) raise errors.Error(msg) if not config.dry_run: logger.info("Registering without email!") # If --dry-run is used, and there is no staging account, create one with no email. if config.dry_run: config.email = None # Each new registration shall use a fresh new key rsa_key = generate_private_key( public_exponent=65537, key_size=config.rsa_key_size, backend=default_backend()) key = jose.JWKRSA(key=jose.ComparableRSAKey(rsa_key)) acme = acme_from_config_key(config, key) # TODO: add phone? regr = perform_registration(acme, config, tos_cb) acc = account.Account(regr, key) account.report_new_account(config) account_storage.save(acc, acme) eff.handle_subscription(config) return acc, acme def perform_registration(acme, config, tos_cb): """ Actually register new account, trying repeatedly if there are email problems :param acme.client.Client client: ACME client object. :param .IConfig config: Client configuration. :param Callable tos_cb: a callback to handle Term of Service agreement. :returns: Registration Resource. :rtype: `acme.messages.RegistrationResource` """ try: return acme.new_account_and_tos(messages.NewRegistration.from_data(email=config.email), tos_cb) except messages.Error as e: if e.code == "invalidEmail" or e.code == "invalidContact": if config.noninteractive_mode: msg = ("The ACME server believes %s is an invalid email address. " "Please ensure it is a valid email and attempt " "registration again." % config.email) raise errors.Error(msg) else: config.email = display_ops.get_email(invalid=True) return perform_registration(acme, config, tos_cb) else: raise class Client(object): """Certbot's client. :ivar .IConfig config: Client configuration. :ivar .Account account: Account registered with `register`. :ivar .AuthHandler auth_handler: Authorizations handler that will dispatch DV challenges to appropriate authenticators (providing `.IAuthenticator` interface). :ivar .IAuthenticator auth: Prepared (`.IAuthenticator.prepare`) authenticator that can solve ACME challenges. :ivar .IInstaller installer: Installer. :ivar acme.client.BackwardsCompatibleClientV2 acme: Optional ACME client API handle. You might already have one from `register`. """ def __init__(self, config, account_, auth, installer, acme=None): """Initialize a client.""" self.config = config self.account = account_ self.auth = auth self.installer = installer # Initialize ACME if account is provided if acme is None and self.account is not None: acme = acme_from_config_key(config, self.account.key, self.account.regr) self.acme = acme if auth is not None: self.auth_handler = auth_handler.AuthHandler( auth, self.acme, self.account, self.config.pref_challs) else: self.auth_handler = None def obtain_certificate_from_csr(self, csr, orderr=None): """Obtain certificate. :param .util.CSR csr: PEM-encoded Certificate Signing Request. The key used to generate this CSR can be different than `authkey`. :param acme.messages.OrderResource orderr: contains authzrs :returns: certificate and chain as PEM byte strings :rtype: tuple """ if self.auth_handler is None: msg = ("Unable to obtain certificate because authenticator is " "not set.") logger.warning(msg) raise errors.Error(msg) if self.account.regr is None: raise errors.Error("Please register with the ACME server first.") logger.debug("CSR: %s", csr) if orderr is None: orderr = self._get_order_and_authorizations(csr.data, best_effort=False) deadline = datetime.datetime.now() + datetime.timedelta(seconds=90) orderr = self.acme.finalize_order(orderr, deadline) cert, chain = crypto_util.cert_and_chain_from_fullchain(orderr.fullchain_pem) return cert.encode(), chain.encode() def obtain_certificate(self, domains, old_keypath=None): """Obtains a certificate from the ACME server. `.register` must be called before `.obtain_certificate` :param list domains: domains to get a certificate :returns: certificate as PEM string, chain as PEM string, newly generated private key (`.util.Key`), and DER-encoded Certificate Signing Request (`.util.CSR`). :rtype: tuple """ # We need to determine the key path, key PEM data, CSR path, # and CSR PEM data. For a dry run, the paths are None because # they aren't permanently saved to disk. For a lineage with # --reuse-key, the key path and PEM data are derived from an # existing file. if old_keypath is not None: # We've been asked to reuse a specific existing private key. # Therefore, we'll read it now and not generate a new one in # either case below. # # We read in bytes here because the type of `key.pem` # created below is also bytes. with open(old_keypath, "rb") as f: keypath = old_keypath keypem = f.read() key = util.Key(file=keypath, pem=keypem) # type: Optional[util.Key] logger.info("Reusing existing private key from %s.", old_keypath) else: # The key is set to None here but will be created below. key = None # Create CSR from names if self.config.dry_run: key = key or util.Key(file=None, pem=crypto_util.make_key(self.config.rsa_key_size)) csr = util.CSR(file=None, form="pem", data=acme_crypto_util.make_csr( key.pem, domains, self.config.must_staple)) else: key = key or crypto_util.init_save_key(self.config.rsa_key_size, self.config.key_dir) csr = crypto_util.init_save_csr(key, domains, self.config.csr_dir) orderr = self._get_order_and_authorizations(csr.data, self.config.allow_subset_of_names) authzr = orderr.authorizations auth_domains = set(a.body.identifier.value for a in authzr) successful_domains = [d for d in domains if d in auth_domains] # allow_subset_of_names is currently disabled for wildcard # certificates. The reason for this and checking allow_subset_of_names # below is because successful_domains == domains is never true if # domains contains a wildcard because the ACME spec forbids identifiers # in authzs from containing a wildcard character. if self.config.allow_subset_of_names and successful_domains != domains: if not self.config.dry_run: os.remove(key.file) os.remove(csr.file) return self.obtain_certificate(successful_domains) else: cert, chain = self.obtain_certificate_from_csr(csr, orderr) return cert, chain, key, csr def _get_order_and_authorizations(self, csr_pem, best_effort): """Request a new order and complete its authorizations. :param str csr_pem: A CSR in PEM format. :param bool best_effort: True if failing to complete all authorizations should not raise an exception :returns: order resource containing its completed authorizations :rtype: acme.messages.OrderResource """ try: orderr = self.acme.new_order(csr_pem) except acme_errors.WildcardUnsupportedError: raise errors.Error("The currently selected ACME CA endpoint does" " not support issuing wildcard certificates.") authzr = self.auth_handler.handle_authorizations(orderr, best_effort) return orderr.update(authorizations=authzr) # pylint: disable=no-member def obtain_and_enroll_certificate(self, domains, certname): """Obtain and enroll certificate. Get a new certificate for the specified domains using the specified authenticator and installer, and then create a new renewable lineage containing it. :param domains: domains to request a certificate for :type domains: `list` of `str` :param certname: requested name of lineage :type certname: `str` or `None` :returns: A new :class:`certbot.storage.RenewableCert` instance referred to the enrolled cert lineage, False if the cert could not be obtained, or None if doing a successful dry run. """ cert, chain, key, _ = self.obtain_certificate(domains) if (self.config.config_dir != constants.CLI_DEFAULTS["config_dir"] or self.config.work_dir != constants.CLI_DEFAULTS["work_dir"]): logger.info( "Non-standard path(s), might not work with crontab installed " "by your operating system package manager") new_name = self._choose_lineagename(domains, certname) if self.config.dry_run: logger.debug("Dry run: Skipping creating new lineage for %s", new_name) return None else: return storage.RenewableCert.new_lineage( new_name, cert, key.pem, chain, self.config) def _choose_lineagename(self, domains, certname): """Chooses a name for the new lineage. :param domains: domains in certificate request :type domains: `list` of `str` :param certname: requested name of lineage :type certname: `str` or `None` :returns: lineage name that should be used :rtype: str """ if certname: return certname elif util.is_wildcard_domain(domains[0]): # Don't make files and directories starting with *. return domains[0][2:] else: return domains[0] def save_certificate(self, cert_pem, chain_pem, cert_path, chain_path, fullchain_path): """Saves the certificate received from the ACME server. :param str cert_pem: :param str chain_pem: :param str cert_path: Candidate path to a certificate. :param str chain_path: Candidate path to a certificate chain. :param str fullchain_path: Candidate path to a full cert chain. :returns: cert_path, chain_path, and fullchain_path as absolute paths to the actual files :rtype: `tuple` of `str` :raises IOError: If unable to find room to write the cert files """ for path in cert_path, chain_path, fullchain_path: util.make_or_verify_dir( os.path.dirname(path), 0o755, os.geteuid(), self.config.strict_permissions) cert_file, abs_cert_path = _open_pem_file('cert_path', cert_path) try: cert_file.write(cert_pem) finally: cert_file.close() logger.info("Server issued certificate; certificate written to %s", abs_cert_path) chain_file, abs_chain_path =\ _open_pem_file('chain_path', chain_path) fullchain_file, abs_fullchain_path =\ _open_pem_file('fullchain_path', fullchain_path) _save_chain(chain_pem, chain_file) _save_chain(cert_pem + chain_pem, fullchain_file) return abs_cert_path, abs_chain_path, abs_fullchain_path def deploy_certificate(self, domains, privkey_path, cert_path, chain_path, fullchain_path): """Install certificate :param list domains: list of domains to install the certificate :param str privkey_path: path to certificate private key :param str cert_path: certificate file path (optional) :param str chain_path: chain file path """ if self.installer is None: logger.warning("No installer specified, client is unable to deploy" "the certificate") raise errors.Error("No installer available") chain_path = None if chain_path is None else os.path.abspath(chain_path) msg = ("Unable to install the certificate") with error_handler.ErrorHandler(self._recovery_routine_with_msg, msg): for dom in domains: self.installer.deploy_cert( domain=dom, cert_path=os.path.abspath(cert_path), key_path=os.path.abspath(privkey_path), chain_path=chain_path, fullchain_path=fullchain_path) self.installer.save() # needed by the Apache plugin self.installer.save("Deployed ACME Certificate") msg = ("We were unable to install your certificate, " "however, we successfully restored your " "server to its prior configuration.") with error_handler.ErrorHandler(self._rollback_and_restart, msg): # sites may have been enabled / final cleanup self.installer.restart() def enhance_config(self, domains, chain_path, ask_redirect=True): """Enhance the configuration. :param list domains: list of domains to configure :param chain_path: chain file path :type chain_path: `str` or `None` :raises .errors.Error: if no installer is specified in the client. """ if self.installer is None: logger.warning("No installer is specified, there isn't any " "configuration to enhance.") raise errors.Error("No installer available") enhanced = False enhancement_info = ( ("hsts", "ensure-http-header", "Strict-Transport-Security"), ("redirect", "redirect", None), ("staple", "staple-ocsp", chain_path), ("uir", "ensure-http-header", "Upgrade-Insecure-Requests"),) supported = self.installer.supported_enhancements() for config_name, enhancement_name, option in enhancement_info: config_value = getattr(self.config, config_name) if enhancement_name in supported: if ask_redirect: if config_name == "redirect" and config_value is None: config_value = enhancements.ask(enhancement_name) if config_value: self.apply_enhancement(domains, enhancement_name, option) enhanced = True elif config_value: logger.warning( "Option %s is not supported by the selected installer. " "Skipping enhancement.", config_name) msg = ("We were unable to restart web server") if enhanced: with error_handler.ErrorHandler(self._rollback_and_restart, msg): self.installer.restart() def apply_enhancement(self, domains, enhancement, options=None): """Applies an enhancement on all domains. :param list domains: list of ssl_vhosts (as strings) :param str enhancement: name of enhancement, e.g. ensure-http-header :param str options: options to enhancement, e.g. Strict-Transport-Security .. note:: When more `options` are needed, make options a list. :raises .errors.PluginError: If Enhancement is not supported, or if there is any other problem with the enhancement. """ msg = ("We were unable to set up enhancement %s for your server, " "however, we successfully installed your certificate." % (enhancement)) with error_handler.ErrorHandler(self._recovery_routine_with_msg, msg): for dom in domains: try: self.installer.enhance(dom, enhancement, options) except errors.PluginEnhancementAlreadyPresent: if enhancement == "ensure-http-header": logger.warning("Enhancement %s was already set.", options) else: logger.warning("Enhancement %s was already set.", enhancement) except errors.PluginError: logger.warning("Unable to set enhancement %s for %s", enhancement, dom) raise self.installer.save("Add enhancement %s" % (enhancement)) def _recovery_routine_with_msg(self, success_msg): """Calls the installer's recovery routine and prints success_msg :param str success_msg: message to show on successful recovery """ self.installer.recovery_routine() reporter = zope.component.getUtility(interfaces.IReporter) reporter.add_message(success_msg, reporter.HIGH_PRIORITY) def _rollback_and_restart(self, success_msg): """Rollback the most recent checkpoint and restart the webserver :param str success_msg: message to show on successful rollback """ logger.critical("Rolling back to previous server configuration...") reporter = zope.component.getUtility(interfaces.IReporter) try: self.installer.rollback_checkpoints() self.installer.restart() except: reporter.add_message( "An error occurred and we failed to restore your config and " "restart your server. Please post to " "https://community.letsencrypt.org/c/server-config " "with details about your configuration and this error you received.", reporter.HIGH_PRIORITY) raise reporter.add_message(success_msg, reporter.HIGH_PRIORITY) def validate_key_csr(privkey, csr=None): """Validate Key and CSR files. Verifies that the client key and csr arguments are valid and correspond to one another. This does not currently check the names in the CSR due to the inability to read SANs from CSRs in python crypto libraries. If csr is left as None, only the key will be validated. :param privkey: Key associated with CSR :type privkey: :class:`certbot.util.Key` :param .util.CSR csr: CSR :raises .errors.Error: when validation fails """ # TODO: Handle all of these problems appropriately # The client can eventually do things like prompt the user # and allow the user to take more appropriate actions # Key must be readable and valid. if privkey.pem and not crypto_util.valid_privkey(privkey.pem): raise errors.Error("The provided key is not a valid key") if csr: if csr.form == "der": csr_obj = OpenSSL.crypto.load_certificate_request( OpenSSL.crypto.FILETYPE_ASN1, csr.data) cert_buffer = OpenSSL.crypto.dump_certificate_request( OpenSSL.crypto.FILETYPE_PEM, csr_obj ) csr = util.CSR(csr.file, cert_buffer, "pem") # If CSR is provided, it must be readable and valid. if csr.data and not crypto_util.valid_csr(csr.data): raise errors.Error("The provided CSR is not a valid CSR") # If both CSR and key are provided, the key must be the same key used # in the CSR. if csr.data and privkey.pem: if not crypto_util.csr_matches_pubkey( csr.data, privkey.pem): raise errors.Error("The key and CSR do not match") def rollback(default_installer, checkpoints, config, plugins): """Revert configuration the specified number of checkpoints. :param int checkpoints: Number of checkpoints to revert. :param config: Configuration. :type config: :class:`certbot.interfaces.IConfig` """ # Misconfigurations are only a slight problems... allow the user to rollback installer = plugin_selection.pick_installer( config, default_installer, plugins, question="Which installer " "should be used for rollback?") # No Errors occurred during init... proceed normally # If installer is None... couldn't find an installer... there shouldn't be # anything to rollback if installer is not None: installer.rollback_checkpoints(checkpoints) installer.restart() def view_config_changes(config, num=None): """View checkpoints and associated configuration changes. .. note:: This assumes that the installation is using a Reverter object. :param config: Configuration. :type config: :class:`certbot.interfaces.IConfig` """ rev = reverter.Reverter(config) rev.recovery_routine() rev.view_config_changes(num) def _open_pem_file(cli_arg_path, pem_path): """Open a pem file. If cli_arg_path was set by the client, open that. Otherwise, uniquify the file path. :param str cli_arg_path: the cli arg name, e.g. cert_path :param str pem_path: the pem file path to open :returns: a tuple of file object and its absolute file path """ if cli.set_by_cli(cli_arg_path): return util.safe_open(pem_path, chmod=0o644, mode="wb"),\ os.path.abspath(pem_path) else: uniq = util.unique_file(pem_path, 0o644, "wb") return uniq[0], os.path.abspath(uniq[1]) def _save_chain(chain_pem, chain_file): """Saves chain_pem at a unique path based on chain_path. :param str chain_pem: certificate chain in PEM format :param str chain_file: chain file object """ try: chain_file.write(chain_pem) finally: chain_file.close() logger.info("Cert chain written to %s", chain_file.name) certbot-0.27.0/certbot/storage.py0000644000175000017500000013257013344054434017126 0ustar ericaerica00000000000000"""Renewable certificates storage.""" import datetime import glob import logging import os import re import stat import configobj import parsedatetime import pytz import shutil import six import certbot from certbot import cli from certbot import constants from certbot import crypto_util from certbot import errors from certbot import error_handler from certbot import util from certbot.plugins import common as plugins_common from certbot.plugins import disco as plugins_disco logger = logging.getLogger(__name__) ALL_FOUR = ("cert", "privkey", "chain", "fullchain") README = "README" CURRENT_VERSION = util.get_strict_version(certbot.__version__) def renewal_conf_files(config): """Build a list of all renewal configuration files. :param certbot.interfaces.IConfig config: Configuration object :returns: list of renewal configuration files :rtype: `list` of `str` """ return glob.glob(os.path.join(config.renewal_configs_dir, "*.conf")) def renewal_file_for_certname(config, certname): """Return /path/to/certname.conf in the renewal conf directory""" path = os.path.join(config.renewal_configs_dir, "{0}.conf".format(certname)) if not os.path.exists(path): raise errors.CertStorageError("No certificate found with name {0} (expected " "{1}).".format(certname, path)) return path def cert_path_for_cert_name(config, cert_name): """ If `--cert-name` was specified, but you need a value for `--cert-path`. :param `configuration.NamespaceConfig` config: parsed command line arguments :param str cert_name: cert name. """ cert_name_implied_conf = renewal_file_for_certname(config, cert_name) fullchain_path = configobj.ConfigObj(cert_name_implied_conf)["fullchain"] with open(fullchain_path) as f: cert_path = (fullchain_path, f.read()) return cert_path def config_with_defaults(config=None): """Merge supplied config, if provided, on top of builtin defaults.""" defaults_copy = configobj.ConfigObj(constants.RENEWER_DEFAULTS) defaults_copy.merge(config if config is not None else configobj.ConfigObj()) return defaults_copy def add_time_interval(base_time, interval, textparser=parsedatetime.Calendar()): """Parse the time specified time interval, and add it to the base_time The interval can be in the English-language format understood by parsedatetime, e.g., '10 days', '3 weeks', '6 months', '9 hours', or a sequence of such intervals like '6 months 1 week' or '3 days 12 hours'. If an integer is found with no associated unit, it is interpreted by default as a number of days. :param datetime.datetime base_time: The time to be added with the interval. :param str interval: The time interval to parse. :returns: The base_time plus the interpretation of the time interval. :rtype: :class:`datetime.datetime`""" if interval.strip().isdigit(): interval += " days" # try to use the same timezone, but fallback to UTC tzinfo = base_time.tzinfo or pytz.UTC return textparser.parseDT(interval, base_time, tzinfo=tzinfo)[0] def write_renewal_config(o_filename, n_filename, archive_dir, target, relevant_data): """Writes a renewal config file with the specified name and values. :param str o_filename: Absolute path to the previous version of config file :param str n_filename: Absolute path to the new destination of config file :param str archive_dir: Absolute path to the archive directory :param dict target: Maps ALL_FOUR to their symlink paths :param dict relevant_data: Renewal configuration options to save :returns: Configuration object for the new config file :rtype: configobj.ConfigObj """ config = configobj.ConfigObj(o_filename) config["version"] = certbot.__version__ config["archive_dir"] = archive_dir for kind in ALL_FOUR: config[kind] = target[kind] if "renewalparams" not in config: config["renewalparams"] = {} config.comments["renewalparams"] = ["", "Options used in " "the renewal process"] config["renewalparams"].update(relevant_data) for k in config["renewalparams"].keys(): if k not in relevant_data: del config["renewalparams"][k] if "renew_before_expiry" not in config: default_interval = constants.RENEWER_DEFAULTS["renew_before_expiry"] config.initial_comment = ["renew_before_expiry = " + default_interval] # TODO: add human-readable comments explaining other available # parameters logger.debug("Writing new config %s.", n_filename) # Ensure that the file exists open(n_filename, 'a').close() # Copy permissions from the old version of the file, if it exists. if os.path.exists(o_filename): current_permissions = stat.S_IMODE(os.lstat(o_filename).st_mode) os.chmod(n_filename, current_permissions) with open(n_filename, "wb") as f: config.write(outfile=f) return config def rename_renewal_config(prev_name, new_name, cli_config): """Renames cli_config.certname's config to cli_config.new_certname. :param .NamespaceConfig cli_config: parsed command line arguments """ prev_filename = renewal_filename_for_lineagename(cli_config, prev_name) new_filename = renewal_filename_for_lineagename(cli_config, new_name) if os.path.exists(new_filename): raise errors.ConfigurationError("The new certificate name " "is already in use.") try: os.rename(prev_filename, new_filename) except OSError: raise errors.ConfigurationError("Please specify a valid filename " "for the new certificate name.") def update_configuration(lineagename, archive_dir, target, cli_config): """Modifies lineagename's config to contain the specified values. :param str lineagename: Name of the lineage being modified :param str archive_dir: Absolute path to the archive directory :param dict target: Maps ALL_FOUR to their symlink paths :param .NamespaceConfig cli_config: parsed command line arguments :returns: Configuration object for the updated config file :rtype: configobj.ConfigObj """ config_filename = renewal_filename_for_lineagename(cli_config, lineagename) temp_filename = config_filename + ".new" # If an existing tempfile exists, delete it if os.path.exists(temp_filename): os.unlink(temp_filename) # Save only the config items that are relevant to renewal values = relevant_values(vars(cli_config.namespace)) write_renewal_config(config_filename, temp_filename, archive_dir, target, values) os.rename(temp_filename, config_filename) return configobj.ConfigObj(config_filename) def get_link_target(link): """Get an absolute path to the target of link. :param str link: Path to a symbolic link :returns: Absolute path to the target of link :rtype: str :raises .CertStorageError: If link does not exists. """ try: target = os.readlink(link) except OSError: raise errors.CertStorageError( "Expected {0} to be a symlink".format(link)) if not os.path.isabs(target): target = os.path.join(os.path.dirname(link), target) return os.path.abspath(target) def _relevant(option): """ Is this option one that could be restored for future renewal purposes? :param str option: the name of the option :rtype: bool """ from certbot import renewal plugins = plugins_disco.PluginsRegistry.find_all() namespaces = [plugins_common.dest_namespace(plugin) for plugin in plugins] return (option in renewal.CONFIG_ITEMS or any(option.startswith(namespace) for namespace in namespaces)) def relevant_values(all_values): """Return a new dict containing only items relevant for renewal. :param dict all_values: The original values. :returns: A new dictionary containing items that can be used in renewal. :rtype dict: """ rv = dict( (option, value) for option, value in six.iteritems(all_values) if _relevant(option) and cli.option_was_set(option, value)) # We always save the server value to help with forward compatibility # and behavioral consistency when versions of Certbot with different # server defaults are used. rv["server"] = all_values["server"] return rv def lineagename_for_filename(config_filename): """Returns the lineagename for a configuration filename. """ if not config_filename.endswith(".conf"): raise errors.CertStorageError( "renewal config file name must end in .conf") return os.path.basename(config_filename[:-len(".conf")]) def renewal_filename_for_lineagename(config, lineagename): """Returns the lineagename for a configuration filename. """ return os.path.join(config.renewal_configs_dir, lineagename) + ".conf" def _relpath_from_file(archive_dir, from_file): """Path to a directory from a file""" return os.path.relpath(archive_dir, os.path.dirname(from_file)) def full_archive_path(config_obj, cli_config, lineagename): """Returns the full archive path for a lineagename Uses cli_config to determine archive path if not available from config_obj. :param configobj.ConfigObj config_obj: Renewal conf file contents (can be None) :param configuration.NamespaceConfig cli_config: Main config file :param str lineagename: Certificate name """ if config_obj and "archive_dir" in config_obj: return config_obj["archive_dir"] else: return os.path.join(cli_config.default_archive_dir, lineagename) def _full_live_path(cli_config, lineagename): """Returns the full default live path for a lineagename""" return os.path.join(cli_config.live_dir, lineagename) def delete_files(config, certname): """Delete all files related to the certificate. If some files are not found, ignore them and continue. """ renewal_filename = renewal_file_for_certname(config, certname) # file exists full_default_archive_dir = full_archive_path(None, config, certname) full_default_live_dir = _full_live_path(config, certname) try: renewal_config = configobj.ConfigObj(renewal_filename) except configobj.ConfigObjError: # config is corrupted logger.warning("Could not parse %s. You may wish to manually " "delete the contents of %s and %s.", renewal_filename, full_default_live_dir, full_default_archive_dir) raise errors.CertStorageError( "error parsing {0}".format(renewal_filename)) finally: # we couldn't read it, but let's at least delete it # if this was going to fail, it already would have. os.remove(renewal_filename) logger.debug("Removed %s", renewal_filename) # cert files and (hopefully) live directory # it's not guaranteed that the files are in our default storage # structure. so, first delete the cert files. directory_names = set() for kind in ALL_FOUR: link = renewal_config.get(kind) try: os.remove(link) logger.debug("Removed %s", link) except OSError: logger.debug("Unable to delete %s", link) directory = os.path.dirname(link) directory_names.add(directory) # if all four were in the same directory, and the only thing left # is the README file (or nothing), delete that directory. # this will be wrong in very few but some cases. if len(directory_names) == 1: # delete the README file directory = directory_names.pop() readme_path = os.path.join(directory, README) try: os.remove(readme_path) logger.debug("Removed %s", readme_path) except OSError: logger.debug("Unable to delete %s", readme_path) # if it's now empty, delete the directory try: os.rmdir(directory) # only removes empty directories logger.debug("Removed %s", directory) except OSError: logger.debug("Unable to remove %s; may not be empty.", directory) # archive directory try: archive_path = full_archive_path(renewal_config, config, certname) shutil.rmtree(archive_path) logger.debug("Removed %s", archive_path) except OSError: logger.debug("Unable to remove %s", archive_path) class RenewableCert(object): # pylint: disable=too-many-instance-attributes,too-many-public-methods """Renewable certificate. Represents a lineage of certificates that is under the management of Certbot, indicated by the existence of an associated renewal configuration file. Note that the notion of "current version" for a lineage is maintained on disk in the structure of symbolic links, and is not explicitly stored in any instance variable in this object. The RenewableCert object is able to determine information about the current (or other) version by accessing data on disk, but does not inherently know any of this information except by examining the symbolic links as needed. The instance variables mentioned below point to symlinks that reflect the notion of "current version" of each managed object, and it is these paths that should be used when configuring servers to use the certificate managed in a lineage. These paths are normally within the "live" directory, and their symlink targets -- the actual cert files -- are normally found within the "archive" directory. :ivar str cert: The path to the symlink representing the current version of the certificate managed by this lineage. :ivar str privkey: The path to the symlink representing the current version of the private key managed by this lineage. :ivar str chain: The path to the symlink representing the current version of the chain managed by this lineage. :ivar str fullchain: The path to the symlink representing the current version of the fullchain (combined chain and cert) managed by this lineage. :ivar configobj.ConfigObj configuration: The renewal configuration options associated with this lineage, obtained from parsing the renewal configuration file and/or systemwide defaults. """ def __init__(self, config_filename, cli_config, update_symlinks=False): """Instantiate a RenewableCert object from an existing lineage. :param str config_filename: the path to the renewal config file that defines this lineage. :param .NamespaceConfig: parsed command line arguments :raises .CertStorageError: if the configuration file's name didn't end in ".conf", or the file is missing or broken. """ self.cli_config = cli_config self.lineagename = lineagename_for_filename(config_filename) # self.configuration should be used to read parameters that # may have been chosen based on default values from the # systemwide renewal configuration; self.configfile should be # used to make and save changes. try: self.configfile = configobj.ConfigObj(config_filename) except configobj.ConfigObjError: raise errors.CertStorageError( "error parsing {0}".format(config_filename)) # TODO: Do we actually use anything from defaults and do we want to # read further defaults from the systemwide renewal configuration # file at this stage? self.configuration = config_with_defaults(self.configfile) if not all(x in self.configuration for x in ALL_FOUR): raise errors.CertStorageError( "renewal config file {0} is missing a required " "file reference".format(self.configfile)) conf_version = self.configuration.get("version") if (conf_version is not None and util.get_strict_version(conf_version) > CURRENT_VERSION): logger.info( "Attempting to parse the version %s renewal configuration " "file found at %s with version %s of Certbot. This might not " "work.", conf_version, config_filename, certbot.__version__) self.cert = self.configuration["cert"] self.privkey = self.configuration["privkey"] self.chain = self.configuration["chain"] self.fullchain = self.configuration["fullchain"] self.live_dir = os.path.dirname(self.cert) self._fix_symlinks() if update_symlinks: self._update_symlinks() self._check_symlinks() @property def key_path(self): """Duck type for self.privkey""" return self.privkey @property def cert_path(self): """Duck type for self.cert""" return self.cert @property def chain_path(self): """Duck type for self.chain""" return self.chain @property def fullchain_path(self): """Duck type for self.fullchain""" return self.fullchain @property def target_expiry(self): """The current target certificate's expiration datetime :returns: Expiration datetime of the current target certificate :rtype: :class:`datetime.datetime` """ return crypto_util.notAfter(self.current_target("cert")) @property def archive_dir(self): """Returns the default or specified archive directory""" return full_archive_path(self.configuration, self.cli_config, self.lineagename) def relative_archive_dir(self, from_file): """Returns the default or specified archive directory as a relative path Used for creating symbolic links. """ return _relpath_from_file(self.archive_dir, from_file) @property def is_test_cert(self): """Returns true if this is a test cert from a staging server.""" server = self.configuration["renewalparams"].get("server", None) if server: return util.is_staging(server) else: return False def _check_symlinks(self): """Raises an exception if a symlink doesn't exist""" for kind in ALL_FOUR: link = getattr(self, kind) if not os.path.islink(link): raise errors.CertStorageError( "expected {0} to be a symlink".format(link)) target = get_link_target(link) if not os.path.exists(target): raise errors.CertStorageError("target {0} of symlink {1} does " "not exist".format(target, link)) def _update_symlinks(self): """Updates symlinks to use archive_dir""" for kind in ALL_FOUR: link = getattr(self, kind) previous_link = get_link_target(link) new_link = os.path.join(self.relative_archive_dir(link), os.path.basename(previous_link)) os.unlink(link) os.symlink(new_link, link) def _consistent(self): """Are the files associated with this lineage self-consistent? :returns: Whether the files stored in connection with this lineage appear to be correct and consistent with one another. :rtype: bool """ # Each element must be referenced with an absolute path for x in (self.cert, self.privkey, self.chain, self.fullchain): if not os.path.isabs(x): logger.debug("Element %s is not referenced with an " "absolute path.", x) return False # Each element must exist and be a symbolic link for x in (self.cert, self.privkey, self.chain, self.fullchain): if not os.path.islink(x): logger.debug("Element %s is not a symbolic link.", x) return False for kind in ALL_FOUR: link = getattr(self, kind) target = get_link_target(link) # Each element's link must point within the cert lineage's # directory within the official archive directory if not os.path.samefile(os.path.dirname(target), self.archive_dir): logger.debug("Element's link does not point within the " "cert lineage's directory within the " "official archive directory. Link: %s, " "target directory: %s, " "archive directory: %s. If you've specified " "the archive directory in the renewal configuration " "file, you may need to update links by running " "certbot update_symlinks.", link, os.path.dirname(target), self.archive_dir) return False # The link must point to a file that exists if not os.path.exists(target): logger.debug("Link %s points to file %s that does not exist.", link, target) return False # The link must point to a file that follows the archive # naming convention pattern = re.compile(r"^{0}([0-9]+)\.pem$".format(kind)) if not pattern.match(os.path.basename(target)): logger.debug("%s does not follow the archive naming " "convention.", target) return False # It is NOT required that the link's target be a regular # file (it may itself be a symlink). But we should probably # do a recursive check that ultimately the target does # exist? # XXX: Additional possible consistency checks (e.g. # cryptographic validation of the chain being a chain, # the chain matching the cert, and the cert matching # the subject key) # XXX: All four of the targets are in the same directory # (This check is redundant with the check that they # are all in the desired directory!) # len(set(os.path.basename(self.current_target(x) # for x in ALL_FOUR))) == 1 return True def _fix(self): """Attempt to fix defects or inconsistencies in this lineage. .. todo:: Currently unimplemented. """ # TODO: Figure out what kinds of fixes are possible. For # example, checking if there is a valid version that # we can update the symlinks to. (Maybe involve # parsing keys and certs to see if they exist and # if a key corresponds to the subject key of a cert?) # TODO: In general, the symlink-reading functions below are not # cautious enough about the possibility that links or their # targets may not exist. (This shouldn't happen, but might # happen as a result of random tampering by a sysadmin, or # filesystem errors, or crashes.) def _previous_symlinks(self): """Returns the kind and path of all symlinks used in recovery. :returns: list of (kind, symlink) tuples :rtype: list """ previous_symlinks = [] for kind in ALL_FOUR: link_dir = os.path.dirname(getattr(self, kind)) link_base = "previous_{0}.pem".format(kind) previous_symlinks.append((kind, os.path.join(link_dir, link_base))) return previous_symlinks def _fix_symlinks(self): """Fixes symlinks in the event of an incomplete version update. If there is no problem with the current symlinks, this function has no effect. """ previous_symlinks = self._previous_symlinks() if all(os.path.exists(link[1]) for link in previous_symlinks): for kind, previous_link in previous_symlinks: current_link = getattr(self, kind) if os.path.lexists(current_link): os.unlink(current_link) os.symlink(os.readlink(previous_link), current_link) for _, link in previous_symlinks: if os.path.exists(link): os.unlink(link) def current_target(self, kind): """Returns full path to which the specified item currently points. :param str kind: the lineage member item ("cert", "privkey", "chain", or "fullchain") :returns: The path to the current version of the specified member. :rtype: str or None """ if kind not in ALL_FOUR: raise errors.CertStorageError("unknown kind of item") link = getattr(self, kind) if not os.path.exists(link): logger.debug("Expected symlink %s for %s does not exist.", link, kind) return None return get_link_target(link) def current_version(self, kind): """Returns numerical version of the specified item. For example, if kind is "chain" and the current chain link points to a file named "chain7.pem", returns the integer 7. :param str kind: the lineage member item ("cert", "privkey", "chain", or "fullchain") :returns: the current version of the specified member. :rtype: int """ if kind not in ALL_FOUR: raise errors.CertStorageError("unknown kind of item") pattern = re.compile(r"^{0}([0-9]+)\.pem$".format(kind)) target = self.current_target(kind) if target is None or not os.path.exists(target): logger.debug("Current-version target for %s " "does not exist at %s.", kind, target) target = "" matches = pattern.match(os.path.basename(target)) if matches: return int(matches.groups()[0]) else: logger.debug("No matches for target %s.", kind) return None def version(self, kind, version): """The filename that corresponds to the specified version and kind. .. warning:: The specified version may not exist in this lineage. There is no guarantee that the file path returned by this method actually exists. :param str kind: the lineage member item ("cert", "privkey", "chain", or "fullchain") :param int version: the desired version :returns: The path to the specified version of the specified member. :rtype: str """ if kind not in ALL_FOUR: raise errors.CertStorageError("unknown kind of item") where = os.path.dirname(self.current_target(kind)) return os.path.join(where, "{0}{1}.pem".format(kind, version)) def available_versions(self, kind): """Which alternative versions of the specified kind of item exist? The archive directory where the current version is stored is consulted to obtain the list of alternatives. :param str kind: the lineage member item ( ``cert``, ``privkey``, ``chain``, or ``fullchain``) :returns: all of the version numbers that currently exist :rtype: `list` of `int` """ if kind not in ALL_FOUR: raise errors.CertStorageError("unknown kind of item") where = os.path.dirname(self.current_target(kind)) files = os.listdir(where) pattern = re.compile(r"^{0}([0-9]+)\.pem$".format(kind)) matches = [pattern.match(f) for f in files] return sorted([int(m.groups()[0]) for m in matches if m]) def newest_available_version(self, kind): """Newest available version of the specified kind of item? :param str kind: the lineage member item (``cert``, ``privkey``, ``chain``, or ``fullchain``) :returns: the newest available version of this member :rtype: int """ return max(self.available_versions(kind)) def latest_common_version(self): """Newest version for which all items are available? :returns: the newest available version for which all members (``cert, ``privkey``, ``chain``, and ``fullchain``) exist :rtype: int """ # TODO: this can raise CertStorageError if there is no version overlap # (it should probably return None instead) # TODO: this can raise a spurious AttributeError if the current # link for any kind is missing (it should probably return None) versions = [self.available_versions(x) for x in ALL_FOUR] return max(n for n in versions[0] if all(n in v for v in versions[1:])) def next_free_version(self): """Smallest version newer than all full or partial versions? :returns: the smallest version number that is larger than any version of any item currently stored in this lineage :rtype: int """ # TODO: consider locking/mutual exclusion between updating processes # This isn't self.latest_common_version() + 1 because we don't want # collide with a version that might exist for one file type but not # for the others. return max(self.newest_available_version(x) for x in ALL_FOUR) + 1 def ensure_deployed(self): """Make sure we've deployed the latest version. :returns: False if a change was needed, True otherwise :rtype: bool May need to recover from rare interrupted / crashed states.""" if self.has_pending_deployment(): logger.warn("Found a new cert /archive/ that was not linked to in /live/; " "fixing...") self.update_all_links_to(self.latest_common_version()) return False return True def has_pending_deployment(self): """Is there a later version of all of the managed items? :returns: ``True`` if there is a complete version of this lineage with a larger version number than the current version, and ``False`` otherwise :rtype: bool """ # TODO: consider whether to assume consistency or treat # inconsistent/consistent versions differently smallest_current = min(self.current_version(x) for x in ALL_FOUR) return smallest_current < self.latest_common_version() def _update_link_to(self, kind, version): """Make the specified item point at the specified version. (Note that this method doesn't verify that the specified version exists.) :param str kind: the lineage member item ("cert", "privkey", "chain", or "fullchain") :param int version: the desired version """ if kind not in ALL_FOUR: raise errors.CertStorageError("unknown kind of item") link = getattr(self, kind) filename = "{0}{1}.pem".format(kind, version) # Relative rather than absolute target directory target_directory = os.path.dirname(os.readlink(link)) # TODO: it could be safer to make the link first under a temporary # filename, then unlink the old link, then rename the new link # to the old link; this ensures that this process is able to # create symlinks. # TODO: we might also want to check consistency of related links # for the other corresponding items os.unlink(link) os.symlink(os.path.join(target_directory, filename), link) def update_all_links_to(self, version): """Change all member objects to point to the specified version. :param int version: the desired version """ with error_handler.ErrorHandler(self._fix_symlinks): previous_links = self._previous_symlinks() for kind, link in previous_links: os.symlink(self.current_target(kind), link) for kind in ALL_FOUR: self._update_link_to(kind, version) for _, link in previous_links: os.unlink(link) def names(self, version=None): """What are the subject names of this certificate? (If no version is specified, use the current version.) :param int version: the desired version number :returns: the subject names :rtype: `list` of `str` :raises .CertStorageError: if could not find cert file. """ if version is None: target = self.current_target("cert") else: target = self.version("cert", version) if target is None: raise errors.CertStorageError("could not find cert file") with open(target) as f: return crypto_util.get_names_from_cert(f.read()) def autodeployment_is_enabled(self): """Is automatic deployment enabled for this cert? If autodeploy is not specified, defaults to True. :returns: True if automatic deployment is enabled :rtype: bool """ return ("autodeploy" not in self.configuration or self.configuration.as_bool("autodeploy")) def should_autodeploy(self, interactive=False): """Should this lineage now automatically deploy a newer version? This is a policy question and does not only depend on whether there is a newer version of the cert. (This considers whether autodeployment is enabled, whether a relevant newer version exists, and whether the time interval for autodeployment has been reached.) :param bool interactive: set to True to examine the question regardless of whether the renewal configuration allows automated deployment (for interactive use). Default False. :returns: whether the lineage now ought to autodeploy an existing newer cert version :rtype: bool """ if interactive or self.autodeployment_is_enabled(): if self.has_pending_deployment(): interval = self.configuration.get("deploy_before_expiry", "5 days") now = pytz.UTC.fromutc(datetime.datetime.utcnow()) if self.target_expiry < add_time_interval(now, interval): return True return False def ocsp_revoked(self, version=None): # pylint: disable=no-self-use,unused-argument """Is the specified cert version revoked according to OCSP? Also returns True if the cert version is declared as intended to be revoked according to Let's Encrypt OCSP extensions. (If no version is specified, uses the current version.) This method is not yet implemented and currently always returns False. :param int version: the desired version number :returns: whether the certificate is or will be revoked :rtype: bool """ # XXX: This query and its associated network service aren't # implemented yet, so we currently return False (indicating that the # certificate is not revoked). return False def autorenewal_is_enabled(self): """Is automatic renewal enabled for this cert? If autorenew is not specified, defaults to True. :returns: True if automatic renewal is enabled :rtype: bool """ return ("autorenew" not in self.configuration["renewalparams"] or self.configuration["renewalparams"].as_bool("autorenew")) def should_autorenew(self): """Should we now try to autorenew the most recent cert version? This is a policy question and does not only depend on whether the cert is expired. (This considers whether autorenewal is enabled, whether the cert is revoked, and whether the time interval for autorenewal has been reached.) Note that this examines the numerically most recent cert version, not the currently deployed version. :returns: whether an attempt should now be made to autorenew the most current cert version in this lineage :rtype: bool """ if self.autorenewal_is_enabled(): # Consider whether to attempt to autorenew this cert now # Renewals on the basis of revocation if self.ocsp_revoked(self.latest_common_version()): logger.debug("Should renew, certificate is revoked.") return True # Renews some period before expiry time default_interval = constants.RENEWER_DEFAULTS["renew_before_expiry"] interval = self.configuration.get("renew_before_expiry", default_interval) expiry = crypto_util.notAfter(self.version( "cert", self.latest_common_version())) now = pytz.UTC.fromutc(datetime.datetime.utcnow()) if expiry < add_time_interval(now, interval): logger.debug("Should renew, less than %s before certificate " "expiry %s.", interval, expiry.strftime("%Y-%m-%d %H:%M:%S %Z")) return True return False @classmethod def new_lineage(cls, lineagename, cert, privkey, chain, cli_config): # pylint: disable=too-many-locals """Create a new certificate lineage. Attempts to create a certificate lineage -- enrolled for potential future renewal -- with the (suggested) lineage name lineagename, and the associated cert, privkey, and chain (the associated fullchain will be created automatically). Optional configurator and renewalparams record the configuration that was originally used to obtain this cert, so that it can be reused later during automated renewal. Returns a new RenewableCert object referring to the created lineage. (The actual lineage name, as well as all the relevant file paths, will be available within this object.) :param str lineagename: the suggested name for this lineage (normally the current cert's first subject DNS name) :param str cert: the initial certificate version in PEM format :param str privkey: the private key in PEM format :param str chain: the certificate chain in PEM format :param .NamespaceConfig cli_config: parsed command line arguments :returns: the newly-created RenewalCert object :rtype: :class:`storage.renewableCert` """ # Examine the configuration and find the new lineage's name for i in (cli_config.renewal_configs_dir, cli_config.default_archive_dir, cli_config.live_dir): if not os.path.exists(i): os.makedirs(i, 0o700) logger.debug("Creating directory %s.", i) config_file, config_filename = util.unique_lineage_name( cli_config.renewal_configs_dir, lineagename) # Determine where on disk everything will go # lineagename will now potentially be modified based on which # renewal configuration file could actually be created lineagename = lineagename_for_filename(config_filename) archive = full_archive_path(None, cli_config, lineagename) live_dir = _full_live_path(cli_config, lineagename) if os.path.exists(archive): raise errors.CertStorageError( "archive directory exists for " + lineagename) if os.path.exists(live_dir): raise errors.CertStorageError( "live directory exists for " + lineagename) os.mkdir(archive) os.mkdir(live_dir) logger.debug("Archive directory %s and live " "directory %s created.", archive, live_dir) # Put the data into the appropriate files on disk target = dict([(kind, os.path.join(live_dir, kind + ".pem")) for kind in ALL_FOUR]) for kind in ALL_FOUR: os.symlink(os.path.join(_relpath_from_file(archive, target[kind]), kind + "1.pem"), target[kind]) with open(target["cert"], "wb") as f: logger.debug("Writing certificate to %s.", target["cert"]) f.write(cert) with open(target["privkey"], "wb") as f: logger.debug("Writing private key to %s.", target["privkey"]) f.write(privkey) # XXX: Let's make sure to get the file permissions right here with open(target["chain"], "wb") as f: logger.debug("Writing chain to %s.", target["chain"]) f.write(chain) with open(target["fullchain"], "wb") as f: # assumes that OpenSSL.crypto.dump_certificate includes # ending newline character logger.debug("Writing full chain to %s.", target["fullchain"]) f.write(cert + chain) # Write a README file to the live directory readme_path = os.path.join(live_dir, README) with open(readme_path, "w") as f: logger.debug("Writing README to %s.", readme_path) f.write("This directory contains your keys and certificates.\n\n" "`privkey.pem` : the private key for your certificate.\n" "`fullchain.pem`: the certificate file used in most server software.\n" "`chain.pem` : used for OCSP stapling in Nginx >=1.3.7.\n" "`cert.pem` : will break many server configurations, and " "should not be used\n" " without reading further documentation (see link below).\n\n" "WARNING: DO NOT MOVE THESE FILES!\n" " Certbot expects these files to remain in this location in order\n" " to function properly!\n\n" "We recommend not moving these files. For more information, see the Certbot\n" "User Guide at https://certbot.eff.org/docs/using.html#where-are-my-" "certificates.\n") # Document what we've done in a new renewal config file config_file.close() # Save only the config items that are relevant to renewal values = relevant_values(vars(cli_config.namespace)) new_config = write_renewal_config(config_filename, config_filename, archive, target, values) return cls(new_config.filename, cli_config) def save_successor(self, prior_version, new_cert, new_privkey, new_chain, cli_config): """Save new cert and chain as a successor of a prior version. Returns the new version number that was created. .. note:: this function does NOT update links to deploy this version :param int prior_version: the old version to which this version is regarded as a successor (used to choose a privkey, if the key has not changed, but otherwise this information is not permanently recorded anywhere) :param bytes new_cert: the new certificate, in PEM format :param bytes new_privkey: the new private key, in PEM format, or ``None``, if the private key has not changed :param bytes new_chain: the new chain, in PEM format :param .NamespaceConfig cli_config: parsed command line arguments :returns: the new version number that was created :rtype: int """ # XXX: assumes official archive location rather than examining links # XXX: consider using os.open for availability of os.O_EXCL # XXX: ensure file permissions are correct; also create directories # if needed (ensuring their permissions are correct) # Figure out what the new version is and hence where to save things self.cli_config = cli_config target_version = self.next_free_version() target = dict( [(kind, os.path.join(self.archive_dir, "{0}{1}.pem".format(kind, target_version))) for kind in ALL_FOUR]) # Distinguish the cases where the privkey has changed and where it # has not changed (in the latter case, making an appropriate symlink # to an earlier privkey version) if new_privkey is None: # The behavior below keeps the prior key by creating a new # symlink to the old key or the target of the old key symlink. old_privkey = os.path.join( self.archive_dir, "privkey{0}.pem".format(prior_version)) if os.path.islink(old_privkey): old_privkey = os.readlink(old_privkey) else: old_privkey = "privkey{0}.pem".format(prior_version) logger.debug("Writing symlink to old private key, %s.", old_privkey) os.symlink(old_privkey, target["privkey"]) else: with open(target["privkey"], "wb") as f: logger.debug("Writing new private key to %s.", target["privkey"]) f.write(new_privkey) # Save everything else with open(target["cert"], "wb") as f: logger.debug("Writing certificate to %s.", target["cert"]) f.write(new_cert) with open(target["chain"], "wb") as f: logger.debug("Writing chain to %s.", target["chain"]) f.write(new_chain) with open(target["fullchain"], "wb") as f: logger.debug("Writing full chain to %s.", target["fullchain"]) f.write(new_cert + new_chain) symlinks = dict((kind, self.configuration[kind]) for kind in ALL_FOUR) # Update renewal config file self.configfile = update_configuration( self.lineagename, self.archive_dir, symlinks, cli_config) self.configuration = config_with_defaults(self.configfile) return target_version certbot-0.27.0/certbot/ssl-dhparams.pem0000644000175000017500000000065013344054434020202 0ustar ericaerica00000000000000-----BEGIN DH PARAMETERS----- MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz +8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a 87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7 YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi 7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg== -----END DH PARAMETERS----- certbot-0.27.0/certbot/main.py0000644000175000017500000014203013344054434016376 0ustar ericaerica00000000000000"""Certbot main entry point.""" # pylint: disable=too-many-lines from __future__ import print_function import functools import logging.handlers import os import sys import configobj import josepy as jose import zope.component from acme import errors as acme_errors from acme.magic_typing import Union # pylint: disable=unused-import, no-name-in-module import certbot from certbot import account from certbot import cert_manager from certbot import cli from certbot import client from certbot import configuration from certbot import constants from certbot import crypto_util from certbot import eff from certbot import errors from certbot import hooks from certbot import interfaces from certbot import log from certbot import renewal from certbot import reporter from certbot import storage from certbot import updater from certbot import util from certbot.display import util as display_util, ops as display_ops from certbot.plugins import disco as plugins_disco from certbot.plugins import selection as plug_sel from certbot.plugins import enhancements USER_CANCELLED = ("User chose to cancel the operation and may " "reinvoke the client.") logger = logging.getLogger(__name__) def _suggest_donation_if_appropriate(config): """Potentially suggest a donation to support Certbot. :param config: Configuration object :type config: interfaces.IConfig :returns: `None` :rtype: None """ assert config.verb != "renew" if config.staging: # --dry-run implies --staging return reporter_util = zope.component.getUtility(interfaces.IReporter) msg = ("If you like Certbot, please consider supporting our work by:\n\n" "Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate\n" "Donating to EFF: https://eff.org/donate-le\n\n") reporter_util.add_message(msg, reporter_util.LOW_PRIORITY) def _report_successful_dry_run(config): """Reports on successful dry run :param config: Configuration object :type config: interfaces.IConfig :returns: `None` :rtype: None """ reporter_util = zope.component.getUtility(interfaces.IReporter) assert config.verb != "renew" reporter_util.add_message("The dry run was successful.", reporter_util.HIGH_PRIORITY, on_crash=False) def _get_and_save_cert(le_client, config, domains=None, certname=None, lineage=None): """Authenticate and enroll certificate. This method finds the relevant lineage, figures out what to do with it, then performs that action. Includes calls to hooks, various reports, checks, and requests for user input. :param config: Configuration object :type config: interfaces.IConfig :param domains: List of domain names to get a certificate. Defaults to `None` :type domains: `list` of `str` :param certname: Name of new certificate. Defaults to `None` :type certname: str :param lineage: Certificate lineage object. Defaults to `None` :type lineage: storage.RenewableCert :returns: the issued certificate or `None` if doing a dry run :rtype: storage.RenewableCert or None :raises errors.Error: if certificate could not be obtained """ hooks.pre_hook(config) try: if lineage is not None: # Renewal, where we already know the specific lineage we're # interested in logger.info("Renewing an existing certificate") renewal.renew_cert(config, domains, le_client, lineage) else: # TREAT AS NEW REQUEST assert domains is not None logger.info("Obtaining a new certificate") lineage = le_client.obtain_and_enroll_certificate(domains, certname) if lineage is False: raise errors.Error("Certificate could not be obtained") elif lineage is not None: hooks.deploy_hook(config, lineage.names(), lineage.live_dir) finally: hooks.post_hook(config) return lineage def _handle_subset_cert_request(config, domains, cert): """Figure out what to do if a previous cert had a subset of the names now requested :param config: Configuration object :type config: interfaces.IConfig :param domains: List of domain names :type domains: `list` of `str` :param cert: Certificate object :type cert: storage.RenewableCert :returns: Tuple of (str action, cert_or_None) as per _find_lineage_for_domains_and_certname action can be: "newcert" | "renew" | "reinstall" :rtype: `tuple` of `str` """ existing = ", ".join(cert.names()) question = ( "You have an existing certificate that contains a portion of " "the domains you requested (ref: {0}){br}{br}It contains these " "names: {1}{br}{br}You requested these names for the new " "certificate: {2}.{br}{br}Do you want to expand and replace this existing " "certificate with the new certificate?" ).format(cert.configfile.filename, existing, ", ".join(domains), br=os.linesep) if config.expand or config.renew_by_default or zope.component.getUtility( interfaces.IDisplay).yesno(question, "Expand", "Cancel", cli_flag="--expand", force_interactive=True): return "renew", cert else: reporter_util = zope.component.getUtility(interfaces.IReporter) reporter_util.add_message( "To obtain a new certificate that contains these names without " "replacing your existing certificate for {0}, you must use the " "--duplicate option.{br}{br}" "For example:{br}{br}{1} --duplicate {2}".format( existing, sys.argv[0], " ".join(sys.argv[1:]), br=os.linesep ), reporter_util.HIGH_PRIORITY) raise errors.Error(USER_CANCELLED) def _handle_identical_cert_request(config, lineage): """Figure out what to do if a lineage has the same names as a previously obtained one :param config: Configuration object :type config: interfaces.IConfig :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :returns: Tuple of (str action, cert_or_None) as per _find_lineage_for_domains_and_certname action can be: "newcert" | "renew" | "reinstall" :rtype: `tuple` of `str` """ if not lineage.ensure_deployed(): return "reinstall", lineage if renewal.should_renew(config, lineage): return "renew", lineage if config.reinstall: # Set with --reinstall, force an identical certificate to be # reinstalled without further prompting. return "reinstall", lineage question = ( "You have an existing certificate that has exactly the same " "domains or certificate name you requested and isn't close to expiry." "{br}(ref: {0}){br}{br}What would you like to do?" ).format(lineage.configfile.filename, br=os.linesep) if config.verb == "run": keep_opt = "Attempt to reinstall this existing certificate" elif config.verb == "certonly": keep_opt = "Keep the existing certificate for now" choices = [keep_opt, "Renew & replace the cert (limit ~5 per 7 days)"] display = zope.component.getUtility(interfaces.IDisplay) response = display.menu(question, choices, default=0, force_interactive=True) if response[0] == display_util.CANCEL: # TODO: Add notification related to command-line options for # skipping the menu for this case. raise errors.Error( "Operation canceled. You may re-run the client.") elif response[1] == 0: return "reinstall", lineage elif response[1] == 1: return "renew", lineage else: assert False, "This is impossible" def _find_lineage_for_domains(config, domains): """Determine whether there are duplicated names and how to handle them (renew, reinstall, newcert, or raising an error to stop the client run if the user chooses to cancel the operation when prompted). :param config: Configuration object :type config: interfaces.IConfig :param domains: List of domain names :type domains: `list` of `str` :returns: Two-element tuple containing desired new-certificate behavior as a string token ("reinstall", "renew", or "newcert"), plus either a RenewableCert instance or `None` if renewal shouldn't occur. :rtype: `tuple` of `str` and :class:`storage.RenewableCert` or `None` :raises errors.Error: If the user would like to rerun the client again. """ # Considering the possibility that the requested certificate is # related to an existing certificate. (config.duplicate, which # is set with --duplicate, skips all of this logic and forces any # kind of certificate to be obtained with renewal = False.) if config.duplicate: return "newcert", None # TODO: Also address superset case ident_names_cert, subset_names_cert = cert_manager.find_duplicative_certs(config, domains) # XXX ^ schoen is not sure whether that correctly reads the systemwide # configuration file. if ident_names_cert is None and subset_names_cert is None: return "newcert", None if ident_names_cert is not None: return _handle_identical_cert_request(config, ident_names_cert) elif subset_names_cert is not None: return _handle_subset_cert_request(config, domains, subset_names_cert) def _find_cert(config, domains, certname): """Finds an existing certificate object given domains and/or a certificate name. :param config: Configuration object :type config: interfaces.IConfig :param domains: List of domain names :type domains: `list` of `str` :param certname: Name of certificate :type certname: str :returns: Two-element tuple of a boolean that indicates if this function should be followed by a call to fetch a certificate from the server, and either a RenewableCert instance or None. :rtype: `tuple` of `bool` and :class:`storage.RenewableCert` or `None` """ action, lineage = _find_lineage_for_domains_and_certname(config, domains, certname) if action == "reinstall": logger.info("Keeping the existing certificate") return (action != "reinstall"), lineage def _find_lineage_for_domains_and_certname(config, domains, certname): """Find appropriate lineage based on given domains and/or certname. :param config: Configuration object :type config: interfaces.IConfig :param domains: List of domain names :type domains: `list` of `str` :param certname: Name of certificate :type certname: str :returns: Two-element tuple containing desired new-certificate behavior as a string token ("reinstall", "renew", or "newcert"), plus either a RenewableCert instance or None if renewal should not occur. :rtype: `tuple` of `str` and :class:`storage.RenewableCert` or `None` :raises errors.Error: If the user would like to rerun the client again. """ if not certname: return _find_lineage_for_domains(config, domains) else: lineage = cert_manager.lineage_for_certname(config, certname) if lineage: if domains: if set(cert_manager.domains_for_certname(config, certname)) != set(domains): _ask_user_to_confirm_new_names(config, domains, certname, lineage.names()) # raises if no return "renew", lineage # unnecessarily specified domains or no domains specified return _handle_identical_cert_request(config, lineage) else: if domains: return "newcert", None else: raise errors.ConfigurationError("No certificate with name {0} found. " "Use -d to specify domains, or run certbot certificates to see " "possible certificate names.".format(certname)) def _get_added_removed(after, before): """Get lists of items removed from `before` and a lists of items added to `after` """ added = list(set(after) - set(before)) removed = list(set(before) - set(after)) added.sort() removed.sort() return added, removed def _format_list(character, strings): """Format list with given character """ if len(strings) == 0: formatted = "{br}(None)" else: formatted = "{br}{ch} " + "{br}{ch} ".join(strings) return formatted.format( ch=character, br=os.linesep ) def _ask_user_to_confirm_new_names(config, new_domains, certname, old_domains): """Ask user to confirm update cert certname to contain new_domains. :param config: Configuration object :type config: interfaces.IConfig :param new_domains: List of new domain names :type new_domains: `list` of `str` :param certname: Name of certificate :type certname: str :param old_domains: List of old domain names :type old_domains: `list` of `str` :returns: None :rtype: None :raises errors.ConfigurationError: if cert name and domains mismatch """ if config.renew_with_new_domains: return added, removed = _get_added_removed(new_domains, old_domains) msg = ("You are updating certificate {0} to include new domain(s): {1}{br}{br}" "You are also removing previously included domain(s): {2}{br}{br}" "Did you intend to make this change?".format( certname, _format_list("+", added), _format_list("-", removed), br=os.linesep)) obj = zope.component.getUtility(interfaces.IDisplay) if not obj.yesno(msg, "Update cert", "Cancel", default=True): raise errors.ConfigurationError("Specified mismatched cert name and domains.") def _find_domains_or_certname(config, installer, question=None): """Retrieve domains and certname from config or user input. :param config: Configuration object :type config: interfaces.IConfig :param installer: Installer object :type installer: interfaces.IInstaller :param `str` question: Overriding dialog question to ask the user if asked to choose from domain names. :returns: Two-part tuple of domains and certname :rtype: `tuple` of list of `str` and `str` :raises errors.Error: Usage message, if parameters are not used correctly """ domains = None certname = config.certname # first, try to get domains from the config if config.domains: domains = config.domains # if we can't do that but we have a certname, get the domains # with that certname elif certname: domains = cert_manager.domains_for_certname(config, certname) # that certname might not have existed, or there was a problem. # try to get domains from the user. if not domains: domains = display_ops.choose_names(installer, question) if not domains and not certname: raise errors.Error("Please specify --domains, or --installer that " "will help in domain names autodiscovery, or " "--cert-name for an existing certificate name.") return domains, certname def _report_new_cert(config, cert_path, fullchain_path, key_path=None): """Reports the creation of a new certificate to the user. :param cert_path: path to certificate :type cert_path: str :param fullchain_path: path to full chain :type fullchain_path: str :param key_path: path to private key, if available :type key_path: str :returns: `None` :rtype: None """ if config.dry_run: _report_successful_dry_run(config) return assert cert_path and fullchain_path, "No certificates saved to report." expiry = crypto_util.notAfter(cert_path).date() reporter_util = zope.component.getUtility(interfaces.IReporter) # Print the path to fullchain.pem because that's what modern webservers # (Nginx and Apache2.4) will want. verbswitch = ' with the "certonly" option' if config.verb == "run" else "" privkey_statement = 'Your key file has been saved at:{br}{0}{br}'.format( key_path, br=os.linesep) if key_path else "" # XXX Perhaps one day we could detect the presence of known old webservers # and say something more informative here. msg = ('Congratulations! Your certificate and chain have been saved at:{br}' '{0}{br}{1}' 'Your cert will expire on {2}. To obtain a new or tweaked version of this ' 'certificate in the future, simply run {3} again{4}. ' 'To non-interactively renew *all* of your certificates, run "{3} renew"' .format(fullchain_path, privkey_statement, expiry, cli.cli_command, verbswitch, br=os.linesep)) reporter_util.add_message(msg, reporter_util.MEDIUM_PRIORITY) def _determine_account(config): """Determine which account to use. If ``config.account`` is ``None``, it will be updated based on the user input. Same for ``config.email``. :param config: Configuration object :type config: interfaces.IConfig :returns: Account and optionally ACME client API (biproduct of new registration). :rtype: tuple of :class:`certbot.account.Account` and :class:`acme.client.Client` :raises errors.Error: If unable to register an account with ACME server """ def _tos_cb(terms_of_service): if config.tos: return True msg = ("Please read the Terms of Service at {0}. You " "must agree in order to register with the ACME " "server at {1}".format( terms_of_service, config.server)) obj = zope.component.getUtility(interfaces.IDisplay) result = obj.yesno(msg, "Agree", "Cancel", cli_flag="--agree-tos", force_interactive=True) if not result: raise errors.Error( "Registration cannot proceed without accepting " "Terms of Service.") account_storage = account.AccountFileStorage(config) acme = None if config.account is not None: acc = account_storage.load(config.account) else: accounts = account_storage.find_all() if len(accounts) > 1: acc = display_ops.choose_account(accounts) elif len(accounts) == 1: acc = accounts[0] else: # no account registered yet if config.email is None and not config.register_unsafely_without_email: config.email = display_ops.get_email() try: acc, acme = client.register( config, account_storage, tos_cb=_tos_cb) except errors.MissingCommandlineFlag: raise except errors.Error: logger.debug("", exc_info=True) raise errors.Error( "Unable to register an account with ACME server") config.account = acc.id return acc, acme def _delete_if_appropriate(config): # pylint: disable=too-many-locals,too-many-branches """Does the user want to delete their now-revoked certs? If run in non-interactive mode, deleting happens automatically, unless if both `--cert-name` and `--cert-path` were specified with conflicting values. :param config: parsed command line arguments :type config: interfaces.IConfig :returns: `None` :rtype: None :raises errors.Error: If anything goes wrong, including bad user input, if an overlapping archive dir is found for the specified lineage, etc ... """ display = zope.component.getUtility(interfaces.IDisplay) reporter_util = zope.component.getUtility(interfaces.IReporter) attempt_deletion = config.delete_after_revoke if attempt_deletion is None: msg = ("Would you like to delete the cert(s) you just revoked?") attempt_deletion = display.yesno(msg, yes_label="Yes (recommended)", no_label="No", force_interactive=True, default=True) if not attempt_deletion: reporter_util.add_message("Not deleting revoked certs.", reporter_util.LOW_PRIORITY) return if not (config.certname or config.cert_path): raise errors.Error('At least one of --cert-path or --cert-name must be specified.') if config.certname and config.cert_path: # first, check if certname and cert_path imply the same certs implied_cert_name = cert_manager.cert_path_to_lineage(config) if implied_cert_name != config.certname: cert_path_implied_cert_name = cert_manager.cert_path_to_lineage(config) cert_path_implied_conf = storage.renewal_file_for_certname(config, cert_path_implied_cert_name) cert_path_cert = storage.RenewableCert(cert_path_implied_conf, config) cert_path_info = cert_manager.human_readable_cert_info(config, cert_path_cert, skip_filter_checks=True) cert_name_implied_conf = storage.renewal_file_for_certname(config, config.certname) cert_name_cert = storage.RenewableCert(cert_name_implied_conf, config) cert_name_info = cert_manager.human_readable_cert_info(config, cert_name_cert) msg = ("You specified conflicting values for --cert-path and --cert-name. " "Which did you mean to select?") choices = [cert_path_info, cert_name_info] try: code, index = display.menu(msg, choices, ok_label="Select", force_interactive=True) except errors.MissingCommandlineFlag: error_msg = ('To run in non-interactive mode, you must either specify only one of ' '--cert-path or --cert-name, or both must point to the same certificate lineages.') raise errors.Error(error_msg) if code != display_util.OK or not index in range(0, len(choices)): raise errors.Error("User ended interaction.") if index == 0: config.certname = cert_path_implied_cert_name else: config.cert_path = storage.cert_path_for_cert_name(config, config.certname) elif config.cert_path: config.certname = cert_manager.cert_path_to_lineage(config) else: # if only config.certname was specified config.cert_path = storage.cert_path_for_cert_name(config, config.certname) # don't delete if the archive_dir is used by some other lineage archive_dir = storage.full_archive_path( configobj.ConfigObj(storage.renewal_file_for_certname(config, config.certname)), config, config.certname) try: cert_manager.match_and_check_overlaps(config, [lambda x: archive_dir], lambda x: x.archive_dir, lambda x: x) except errors.OverlappingMatchFound: msg = ('Not deleting revoked certs due to overlapping archive dirs. More than ' 'one lineage is using {0}'.format(archive_dir)) reporter_util.add_message(''.join(msg), reporter_util.MEDIUM_PRIORITY) return except Exception as e: msg = ('config.default_archive_dir: {0}, config.live_dir: {1}, archive_dir: {2},' 'original exception: {3}') msg = msg.format(config.default_archive_dir, config.live_dir, archive_dir, e) raise errors.Error(msg) cert_manager.delete(config) def _init_le_client(config, authenticator, installer): """Initialize Let's Encrypt Client :param config: Configuration object :type config: interfaces.IConfig :param authenticator: Acme authentication handler :type authenticator: interfaces.IAuthenticator :param installer: Installer object :type installer: interfaces.IInstaller :returns: client: Client object :rtype: client.Client """ if authenticator is not None: # if authenticator was given, then we will need account... acc, acme = _determine_account(config) logger.debug("Picked account: %r", acc) # XXX #crypto_util.validate_key_csr(acc.key) else: acc, acme = None, None return client.Client(config, acc, authenticator, installer, acme=acme) def unregister(config, unused_plugins): """Deactivate account on server :param config: Configuration object :type config: interfaces.IConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str` :returns: `None` :rtype: None """ account_storage = account.AccountFileStorage(config) accounts = account_storage.find_all() reporter_util = zope.component.getUtility(interfaces.IReporter) if not accounts: return "Could not find existing account to deactivate." yesno = zope.component.getUtility(interfaces.IDisplay).yesno prompt = ("Are you sure you would like to irrevocably deactivate " "your account?") wants_deactivate = yesno(prompt, yes_label='Deactivate', no_label='Abort', default=True) if not wants_deactivate: return "Deactivation aborted." acc, acme = _determine_account(config) cb_client = client.Client(config, acc, None, None, acme=acme) # delete on boulder cb_client.acme.deactivate_registration(acc.regr) account_files = account.AccountFileStorage(config) # delete local account files account_files.delete(config.account) reporter_util.add_message("Account deactivated.", reporter_util.MEDIUM_PRIORITY) def register(config, unused_plugins): """Create or modify accounts on the server. :param config: Configuration object :type config: interfaces.IConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str` :returns: `None` or a string indicating and error :rtype: None or str """ # Portion of _determine_account logic to see whether accounts already # exist or not. account_storage = account.AccountFileStorage(config) accounts = account_storage.find_all() reporter_util = zope.component.getUtility(interfaces.IReporter) add_msg = lambda m: reporter_util.add_message(m, reporter_util.MEDIUM_PRIORITY) # registering a new account if not config.update_registration: if len(accounts) > 0: # TODO: add a flag to register a duplicate account (this will # also require extending _determine_account's behavior # or else extracting the registration code from there) return ("There is an existing account; registration of a " "duplicate account with this command is currently " "unsupported.") # _determine_account will register an account _determine_account(config) return # --update-registration if len(accounts) == 0: return "Could not find an existing account to update." if config.email is None: if config.register_unsafely_without_email: return ("--register-unsafely-without-email provided, however, a " "new e-mail address must\ncurrently be provided when " "updating a registration.") config.email = display_ops.get_email(optional=False) acc, acme = _determine_account(config) cb_client = client.Client(config, acc, None, None, acme=acme) # We rely on an exception to interrupt this process if it didn't work. acc_contacts = ['mailto:' + email for email in config.email.split(',')] prev_regr_uri = acc.regr.uri acc.regr = cb_client.acme.update_registration(acc.regr.update( body=acc.regr.body.update(contact=acc_contacts))) # A v1 account being used as a v2 account will result in changing the uri to # the v2 uri. Since it's the same object on disk, put it back to the v1 uri # so that we can also continue to use the account object with acmev1. acc.regr = acc.regr.update(uri=prev_regr_uri) account_storage.save_regr(acc, cb_client.acme) eff.handle_subscription(config) add_msg("Your e-mail address was updated to {0}.".format(config.email)) def _install_cert(config, le_client, domains, lineage=None): """Install a cert :param config: Configuration object :type config: interfaces.IConfig :param le_client: Client object :type le_client: client.Client :param domains: List of domains :type domains: `list` of `str` :param lineage: Certificate lineage object. Defaults to `None` :type lineage: storage.RenewableCert :returns: `None` :rtype: None """ path_provider = lineage if lineage else config assert path_provider.cert_path is not None le_client.deploy_certificate(domains, path_provider.key_path, path_provider.cert_path, path_provider.chain_path, path_provider.fullchain_path) le_client.enhance_config(domains, path_provider.chain_path) def install(config, plugins): """Install a previously obtained cert in a server. :param config: Configuration object :type config: interfaces.IConfig :param plugins: List of plugins :type plugins: `list` of `str` :returns: `None` :rtype: None """ # XXX: Update for renewer/RenewableCert # FIXME: be consistent about whether errors are raised or returned from # this function ... try: installer, _ = plug_sel.choose_configurator_plugins(config, plugins, "install") except errors.PluginSelectionError as e: return str(e) custom_cert = (config.key_path and config.cert_path) if not config.certname and not custom_cert: certname_question = "Which certificate would you like to install?" config.certname = cert_manager.get_certnames( config, "install", allow_multiple=False, custom_prompt=certname_question)[0] if not enhancements.are_supported(config, installer): raise errors.NotSupportedError("One ore more of the requested enhancements " "are not supported by the selected installer") # If cert-path is defined, populate missing (ie. not overridden) values. # Unfortunately this can't be done in argument parser, as certificate # manager needs the access to renewal directory paths if config.certname: config = _populate_from_certname(config) elif enhancements.are_requested(config): # Preflight config check raise errors.ConfigurationError("One or more of the requested enhancements " "require --cert-name to be provided") if config.key_path and config.cert_path: _check_certificate_and_key(config) domains, _ = _find_domains_or_certname(config, installer) le_client = _init_le_client(config, authenticator=None, installer=installer) _install_cert(config, le_client, domains) else: raise errors.ConfigurationError("Path to certificate or key was not defined. " "If your certificate is managed by Certbot, please use --cert-name " "to define which certificate you would like to install.") if enhancements.are_requested(config): # In the case where we don't have certname, we have errored out already lineage = cert_manager.lineage_for_certname(config, config.certname) enhancements.enable(lineage, domains, installer, config) def _populate_from_certname(config): """Helper function for install to populate missing config values from lineage defined by --cert-name.""" lineage = cert_manager.lineage_for_certname(config, config.certname) if not lineage: return config if not config.key_path: config.namespace.key_path = lineage.key_path if not config.cert_path: config.namespace.cert_path = lineage.cert_path if not config.chain_path: config.namespace.chain_path = lineage.chain_path if not config.fullchain_path: config.namespace.fullchain_path = lineage.fullchain_path return config def _check_certificate_and_key(config): if not os.path.isfile(os.path.realpath(config.cert_path)): raise errors.ConfigurationError("Error while reading certificate from path " "{0}".format(config.cert_path)) if not os.path.isfile(os.path.realpath(config.key_path)): raise errors.ConfigurationError("Error while reading private key from path " "{0}".format(config.key_path)) def plugins_cmd(config, plugins): """List server software plugins. :param config: Configuration object :type config: interfaces.IConfig :param plugins: List of plugins :type plugins: `list` of `str` :returns: `None` :rtype: None """ logger.debug("Expected interfaces: %s", config.ifaces) ifaces = [] if config.ifaces is None else config.ifaces filtered = plugins.visible().ifaces(ifaces) logger.debug("Filtered plugins: %r", filtered) notify = functools.partial(zope.component.getUtility( interfaces.IDisplay).notification, pause=False) if not config.init and not config.prepare: notify(str(filtered)) return filtered.init(config) verified = filtered.verify(ifaces) logger.debug("Verified plugins: %r", verified) if not config.prepare: notify(str(verified)) return verified.prepare() available = verified.available() logger.debug("Prepared plugins: %s", available) notify(str(available)) def enhance(config, plugins): """Add security enhancements to existing configuration :param config: Configuration object :type config: interfaces.IConfig :param plugins: List of plugins :type plugins: `list` of `str` :returns: `None` :rtype: None """ supported_enhancements = ["hsts", "redirect", "uir", "staple"] # Check that at least one enhancement was requested on command line oldstyle_enh = any([getattr(config, enh) for enh in supported_enhancements]) if not enhancements.are_requested(config) and not oldstyle_enh: msg = ("Please specify one or more enhancement types to configure. To list " "the available enhancement types, run:\n\n%s --help enhance\n") logger.warning(msg, sys.argv[0]) raise errors.MisconfigurationError("No enhancements requested, exiting.") try: installer, _ = plug_sel.choose_configurator_plugins(config, plugins, "enhance") except errors.PluginSelectionError as e: return str(e) if not enhancements.are_supported(config, installer): raise errors.NotSupportedError("One ore more of the requested enhancements " "are not supported by the selected installer") certname_question = ("Which certificate would you like to use to enhance " "your configuration?") config.certname = cert_manager.get_certnames( config, "enhance", allow_multiple=False, custom_prompt=certname_question)[0] cert_domains = cert_manager.domains_for_certname(config, config.certname) if config.noninteractive_mode: domains = cert_domains else: domain_question = ("Which domain names would you like to enable the " "selected enhancements for?") domains = display_ops.choose_values(cert_domains, domain_question) if not domains: raise errors.Error("User cancelled the domain selection. No domains " "defined, exiting.") lineage = cert_manager.lineage_for_certname(config, config.certname) if not config.chain_path: config.chain_path = lineage.chain_path if oldstyle_enh: le_client = _init_le_client(config, authenticator=None, installer=installer) le_client.enhance_config(domains, config.chain_path, ask_redirect=False) if enhancements.are_requested(config): enhancements.enable(lineage, domains, installer, config) def rollback(config, plugins): """Rollback server configuration changes made during install. :param config: Configuration object :type config: interfaces.IConfig :param plugins: List of plugins :type plugins: `list` of `str` :returns: `None` :rtype: None """ client.rollback(config.installer, config.checkpoints, config, plugins) def config_changes(config, unused_plugins): """Show changes made to server config during installation View checkpoints and associated configuration changes. :param config: Configuration object :type config: interfaces.IConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str` :returns: `None` :rtype: None """ client.view_config_changes(config, num=config.num) def update_symlinks(config, unused_plugins): """Update the certificate file family symlinks Use the information in the config file to make symlinks point to the correct archive directory. :param config: Configuration object :type config: interfaces.IConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str` :returns: `None` :rtype: None """ cert_manager.update_live_symlinks(config) def rename(config, unused_plugins): """Rename a certificate Use the information in the config file to rename an existing lineage. :param config: Configuration object :type config: interfaces.IConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str` :returns: `None` :rtype: None """ cert_manager.rename_lineage(config) def delete(config, unused_plugins): """Delete a certificate Use the information in the config file to delete an existing lineage. :param config: Configuration object :type config: interfaces.IConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str` :returns: `None` :rtype: None """ cert_manager.delete(config) def certificates(config, unused_plugins): """Display information about certs configured with Certbot :param config: Configuration object :type config: interfaces.IConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str` :returns: `None` :rtype: None """ cert_manager.certificates(config) def revoke(config, unused_plugins): # TODO: coop with renewal config """Revoke a previously obtained certificate. :param config: Configuration object :type config: interfaces.IConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str` :returns: `None` or string indicating error in case of error :rtype: None or str """ # For user-agent construction config.installer = config.authenticator = None if config.key_path is not None: # revocation by cert key logger.debug("Revoking %s using cert key %s", config.cert_path[0], config.key_path[0]) crypto_util.verify_cert_matches_priv_key(config.cert_path[0], config.key_path[0]) key = jose.JWK.load(config.key_path[1]) acme = client.acme_from_config_key(config, key) else: # revocation by account key logger.debug("Revoking %s using Account Key", config.cert_path[0]) acc, _ = _determine_account(config) acme = client.acme_from_config_key(config, acc.key, acc.regr) cert = crypto_util.pyopenssl_load_certificate(config.cert_path[1])[0] logger.debug("Reason code for revocation: %s", config.reason) try: acme.revoke(jose.ComparableX509(cert), config.reason) _delete_if_appropriate(config) except acme_errors.ClientError as e: return str(e) display_ops.success_revocation(config.cert_path[0]) def run(config, plugins): # pylint: disable=too-many-branches,too-many-locals """Obtain a certificate and install. :param config: Configuration object :type config: interfaces.IConfig :param plugins: List of plugins :type plugins: `list` of `str` :returns: `None` :rtype: None """ # TODO: Make run as close to auth + install as possible # Possible difficulties: config.csr was hacked into auth try: installer, authenticator = plug_sel.choose_configurator_plugins(config, plugins, "run") except errors.PluginSelectionError as e: return str(e) # Preflight check for enhancement support by the selected installer if not enhancements.are_supported(config, installer): raise errors.NotSupportedError("One ore more of the requested enhancements " "are not supported by the selected installer") # TODO: Handle errors from _init_le_client? le_client = _init_le_client(config, authenticator, installer) domains, certname = _find_domains_or_certname(config, installer) should_get_cert, lineage = _find_cert(config, domains, certname) new_lineage = lineage if should_get_cert: new_lineage = _get_and_save_cert(le_client, config, domains, certname, lineage) cert_path = new_lineage.cert_path if new_lineage else None fullchain_path = new_lineage.fullchain_path if new_lineage else None key_path = new_lineage.key_path if new_lineage else None _report_new_cert(config, cert_path, fullchain_path, key_path) _install_cert(config, le_client, domains, new_lineage) if enhancements.are_requested(config) and new_lineage: enhancements.enable(new_lineage, domains, installer, config) if lineage is None or not should_get_cert: display_ops.success_installation(domains) else: display_ops.success_renewal(domains) _suggest_donation_if_appropriate(config) def _csr_get_and_save_cert(config, le_client): """Obtain a cert using a user-supplied CSR This works differently in the CSR case (for now) because we don't have the privkey, and therefore can't construct the files for a lineage. So we just save the cert & chain to disk :/ :param config: Configuration object :type config: interfaces.IConfig :param client: Client object :type client: client.Client :returns: `cert_path` and `fullchain_path` as absolute paths to the actual files :rtype: `tuple` of `str` """ csr, _ = config.actual_csr cert, chain = le_client.obtain_certificate_from_csr(csr) if config.dry_run: logger.debug( "Dry run: skipping saving certificate to %s", config.cert_path) return None, None cert_path, _, fullchain_path = le_client.save_certificate( cert, chain, config.cert_path, config.chain_path, config.fullchain_path) return cert_path, fullchain_path def renew_cert(config, plugins, lineage): """Renew & save an existing cert. Do not install it. :param config: Configuration object :type config: interfaces.IConfig :param plugins: List of plugins :type plugins: `list` of `str` :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :returns: `None` :rtype: None :raises errors.PluginSelectionError: MissingCommandlineFlag if supplied parameters do not pass """ try: # installers are used in auth mode to determine domain names installer, auth = plug_sel.choose_configurator_plugins(config, plugins, "certonly") except errors.PluginSelectionError as e: logger.info("Could not choose appropriate plugin: %s", e) raise le_client = _init_le_client(config, auth, installer) renewed_lineage = _get_and_save_cert(le_client, config, lineage=lineage) notify = zope.component.getUtility(interfaces.IDisplay).notification if installer is None: notify("new certificate deployed without reload, fullchain is {0}".format( lineage.fullchain), pause=False) else: # In case of a renewal, reload server to pick up new certificate. # In principle we could have a configuration option to inhibit this # from happening. # Run deployer updater.run_renewal_deployer(config, renewed_lineage, installer) installer.restart() notify("new certificate deployed with reload of {0} server; fullchain is {1}".format( config.installer, lineage.fullchain), pause=False) def certonly(config, plugins): """Authenticate & obtain cert, but do not install it. This implements the 'certonly' subcommand. :param config: Configuration object :type config: interfaces.IConfig :param plugins: List of plugins :type plugins: `list` of `str` :returns: `None` :rtype: None :raises errors.Error: If specified plugin could not be used """ # SETUP: Select plugins and construct a client instance try: # installers are used in auth mode to determine domain names installer, auth = plug_sel.choose_configurator_plugins(config, plugins, "certonly") except errors.PluginSelectionError as e: logger.info("Could not choose appropriate plugin: %s", e) raise le_client = _init_le_client(config, auth, installer) if config.csr: cert_path, fullchain_path = _csr_get_and_save_cert(config, le_client) _report_new_cert(config, cert_path, fullchain_path) _suggest_donation_if_appropriate(config) return domains, certname = _find_domains_or_certname(config, installer) should_get_cert, lineage = _find_cert(config, domains, certname) if not should_get_cert: notify = zope.component.getUtility(interfaces.IDisplay).notification notify("Certificate not yet due for renewal; no action taken.", pause=False) return lineage = _get_and_save_cert(le_client, config, domains, certname, lineage) cert_path = lineage.cert_path if lineage else None fullchain_path = lineage.fullchain_path if lineage else None key_path = lineage.key_path if lineage else None _report_new_cert(config, cert_path, fullchain_path, key_path) _suggest_donation_if_appropriate(config) def renew(config, unused_plugins): """Renew previously-obtained certificates. :param config: Configuration object :type config: interfaces.IConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str` :returns: `None` :rtype: None """ try: renewal.handle_renewal_request(config) finally: hooks.run_saved_post_hooks() def make_or_verify_needed_dirs(config): """Create or verify existence of config, work, and hook directories. :param config: Configuration object :type config: interfaces.IConfig :returns: `None` :rtype: None """ util.set_up_core_dir(config.config_dir, constants.CONFIG_DIRS_MODE, os.geteuid(), config.strict_permissions) util.set_up_core_dir(config.work_dir, constants.CONFIG_DIRS_MODE, os.geteuid(), config.strict_permissions) hook_dirs = (config.renewal_pre_hooks_dir, config.renewal_deploy_hooks_dir, config.renewal_post_hooks_dir,) for hook_dir in hook_dirs: util.make_or_verify_dir(hook_dir, uid=os.geteuid(), strict=config.strict_permissions) def set_displayer(config): """Set the displayer :param config: Configuration object :type config: interfaces.IConfig :returns: `None` :rtype: None """ if config.quiet: config.noninteractive_mode = True displayer = display_util.NoninteractiveDisplay(open(os.devnull, "w")) \ # type: Union[None, display_util.NoninteractiveDisplay, display_util.FileDisplay] elif config.noninteractive_mode: displayer = display_util.NoninteractiveDisplay(sys.stdout) else: displayer = display_util.FileDisplay(sys.stdout, config.force_interactive) zope.component.provideUtility(displayer) def main(cli_args=sys.argv[1:]): """Command line argument parsing and main script execution. :returns: result of requested command :raises errors.Error: OS errors triggered by wrong permissions :raises errors.Error: error if plugin command is not supported """ log.pre_arg_parse_setup() plugins = plugins_disco.PluginsRegistry.find_all() logger.debug("certbot version: %s", certbot.__version__) # do not log `config`, as it contains sensitive data (e.g. revoke --key)! logger.debug("Arguments: %r", cli_args) logger.debug("Discovered plugins: %r", plugins) # note: arg parser internally handles --help (and exits afterwards) args = cli.prepare_and_parse_args(plugins, cli_args) config = configuration.NamespaceConfig(args) zope.component.provideUtility(config) try: log.post_arg_parse_setup(config) make_or_verify_needed_dirs(config) except errors.Error: # Let plugins_cmd be run as un-privileged user. if config.func != plugins_cmd: raise set_displayer(config) # Reporter report = reporter.Reporter(config) zope.component.provideUtility(report) util.atexit_register(report.print_messages) return config.func(config, plugins) if __name__ == "__main__": err_string = main() if err_string: logger.warning("Exiting with message %s", err_string) sys.exit(err_string) # pragma: no cover certbot-0.27.0/certbot/cli.py0000644000175000017500000021416013344054434016225 0ustar ericaerica00000000000000"""Certbot command line argument & config processing.""" # pylint: disable=too-many-lines from __future__ import print_function import argparse import copy import glob import logging import logging.handlers import os import sys import configargparse import six import zope.component import zope.interface from zope.interface import interfaces as zope_interfaces from acme import challenges # pylint: disable=unused-import, no-name-in-module from acme.magic_typing import Any, Dict, Optional # pylint: enable=unused-import, no-name-in-module import certbot from certbot import constants from certbot import crypto_util from certbot import errors from certbot import hooks from certbot import interfaces from certbot import util from certbot.display import util as display_util from certbot.plugins import disco as plugins_disco import certbot.plugins.enhancements as enhancements import certbot.plugins.selection as plugin_selection logger = logging.getLogger(__name__) # Global, to save us from a lot of argument passing within the scope of this module helpful_parser = None # type: Optional[HelpfulArgumentParser] # For help strings, figure out how the user ran us. # When invoked from letsencrypt-auto, sys.argv[0] is something like: # "/home/user/.local/share/certbot/bin/certbot" # Note that this won't work if the user set VENV_PATH or XDG_DATA_HOME before # running letsencrypt-auto (and sudo stops us from seeing if they did), so it # should only be used for purposes where inability to detect letsencrypt-auto # fails safely LEAUTO = "letsencrypt-auto" if "CERTBOT_AUTO" in os.environ: # if we're here, this is probably going to be certbot-auto, unless the # user saved the script under a different name LEAUTO = os.path.basename(os.environ["CERTBOT_AUTO"]) old_path_fragment = os.path.join(".local", "share", "letsencrypt") new_path_prefix = os.path.abspath(os.path.join(os.sep, "opt", "eff.org", "certbot", "venv")) if old_path_fragment in sys.argv[0] or sys.argv[0].startswith(new_path_prefix): cli_command = LEAUTO else: cli_command = "certbot" # Argparse's help formatting has a lot of unhelpful peculiarities, so we want # to replace as much of it as we can... # This is the stub to include in help generated by argparse SHORT_USAGE = """ {0} [SUBCOMMAND] [options] [-d DOMAIN] [-d DOMAIN] ... Certbot can obtain and install HTTPS/TLS/SSL certificates. By default, it will attempt to use a webserver both for obtaining and installing the certificate. """.format(cli_command) # This section is used for --help and --help all ; it needs information # about installed plugins to be fully formatted COMMAND_OVERVIEW = """The most common SUBCOMMANDS and flags are: obtain, install, and renew certificates: (default) run Obtain & install a certificate in your current webserver certonly Obtain or renew a certificate, but do not install it renew Renew all previously obtained certificates that are near expiry enhance Add security enhancements to your existing configuration -d DOMAINS Comma-separated list of domains to obtain a certificate for %s --standalone Run a standalone webserver for authentication %s --webroot Place files in a server's webroot folder for authentication --manual Obtain certificates interactively, or using shell script hooks -n Run non-interactively --test-cert Obtain a test certificate from a staging server --dry-run Test "renew" or "certonly" without saving any certificates to disk manage certificates: certificates Display information about certificates you have from Certbot revoke Revoke a certificate (supply --cert-path) delete Delete a certificate manage your account with Let's Encrypt: register Create a Let's Encrypt ACME account --agree-tos Agree to the ACME server's Subscriber Agreement -m EMAIL Email address for important account notifications """ # This is the short help for certbot --help, where we disable argparse # altogether HELP_USAGE = """ More detailed help: -h, --help [TOPIC] print this message, or detailed help on a topic; the available TOPICS are: all, automation, commands, paths, security, testing, or any of the subcommands or plugins (certonly, renew, install, register, nginx, apache, standalone, webroot, etc.) """ # These argparse parameters should be removed when detecting defaults. ARGPARSE_PARAMS_TO_REMOVE = ("const", "nargs", "type",) # These sets are used when to help detect options set by the user. EXIT_ACTIONS = set(("help", "version",)) ZERO_ARG_ACTIONS = set(("store_const", "store_true", "store_false", "append_const", "count",)) # Maps a config option to a set of config options that may have modified it. # This dictionary is used recursively, so if A modifies B and B modifies C, # it is determined that C was modified by the user if A was modified. VAR_MODIFIERS = {"account": set(("server",)), "renew_hook": set(("deploy_hook",)), "server": set(("dry_run", "staging",)), "webroot_map": set(("webroot_path",))} def report_config_interaction(modified, modifiers): """Registers config option interaction to be checked by set_by_cli. This function can be called by during the __init__ or add_parser_arguments methods of plugins to register interactions between config options. :param modified: config options that can be modified by modifiers :type modified: iterable or str (string_types) :param modifiers: config options that modify modified :type modifiers: iterable or str (string_types) """ if isinstance(modified, six.string_types): modified = (modified,) if isinstance(modifiers, six.string_types): modifiers = (modifiers,) for var in modified: VAR_MODIFIERS.setdefault(var, set()).update(modifiers) def possible_deprecation_warning(config): "A deprecation warning for users with the old, not-self-upgrading letsencrypt-auto." if cli_command != LEAUTO: return if config.no_self_upgrade: # users setting --no-self-upgrade might be hanging on a client version like 0.3.0 # or 0.5.0 which is the new script, but doesn't set CERTBOT_AUTO; they don't # need warnings return if "CERTBOT_AUTO" not in os.environ: logger.warning("You are running with an old copy of letsencrypt-auto that does " "not receive updates, and is less reliable than more recent versions. " "We recommend upgrading to the latest certbot-auto script, or using native " "OS packages.") logger.debug("Deprecation warning circumstances: %s / %s", sys.argv[0], os.environ) class _Default(object): """A class to use as a default to detect if a value is set by a user""" def __bool__(self): return False def __eq__(self, other): return isinstance(other, _Default) def __hash__(self): return id(_Default) def __nonzero__(self): return self.__bool__() def set_by_cli(var): """ Return True if a particular config variable has been set by the user (CLI or config file) including if the user explicitly set it to the default. Returns False if the variable was assigned a default value. """ detector = set_by_cli.detector # type: ignore if detector is None and helpful_parser is not None: # Setup on first run: `detector` is a weird version of config in which # the default value of every attribute is wrangled to be boolean-false plugins = plugins_disco.PluginsRegistry.find_all() # reconstructed_args == sys.argv[1:], or whatever was passed to main() reconstructed_args = helpful_parser.args + [helpful_parser.verb] detector = set_by_cli.detector = prepare_and_parse_args( # type: ignore plugins, reconstructed_args, detect_defaults=True) # propagate plugin requests: eg --standalone modifies config.authenticator detector.authenticator, detector.installer = ( # type: ignore plugin_selection.cli_plugin_requests(detector)) if not isinstance(getattr(detector, var), _Default): logger.debug("Var %s=%s (set by user).", var, getattr(detector, var)) return True for modifier in VAR_MODIFIERS.get(var, []): if set_by_cli(modifier): logger.debug("Var %s=%s (set by user).", var, VAR_MODIFIERS.get(var, [])) return True return False # static housekeeping var # functions attributed are not supported by mypy # https://github.com/python/mypy/issues/2087 set_by_cli.detector = None # type: ignore def has_default_value(option, value): """Does option have the default value? If the default value of option is not known, False is returned. :param str option: configuration variable being considered :param value: value of the configuration variable named option :returns: True if option has the default value, otherwise, False :rtype: bool """ if helpful_parser is not None: return (option in helpful_parser.defaults and helpful_parser.defaults[option] == value) return False def option_was_set(option, value): """Was option set by the user or does it differ from the default? :param str option: configuration variable being considered :param value: value of the configuration variable named option :returns: True if the option was set, otherwise, False :rtype: bool """ return set_by_cli(option) or not has_default_value(option, value) def argparse_type(variable): """Return our argparse type function for a config variable (default: str)""" # pylint: disable=protected-access if helpful_parser is not None: for action in helpful_parser.parser._actions: if action.type is not None and action.dest == variable: return action.type return str def read_file(filename, mode="rb"): """Returns the given file's contents. :param str filename: path to file :param str mode: open mode (see `open`) :returns: absolute path of filename and its contents :rtype: tuple :raises argparse.ArgumentTypeError: File does not exist or is not readable. """ try: filename = os.path.abspath(filename) return filename, open(filename, mode).read() except IOError as exc: raise argparse.ArgumentTypeError(exc.strerror) def flag_default(name): """Default value for CLI flag.""" # XXX: this is an internal housekeeping notion of defaults before # argparse has been set up; it is not accurate for all flags. Call it # with caution. Plugin defaults are missing, and some things are using # defaults defined in this file, not in constants.py :( return copy.deepcopy(constants.CLI_DEFAULTS[name]) def config_help(name, hidden=False): """Extract the help message for an `.IConfig` attribute.""" # pylint: disable=no-member if hidden: return argparse.SUPPRESS else: field = interfaces.IConfig.__getitem__(name) # type: zope.interface.interface.Attribute return field.__doc__ class HelpfulArgumentGroup(object): """Emulates an argparse group for use with HelpfulArgumentParser. This class is used in the add_group method of HelpfulArgumentParser. Command line arguments can be added to the group, but help suppression and default detection is applied by HelpfulArgumentParser when necessary. """ def __init__(self, helpful_arg_parser, topic): self._parser = helpful_arg_parser self._topic = topic def add_argument(self, *args, **kwargs): """Add a new command line argument to the argument group.""" self._parser.add(self._topic, *args, **kwargs) class CustomHelpFormatter(argparse.HelpFormatter): """This is a clone of ArgumentDefaultsHelpFormatter, with bugfixes. In particular we fix https://bugs.python.org/issue28742 """ def _get_help_string(self, action): helpstr = action.help if '%(default)' not in action.help and '(default:' not in action.help: if action.default != argparse.SUPPRESS: defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE] if action.option_strings or action.nargs in defaulting_nargs: helpstr += ' (default: %(default)s)' return helpstr # The attributes here are: # short: a string that will be displayed by "certbot -h commands" # opts: a string that heads the section of flags with which this command is documented, # both for "certbot -h SUBCOMMAND" and "certbot -h all" # usage: an optional string that overrides the header of "certbot -h SUBCOMMAND" VERB_HELP = [ ("run (default)", { "short": "Obtain/renew a certificate, and install it", "opts": "Options for obtaining & installing certificates", "usage": SHORT_USAGE.replace("[SUBCOMMAND]", ""), "realname": "run" }), ("certonly", { "short": "Obtain or renew a certificate, but do not install it", "opts": "Options for modifying how a certificate is obtained", "usage": ("\n\n certbot certonly [options] [-d DOMAIN] [-d DOMAIN] ...\n\n" "This command obtains a TLS/SSL certificate without installing it anywhere.") }), ("renew", { "short": "Renew all certificates (or one specified with --cert-name)", "opts": ("The 'renew' subcommand will attempt to renew all" " certificates (or more precisely, certificate lineages) you have" " previously obtained if they are close to expiry, and print a" " summary of the results. By default, 'renew' will reuse the options" " used to create obtain or most recently successfully renew each" " certificate lineage. You can try it with `--dry-run` first. For" " more fine-grained control, you can renew individual lineages with" " the `certonly` subcommand. Hooks are available to run commands" " before and after renewal; see" " https://certbot.eff.org/docs/using.html#renewal for more" " information on these."), "usage": "\n\n certbot renew [--cert-name CERTNAME] [options]\n\n" }), ("certificates", { "short": "List certificates managed by Certbot", "opts": "List certificates managed by Certbot", "usage": ("\n\n certbot certificates [options] ...\n\n" "Print information about the status of certificates managed by Certbot.") }), ("delete", { "short": "Clean up all files related to a certificate", "opts": "Options for deleting a certificate", "usage": "\n\n certbot delete --cert-name CERTNAME\n\n" }), ("revoke", { "short": "Revoke a certificate specified with --cert-path", "opts": "Options for revocation of certificates", "usage": "\n\n certbot revoke --cert-path /path/to/fullchain.pem [options]\n\n" }), ("register", { "short": "Register for account with Let's Encrypt / other ACME server", "opts": "Options for account registration & modification", "usage": "\n\n certbot register --email user@example.com [options]\n\n" }), ("unregister", { "short": "Irrevocably deactivate your account", "opts": "Options for account deactivation.", "usage": "\n\n certbot unregister [options]\n\n" }), ("install", { "short": "Install an arbitrary certificate in a server", "opts": "Options for modifying how a certificate is deployed", "usage": "\n\n certbot install --cert-path /path/to/fullchain.pem " " --key-path /path/to/private-key [options]\n\n" }), ("config_changes", { "short": "Show changes that Certbot has made to server configurations", "opts": "Options for controlling which changes are displayed", "usage": "\n\n certbot config_changes --num NUM [options]\n\n" }), ("rollback", { "short": "Roll back server conf changes made during certificate installation", "opts": "Options for rolling back server configuration changes", "usage": "\n\n certbot rollback --checkpoints 3 [options]\n\n" }), ("plugins", { "short": "List plugins that are installed and available on your system", "opts": 'Options for for the "plugins" subcommand', "usage": "\n\n certbot plugins [options]\n\n" }), ("update_symlinks", { "short": "Recreate symlinks in your /etc/letsencrypt/live/ directory", "opts": ("Recreates certificate and key symlinks in {0}, if you changed them by hand " "or edited a renewal configuration file".format( os.path.join(flag_default("config_dir"), "live"))), "usage": "\n\n certbot update_symlinks [options]\n\n" }), ("enhance", { "short": "Add security enhancements to your existing configuration", "opts": ("Helps to harden the TLS configuration by adding security enhancements " "to already existing configuration."), "usage": "\n\n certbot enhance [options]\n\n" }), ] # VERB_HELP is a list in order to preserve order, but a dict is sometimes useful VERB_HELP_MAP = dict(VERB_HELP) class HelpfulArgumentParser(object): """Argparse Wrapper. This class wraps argparse, adding the ability to make --help less verbose, and request help on specific subcategories at a time, eg 'certbot --help security' for security options. """ def __init__(self, args, plugins, detect_defaults=False): from certbot import main self.VERBS = { "auth": main.certonly, "certonly": main.certonly, "config_changes": main.config_changes, "run": main.run, "install": main.install, "plugins": main.plugins_cmd, "register": main.register, "unregister": main.unregister, "renew": main.renew, "revoke": main.revoke, "rollback": main.rollback, "everything": main.run, "update_symlinks": main.update_symlinks, "certificates": main.certificates, "delete": main.delete, "enhance": main.enhance, } # Get notification function for printing try: self.notify = zope.component.getUtility( interfaces.IDisplay).notification except zope_interfaces.ComponentLookupError: self.notify = display_util.NoninteractiveDisplay( sys.stdout).notification # List of topics for which additional help can be provided HELP_TOPICS = ["all", "security", "paths", "automation", "testing"] HELP_TOPICS += list(self.VERBS) + self.COMMANDS_TOPICS + ["manage"] plugin_names = list(plugins) self.help_topics = HELP_TOPICS + plugin_names + [None] # type: ignore self.detect_defaults = detect_defaults self.args = args if self.args and self.args[0] == 'help': self.args[0] = '--help' self.determine_verb() help1 = self.prescan_for_flag("-h", self.help_topics) help2 = self.prescan_for_flag("--help", self.help_topics) if isinstance(help1, bool) and isinstance(help2, bool): self.help_arg = help1 or help2 else: self.help_arg = help1 if isinstance(help1, six.string_types) else help2 short_usage = self._usage_string(plugins, self.help_arg) self.visible_topics = self.determine_help_topics(self.help_arg) # elements are added by .add_group() self.groups = {} # type: Dict[str, argparse._ArgumentGroup] # elements are added by .parse_args() self.defaults = {} # type: Dict[str, Any] self.parser = configargparse.ArgParser( prog="certbot", usage=short_usage, formatter_class=CustomHelpFormatter, args_for_setting_config_path=["-c", "--config"], default_config_files=flag_default("config_files"), config_arg_help_message="path to config file (default: {0})".format( " and ".join(flag_default("config_files")))) # This is the only way to turn off overly verbose config flag documentation self.parser._add_config_file_help = False # pylint: disable=protected-access # Help that are synonyms for --help subcommands COMMANDS_TOPICS = ["command", "commands", "subcommand", "subcommands", "verbs"] def _list_subcommands(self): longest = max(len(v) for v in VERB_HELP_MAP.keys()) text = "The full list of available SUBCOMMANDS is:\n\n" for verb, props in sorted(VERB_HELP): doc = props.get("short", "") text += '{0:<{length}} {1}\n'.format(verb, doc, length=longest) text += "\nYou can get more help on a specific subcommand with --help SUBCOMMAND\n" return text def _usage_string(self, plugins, help_arg): """Make usage strings late so that plugins can be initialised late :param plugins: all discovered plugins :param help_arg: False for none; True for --help; "TOPIC" for --help TOPIC :rtype: str :returns: a short usage string for the top of --help TOPIC) """ if "nginx" in plugins: nginx_doc = "--nginx Use the Nginx plugin for authentication & installation" else: nginx_doc = "(the certbot nginx plugin is not installed)" if "apache" in plugins: apache_doc = "--apache Use the Apache plugin for authentication & installation" else: apache_doc = "(the certbot apache plugin is not installed)" usage = SHORT_USAGE if help_arg == True: self.notify(usage + COMMAND_OVERVIEW % (apache_doc, nginx_doc) + HELP_USAGE) sys.exit(0) elif help_arg in self.COMMANDS_TOPICS: self.notify(usage + self._list_subcommands()) sys.exit(0) elif help_arg == "all": # if we're doing --help all, the OVERVIEW is part of the SHORT_USAGE at # the top; if we're doing --help someothertopic, it's OT so it's not usage += COMMAND_OVERVIEW % (apache_doc, nginx_doc) else: custom = VERB_HELP_MAP.get(help_arg, {}).get("usage", None) usage = custom if custom else usage return usage def remove_config_file_domains_for_renewal(self, parsed_args): """Make "certbot renew" safe if domains are set in cli.ini.""" # Works around https://github.com/certbot/certbot/issues/4096 if self.verb == "renew": for source, flags in self.parser._source_to_settings.items(): # pylint: disable=protected-access if source.startswith("config_file") and "domains" in flags: parsed_args.domains = _Default() if self.detect_defaults else [] def parse_args(self): """Parses command line arguments and returns the result. :returns: parsed command line arguments :rtype: argparse.Namespace """ parsed_args = self.parser.parse_args(self.args) parsed_args.func = self.VERBS[self.verb] parsed_args.verb = self.verb self.remove_config_file_domains_for_renewal(parsed_args) if self.detect_defaults: return parsed_args self.defaults = dict((key, copy.deepcopy(self.parser.get_default(key))) for key in vars(parsed_args)) # Do any post-parsing homework here if self.verb == "renew": if parsed_args.force_interactive: raise errors.Error( "{0} cannot be used with renew".format( constants.FORCE_INTERACTIVE_FLAG)) parsed_args.noninteractive_mode = True if parsed_args.force_interactive and parsed_args.noninteractive_mode: raise errors.Error( "Flag for non-interactive mode and {0} conflict".format( constants.FORCE_INTERACTIVE_FLAG)) if parsed_args.staging or parsed_args.dry_run: self.set_test_server(parsed_args) if parsed_args.csr: self.handle_csr(parsed_args) if parsed_args.must_staple: parsed_args.staple = True if parsed_args.validate_hooks: hooks.validate_hooks(parsed_args) if parsed_args.allow_subset_of_names: if any(util.is_wildcard_domain(d) for d in parsed_args.domains): raise errors.Error("Using --allow-subset-of-names with a" " wildcard domain is not supported.") if parsed_args.hsts and parsed_args.auto_hsts: raise errors.Error( "Parameters --hsts and --auto-hsts cannot be used simultaneously.") possible_deprecation_warning(parsed_args) return parsed_args def set_test_server(self, parsed_args): """We have --staging/--dry-run; perform sanity check and set config.server""" if parsed_args.server not in (flag_default("server"), constants.STAGING_URI): conflicts = ["--staging"] if parsed_args.staging else [] conflicts += ["--dry-run"] if parsed_args.dry_run else [] raise errors.Error("--server value conflicts with {0}".format( " and ".join(conflicts))) parsed_args.server = constants.STAGING_URI if parsed_args.dry_run: if self.verb not in ["certonly", "renew"]: raise errors.Error("--dry-run currently only works with the " "'certonly' or 'renew' subcommands (%r)" % self.verb) parsed_args.break_my_certs = parsed_args.staging = True if glob.glob(os.path.join(parsed_args.config_dir, constants.ACCOUNTS_DIR, "*")): # The user has a prod account, but might not have a staging # one; we don't want to start trying to perform interactive registration parsed_args.tos = True parsed_args.register_unsafely_without_email = True def handle_csr(self, parsed_args): """Process a --csr flag.""" if parsed_args.verb != "certonly": raise errors.Error("Currently, a CSR file may only be specified " "when obtaining a new or replacement " "via the certonly command. Please try the " "certonly command instead.") if parsed_args.allow_subset_of_names: raise errors.Error("--allow-subset-of-names cannot be used with --csr") csrfile, contents = parsed_args.csr[0:2] typ, csr, domains = crypto_util.import_csr_file(csrfile, contents) # This is not necessary for webroot to work, however, # obtain_certificate_from_csr requires parsed_args.domains to be set for domain in domains: add_domains(parsed_args, domain) if not domains: # TODO: add CN to domains instead: raise errors.Error( "Unfortunately, your CSR %s needs to have a SubjectAltName for every domain" % parsed_args.csr[0]) parsed_args.actual_csr = (csr, typ) csr_domains = set([d.lower() for d in domains]) config_domains = set(parsed_args.domains) if csr_domains != config_domains: raise errors.ConfigurationError( "Inconsistent domain requests:\nFrom the CSR: {0}\nFrom command line/config: {1}" .format(", ".join(csr_domains), ", ".join(config_domains))) def determine_verb(self): """Determines the verb/subcommand provided by the user. This function works around some of the limitations of argparse. """ if "-h" in self.args or "--help" in self.args: # all verbs double as help arguments; don't get them confused self.verb = "help" return for i, token in enumerate(self.args): if token in self.VERBS: verb = token if verb == "auth": verb = "certonly" if verb == "everything": verb = "run" self.verb = verb self.args.pop(i) return self.verb = "run" def prescan_for_flag(self, flag, possible_arguments): """Checks cli input for flags. Check for a flag, which accepts a fixed set of possible arguments, in the command line; we will use this information to configure argparse's help correctly. Return the flag's argument, if it has one that matches the sequence @possible_arguments; otherwise return whether the flag is present. """ if flag not in self.args: return False pos = self.args.index(flag) try: nxt = self.args[pos + 1] if nxt in possible_arguments: return nxt except IndexError: pass return True def add(self, topics, *args, **kwargs): """Add a new command line argument. :param topics: str or [str] help topic(s) this should be listed under, or None for "always documented". The first entry determines where the flag lives in the "--help all" output (None -> "optional arguments"). :param list *args: the names of this argument flag :param dict **kwargs: various argparse settings for this argument """ if isinstance(topics, list): # if this flag can be listed in multiple sections, try to pick the one # that the user has asked for help about topic = self.help_arg if self.help_arg in topics else topics[0] else: topic = topics # there's only one if self.detect_defaults: kwargs = self.modify_kwargs_for_default_detection(**kwargs) if self.visible_topics[topic]: if topic in self.groups: group = self.groups[topic] group.add_argument(*args, **kwargs) else: self.parser.add_argument(*args, **kwargs) else: kwargs["help"] = argparse.SUPPRESS self.parser.add_argument(*args, **kwargs) def modify_kwargs_for_default_detection(self, **kwargs): """Modify an arg so we can check if it was set by the user. Changes the parameters given to argparse when adding an argument so we can properly detect if the value was set by the user. :param dict kwargs: various argparse settings for this argument :returns: a modified versions of kwargs :rtype: dict """ action = kwargs.get("action", None) if action not in EXIT_ACTIONS: kwargs["action"] = ("store_true" if action in ZERO_ARG_ACTIONS else "store") kwargs["default"] = _Default() for param in ARGPARSE_PARAMS_TO_REMOVE: kwargs.pop(param, None) return kwargs def add_deprecated_argument(self, argument_name, num_args): """Adds a deprecated argument with the name argument_name. Deprecated arguments are not shown in the help. If they are used on the command line, a warning is shown stating that the argument is deprecated and no other action is taken. :param str argument_name: Name of deprecated argument. :param int nargs: Number of arguments the option takes. """ util.add_deprecated_argument( self.parser.add_argument, argument_name, num_args) def add_group(self, topic, verbs=(), **kwargs): """Create a new argument group. This method must be called once for every topic, however, calls to this function are left next to the argument definitions for clarity. :param str topic: Name of the new argument group. :param str verbs: List of subcommands that should be documented as part of this help group / topic :returns: The new argument group. :rtype: `HelpfulArgumentGroup` """ if self.visible_topics[topic]: self.groups[topic] = self.parser.add_argument_group(topic, **kwargs) if self.help_arg: for v in verbs: self.groups[topic].add_argument(v, help=VERB_HELP_MAP[v]["short"]) return HelpfulArgumentGroup(self, topic) def add_plugin_args(self, plugins): """ Let each of the plugins add its own command line arguments, which may or may not be displayed as help topics. """ for name, plugin_ep in six.iteritems(plugins): parser_or_group = self.add_group(name, description=plugin_ep.long_description) plugin_ep.plugin_cls.inject_parser_options(parser_or_group, name) def determine_help_topics(self, chosen_topic): """ The user may have requested help on a topic, return a dict of which topics to display. @chosen_topic has prescan_for_flag's return type :returns: dict """ # topics maps each topic to whether it should be documented by # argparse on the command line if chosen_topic == "auth": chosen_topic = "certonly" if chosen_topic == "everything": chosen_topic = "run" if chosen_topic == "all": return dict([(t, True) for t in self.help_topics]) elif not chosen_topic: return dict([(t, False) for t in self.help_topics]) else: return dict([(t, t == chosen_topic) for t in self.help_topics]) def _add_all_groups(helpful): helpful.add_group("automation", description="Flags for automating execution & other tweaks") helpful.add_group("security", description="Security parameters & server settings") helpful.add_group("testing", description="The following flags are meant for testing and integration purposes only.") helpful.add_group("paths", description="Flags for changing execution paths & servers") helpful.add_group("manage", description="Various subcommands and flags are available for managing your certificates:", verbs=["certificates", "delete", "renew", "revoke", "update_symlinks"]) # VERBS for verb, docs in VERB_HELP: name = docs.get("realname", verb) helpful.add_group(name, description=docs["opts"]) def prepare_and_parse_args(plugins, args, detect_defaults=False): # pylint: disable=too-many-statements """Returns parsed command line arguments. :param .PluginsRegistry plugins: available plugins :param list args: command line arguments with the program name removed :returns: parsed command line arguments :rtype: argparse.Namespace """ # pylint: disable=too-many-statements helpful = HelpfulArgumentParser(args, plugins, detect_defaults) _add_all_groups(helpful) # --help is automatically provided by argparse helpful.add( None, "-v", "--verbose", dest="verbose_count", action="count", default=flag_default("verbose_count"), help="This flag can be used " "multiple times to incrementally increase the verbosity of output, " "e.g. -vvv.") helpful.add( None, "-t", "--text", dest="text_mode", action="store_true", default=flag_default("text_mode"), help=argparse.SUPPRESS) helpful.add( None, "--max-log-backups", type=nonnegative_int, default=flag_default("max_log_backups"), help="Specifies the maximum number of backup logs that should " "be kept by Certbot's built in log rotation. Setting this " "flag to 0 disables log rotation entirely, causing " "Certbot to always append to the same log file.") helpful.add( [None, "automation", "run", "certonly", "enhance"], "-n", "--non-interactive", "--noninteractive", dest="noninteractive_mode", action="store_true", default=flag_default("noninteractive_mode"), help="Run without ever asking for user input. This may require " "additional command line flags; the client will try to explain " "which ones are required if it finds one missing") helpful.add( [None, "register", "run", "certonly", "enhance"], constants.FORCE_INTERACTIVE_FLAG, action="store_true", default=flag_default("force_interactive"), help="Force Certbot to be interactive even if it detects it's not " "being run in a terminal. This flag cannot be used with the " "renew subcommand.") helpful.add( [None, "run", "certonly", "certificates", "enhance"], "-d", "--domains", "--domain", dest="domains", metavar="DOMAIN", action=_DomainsAction, default=flag_default("domains"), help="Domain names to apply. For multiple domains you can use " "multiple -d flags or enter a comma separated list of domains " "as a parameter. The first domain provided will be the " "subject CN of the certificate, and all domains will be " "Subject Alternative Names on the certificate. " "The first domain will also be used in " "some software user interfaces and as the file paths for the " "certificate and related material unless otherwise " "specified or you already have a certificate with the same " "name. In the case of a name collision it will append a number " "like 0001 to the file path name. (default: Ask)") helpful.add( [None, "run", "certonly", "manage", "delete", "certificates", "renew", "enhance"], "--cert-name", dest="certname", metavar="CERTNAME", default=flag_default("certname"), help="Certificate name to apply. This name is used by Certbot for housekeeping " "and in file paths; it doesn't affect the content of the certificate itself. " "To see certificate names, run 'certbot certificates'. " "When creating a new certificate, specifies the new certificate's name. " "(default: the first provided domain or the name of an existing " "certificate on your system for the same domains)") helpful.add( [None, "testing", "renew", "certonly"], "--dry-run", action="store_true", dest="dry_run", default=flag_default("dry_run"), help="Perform a test run of the client, obtaining test (invalid) certificates" " but not saving them to disk. This can currently only be used" " with the 'certonly' and 'renew' subcommands. \nNote: Although --dry-run" " tries to avoid making any persistent changes on a system, it " " is not completely side-effect free: if used with webserver authenticator plugins" " like apache and nginx, it makes and then reverts temporary config changes" " in order to obtain test certificates, and reloads webservers to deploy and then" " roll back those changes. It also calls --pre-hook and --post-hook commands" " if they are defined because they may be necessary to accurately simulate" " renewal. --deploy-hook commands are not called.") helpful.add( ["register", "automation"], "--register-unsafely-without-email", action="store_true", default=flag_default("register_unsafely_without_email"), help="Specifying this flag enables registering an account with no " "email address. This is strongly discouraged, because in the " "event of key loss or account compromise you will irrevocably " "lose access to your account. You will also be unable to receive " "notice about impending expiration or revocation of your " "certificates. Updates to the Subscriber Agreement will still " "affect you, and will be effective 14 days after posting an " "update to the web site.") helpful.add( "register", "--update-registration", action="store_true", default=flag_default("update_registration"), help="With the register verb, indicates that details associated " "with an existing registration, such as the e-mail address, " "should be updated, rather than registering a new account.") helpful.add( ["register", "unregister", "automation"], "-m", "--email", default=flag_default("email"), help=config_help("email")) helpful.add(["register", "automation"], "--eff-email", action="store_true", default=flag_default("eff_email"), dest="eff_email", help="Share your e-mail address with EFF") helpful.add(["register", "automation"], "--no-eff-email", action="store_false", default=flag_default("eff_email"), dest="eff_email", help="Don't share your e-mail address with EFF") helpful.add( ["automation", "certonly", "run"], "--keep-until-expiring", "--keep", "--reinstall", dest="reinstall", action="store_true", default=flag_default("reinstall"), help="If the requested certificate matches an existing certificate, always keep the " "existing one until it is due for renewal (for the " "'run' subcommand this means reinstall the existing certificate). (default: Ask)") helpful.add( "automation", "--expand", action="store_true", default=flag_default("expand"), help="If an existing certificate is a strict subset of the requested names, " "always expand and replace it with the additional names. (default: Ask)") helpful.add( "automation", "--version", action="version", version="%(prog)s {0}".format(certbot.__version__), help="show program's version number and exit") helpful.add( ["automation", "renew"], "--force-renewal", "--renew-by-default", dest="renew_by_default", action="store_true", default=flag_default("renew_by_default"), help="If a certificate " "already exists for the requested domains, renew it now, " "regardless of whether it is near expiry. (Often " "--keep-until-expiring is more appropriate). Also implies " "--expand.") helpful.add( "automation", "--renew-with-new-domains", dest="renew_with_new_domains", action="store_true", default=flag_default("renew_with_new_domains"), help="If a " "certificate already exists for the requested certificate name " "but does not match the requested domains, renew it now, " "regardless of whether it is near expiry.") helpful.add( "automation", "--reuse-key", dest="reuse_key", action="store_true", default=flag_default("reuse_key"), help="When renewing, use the same private key as the existing " "certificate.") helpful.add( ["automation", "renew", "certonly"], "--allow-subset-of-names", action="store_true", default=flag_default("allow_subset_of_names"), help="When performing domain validation, do not consider it a failure " "if authorizations can not be obtained for a strict subset of " "the requested domains. This may be useful for allowing renewals for " "multiple domains to succeed even if some domains no longer point " "at this system. This option cannot be used with --csr.") helpful.add( "automation", "--agree-tos", dest="tos", action="store_true", default=flag_default("tos"), help="Agree to the ACME Subscriber Agreement (default: Ask)") helpful.add( ["unregister", "automation"], "--account", metavar="ACCOUNT_ID", default=flag_default("account"), help="Account ID to use") helpful.add( "automation", "--duplicate", dest="duplicate", action="store_true", default=flag_default("duplicate"), help="Allow making a certificate lineage that duplicates an existing one " "(both can be renewed in parallel)") helpful.add( "automation", "--os-packages-only", action="store_true", default=flag_default("os_packages_only"), help="(certbot-auto only) install OS package dependencies and then stop") helpful.add( "automation", "--no-self-upgrade", action="store_true", default=flag_default("no_self_upgrade"), help="(certbot-auto only) prevent the certbot-auto script from" " upgrading itself to newer released versions (default: Upgrade" " automatically)") helpful.add( "automation", "--no-bootstrap", action="store_true", default=flag_default("no_bootstrap"), help="(certbot-auto only) prevent the certbot-auto script from" " installing OS-level dependencies (default: Prompt to install " " OS-wide dependencies, but exit if the user says 'No')") helpful.add( ["automation", "renew", "certonly", "run"], "-q", "--quiet", dest="quiet", action="store_true", default=flag_default("quiet"), help="Silence all output except errors. Useful for automation via cron." " Implies --non-interactive.") # overwrites server, handled in HelpfulArgumentParser.parse_args() helpful.add(["testing", "revoke", "run"], "--test-cert", "--staging", dest="staging", action="store_true", default=flag_default("staging"), help="Use the staging server to obtain or revoke test (invalid) certificates; equivalent" " to --server " + constants.STAGING_URI) helpful.add( "testing", "--debug", action="store_true", default=flag_default("debug"), help="Show tracebacks in case of errors, and allow certbot-auto " "execution on experimental platforms") helpful.add( [None, "certonly", "run"], "--debug-challenges", action="store_true", default=flag_default("debug_challenges"), help="After setting up challenges, wait for user input before " "submitting to CA") helpful.add( "testing", "--no-verify-ssl", action="store_true", help=config_help("no_verify_ssl"), default=flag_default("no_verify_ssl")) helpful.add( ["testing", "standalone", "apache", "nginx"], "--tls-sni-01-port", type=int, default=flag_default("tls_sni_01_port"), help=config_help("tls_sni_01_port")) helpful.add( ["testing", "standalone"], "--tls-sni-01-address", default=flag_default("tls_sni_01_address"), help=config_help("tls_sni_01_address")) helpful.add( ["testing", "standalone", "manual"], "--http-01-port", type=int, dest="http01_port", default=flag_default("http01_port"), help=config_help("http01_port")) helpful.add( ["testing", "standalone"], "--http-01-address", dest="http01_address", default=flag_default("http01_address"), help=config_help("http01_address")) helpful.add( "testing", "--break-my-certs", action="store_true", default=flag_default("break_my_certs"), help="Be willing to replace or renew valid certificates with invalid " "(testing/staging) certificates") helpful.add( "security", "--rsa-key-size", type=int, metavar="N", default=flag_default("rsa_key_size"), help=config_help("rsa_key_size")) helpful.add( "security", "--must-staple", action="store_true", dest="must_staple", default=flag_default("must_staple"), help=config_help("must_staple")) helpful.add( ["security", "enhance"], "--redirect", action="store_true", dest="redirect", default=flag_default("redirect"), help="Automatically redirect all HTTP traffic to HTTPS for the newly " "authenticated vhost. (default: Ask)") helpful.add( "security", "--no-redirect", action="store_false", dest="redirect", default=flag_default("redirect"), help="Do not automatically redirect all HTTP traffic to HTTPS for the newly " "authenticated vhost. (default: Ask)") helpful.add( ["security", "enhance"], "--hsts", action="store_true", dest="hsts", default=flag_default("hsts"), help="Add the Strict-Transport-Security header to every HTTP response." " Forcing browser to always use SSL for the domain." " Defends against SSL Stripping.") helpful.add( "security", "--no-hsts", action="store_false", dest="hsts", default=flag_default("hsts"), help=argparse.SUPPRESS) helpful.add( ["security", "enhance"], "--uir", action="store_true", dest="uir", default=flag_default("uir"), help='Add the "Content-Security-Policy: upgrade-insecure-requests"' ' header to every HTTP response. Forcing the browser to use' ' https:// for every http:// resource.') helpful.add( "security", "--no-uir", action="store_false", dest="uir", default=flag_default("uir"), help=argparse.SUPPRESS) helpful.add( "security", "--staple-ocsp", action="store_true", dest="staple", default=flag_default("staple"), help="Enables OCSP Stapling. A valid OCSP response is stapled to" " the certificate that the server offers during TLS.") helpful.add( "security", "--no-staple-ocsp", action="store_false", dest="staple", default=flag_default("staple"), help=argparse.SUPPRESS) helpful.add( "security", "--strict-permissions", action="store_true", default=flag_default("strict_permissions"), help="Require that all configuration files are owned by the current " "user; only needed if your config is somewhere unsafe like /tmp/") helpful.add( ["manual", "standalone", "certonly", "renew"], "--preferred-challenges", dest="pref_challs", action=_PrefChallAction, default=flag_default("pref_challs"), help='A sorted, comma delimited list of the preferred challenge to ' 'use during authorization with the most preferred challenge ' 'listed first (Eg, "dns" or "tls-sni-01,http,dns"). ' 'Not all plugins support all challenges. See ' 'https://certbot.eff.org/docs/using.html#plugins for details. ' 'ACME Challenges are versioned, but if you pick "http" rather ' 'than "http-01", Certbot will select the latest version ' 'automatically.') helpful.add( "renew", "--pre-hook", help="Command to be run in a shell before obtaining any certificates." " Intended primarily for renewal, where it can be used to temporarily" " shut down a webserver that might conflict with the standalone" " plugin. This will only be called if a certificate is actually to be" " obtained/renewed. When renewing several certificates that have" " identical pre-hooks, only the first will be executed.") helpful.add( "renew", "--post-hook", help="Command to be run in a shell after attempting to obtain/renew" " certificates. Can be used to deploy renewed certificates, or to" " restart any servers that were stopped by --pre-hook. This is only" " run if an attempt was made to obtain/renew a certificate. If" " multiple renewed certificates have identical post-hooks, only" " one will be run.") helpful.add("renew", "--renew-hook", action=_RenewHookAction, help=argparse.SUPPRESS) helpful.add( "renew", "--deploy-hook", action=_DeployHookAction, help='Command to be run in a shell once for each successfully' ' issued certificate. For this command, the shell variable' ' $RENEWED_LINEAGE will point to the config live subdirectory' ' (for example, "/etc/letsencrypt/live/example.com") containing' ' the new certificates and keys; the shell variable' ' $RENEWED_DOMAINS will contain a space-delimited list of' ' renewed certificate domains (for example, "example.com' ' www.example.com"') helpful.add( "renew", "--disable-hook-validation", action="store_false", dest="validate_hooks", default=flag_default("validate_hooks"), help="Ordinarily the commands specified for" " --pre-hook/--post-hook/--deploy-hook will be checked for" " validity, to see if the programs being run are in the $PATH," " so that mistakes can be caught early, even when the hooks" " aren't being run just yet. The validation is rather" " simplistic and fails if you use more advanced shell" " constructs, so you can use this switch to disable it." " (default: False)") helpful.add( "renew", "--no-directory-hooks", action="store_false", default=flag_default("directory_hooks"), dest="directory_hooks", help="Disable running executables found in Certbot's hook directories" " during renewal. (default: False)") helpful.add( "renew", "--disable-renew-updates", action="store_true", default=flag_default("disable_renew_updates"), dest="disable_renew_updates", help="Disable automatic updates to your server configuration that" " would otherwise be done by the selected installer plugin, and triggered" " when the user executes \"certbot renew\", regardless of if the certificate" " is renewed. This setting does not apply to important TLS configuration" " updates.") helpful.add( "renew", "--no-autorenew", action="store_false", default=flag_default("autorenew"), dest="autorenew", help="Disable auto renewal of certificates.") helpful.add_deprecated_argument("--agree-dev-preview", 0) helpful.add_deprecated_argument("--dialog", 0) # Populate the command line parameters for new style enhancements enhancements.populate_cli(helpful.add) _create_subparsers(helpful) _paths_parser(helpful) # _plugins_parsing should be the last thing to act upon the main # parser (--help should display plugin-specific options last) _plugins_parsing(helpful, plugins) if not detect_defaults: global helpful_parser # pylint: disable=global-statement helpful_parser = helpful return helpful.parse_args() def _create_subparsers(helpful): helpful.add("config_changes", "--num", type=int, default=flag_default("num"), help="How many past revisions you want to be displayed") from certbot.client import sample_user_agent # avoid import loops helpful.add( None, "--user-agent", default=flag_default("user_agent"), help='Set a custom user agent string for the client. User agent strings allow ' 'the CA to collect high level statistics about success rates by OS, ' 'plugin and use case, and to know when to deprecate support for past Python ' "versions and flags. If you wish to hide this information from the Let's " 'Encrypt server, set this to "". ' '(default: {0}). The flags encoded in the user agent are: ' '--duplicate, --force-renew, --allow-subset-of-names, -n, and ' 'whether any hooks are set.'.format(sample_user_agent())) helpful.add( None, "--user-agent-comment", default=flag_default("user_agent_comment"), type=_user_agent_comment_type, help="Add a comment to the default user agent string. May be used when repackaging Certbot " "or calling it from another tool to allow additional statistical data to be collected." " Ignored if --user-agent is set. (Example: Foo-Wrapper/1.0)") helpful.add("certonly", "--csr", default=flag_default("csr"), type=read_file, help="Path to a Certificate Signing Request (CSR) in DER or PEM format." " Currently --csr only works with the 'certonly' subcommand.") helpful.add("revoke", "--reason", dest="reason", choices=CaseInsensitiveList(sorted(constants.REVOCATION_REASONS, key=constants.REVOCATION_REASONS.get)), action=_EncodeReasonAction, default=flag_default("reason"), help="Specify reason for revoking certificate. (default: unspecified)") helpful.add("revoke", "--delete-after-revoke", action="store_true", default=flag_default("delete_after_revoke"), help="Delete certificates after revoking them.") helpful.add("revoke", "--no-delete-after-revoke", action="store_false", dest="delete_after_revoke", default=flag_default("delete_after_revoke"), help="Do not delete certificates after revoking them. This " "option should be used with caution because the 'renew' " "subcommand will attempt to renew undeleted revoked " "certificates.") helpful.add("rollback", "--checkpoints", type=int, metavar="N", default=flag_default("rollback_checkpoints"), help="Revert configuration N number of checkpoints.") helpful.add("plugins", "--init", action="store_true", default=flag_default("init"), help="Initialize plugins.") helpful.add("plugins", "--prepare", action="store_true", default=flag_default("prepare"), help="Initialize and prepare plugins.") helpful.add("plugins", "--authenticators", action="append_const", dest="ifaces", default=flag_default("ifaces"), const=interfaces.IAuthenticator, help="Limit to authenticator plugins only.") helpful.add("plugins", "--installers", action="append_const", dest="ifaces", default=flag_default("ifaces"), const=interfaces.IInstaller, help="Limit to installer plugins only.") class CaseInsensitiveList(list): """A list that will ignore case when searching. This class is passed to the `choices` argument of `argparse.add_arguments` through the `helpful` wrapper. It is necessary due to special handling of command line arguments by `set_by_cli` in which the `type_func` is not applied.""" def __contains__(self, element): return super(CaseInsensitiveList, self).__contains__(element.lower()) def _paths_parser(helpful): add = helpful.add verb = helpful.verb if verb == "help": verb = helpful.help_arg cph = "Path to where certificate is saved (with auth --csr), installed from, or revoked." sections = ["paths", "install", "revoke", "certonly", "manage"] if verb == "certonly": add(sections, "--cert-path", type=os.path.abspath, default=flag_default("auth_cert_path"), help=cph) elif verb == "revoke": add(sections, "--cert-path", type=read_file, required=True, help=cph) else: add(sections, "--cert-path", type=os.path.abspath, help=cph) section = "paths" if verb in ("install", "revoke"): section = verb # revoke --key-path reads a file, install --key-path takes a string add(section, "--key-path", type=((verb == "revoke" and read_file) or os.path.abspath), help="Path to private key for certificate installation " "or revocation (if account key is missing)") default_cp = None if verb == "certonly": default_cp = flag_default("auth_chain_path") add(["paths", "install"], "--fullchain-path", default=default_cp, type=os.path.abspath, help="Accompanying path to a full certificate chain (certificate plus chain).") add("paths", "--chain-path", default=default_cp, type=os.path.abspath, help="Accompanying path to a certificate chain.") add("paths", "--config-dir", default=flag_default("config_dir"), help=config_help("config_dir")) add("paths", "--work-dir", default=flag_default("work_dir"), help=config_help("work_dir")) add("paths", "--logs-dir", default=flag_default("logs_dir"), help="Logs directory.") add("paths", "--server", default=flag_default("server"), help=config_help("server")) def _plugins_parsing(helpful, plugins): # It's nuts, but there are two "plugins" topics. Somehow this works helpful.add_group( "plugins", description="Plugin Selection: Certbot client supports an " "extensible plugins architecture. See '%(prog)s plugins' for a " "list of all installed plugins and their names. You can force " "a particular plugin by setting options provided below. Running " "--help will list flags specific to that plugin.") helpful.add("plugins", "--configurator", default=flag_default("configurator"), help="Name of the plugin that is both an authenticator and an installer." " Should not be used together with --authenticator or --installer. " "(default: Ask)") helpful.add("plugins", "-a", "--authenticator", default=flag_default("authenticator"), help="Authenticator plugin name.") helpful.add("plugins", "-i", "--installer", default=flag_default("installer"), help="Installer plugin name (also used to find domains).") helpful.add(["plugins", "certonly", "run", "install", "config_changes"], "--apache", action="store_true", default=flag_default("apache"), help="Obtain and install certificates using Apache") helpful.add(["plugins", "certonly", "run", "install", "config_changes"], "--nginx", action="store_true", default=flag_default("nginx"), help="Obtain and install certificates using Nginx") helpful.add(["plugins", "certonly"], "--standalone", action="store_true", default=flag_default("standalone"), help='Obtain certificates using a "standalone" webserver.') helpful.add(["plugins", "certonly"], "--manual", action="store_true", default=flag_default("manual"), help="Provide laborious manual instructions for obtaining a certificate") helpful.add(["plugins", "certonly"], "--webroot", action="store_true", default=flag_default("webroot"), help="Obtain certificates by placing files in a webroot directory.") helpful.add(["plugins", "certonly"], "--dns-cloudflare", action="store_true", default=flag_default("dns_cloudflare"), help=("Obtain certificates using a DNS TXT record (if you are " "using Cloudflare for DNS).")) helpful.add(["plugins", "certonly"], "--dns-cloudxns", action="store_true", default=flag_default("dns_cloudxns"), help=("Obtain certificates using a DNS TXT record (if you are " "using CloudXNS for DNS).")) helpful.add(["plugins", "certonly"], "--dns-digitalocean", action="store_true", default=flag_default("dns_digitalocean"), help=("Obtain certificates using a DNS TXT record (if you are " "using DigitalOcean for DNS).")) helpful.add(["plugins", "certonly"], "--dns-dnsimple", action="store_true", default=flag_default("dns_dnsimple"), help=("Obtain certificates using a DNS TXT record (if you are " "using DNSimple for DNS).")) helpful.add(["plugins", "certonly"], "--dns-dnsmadeeasy", action="store_true", default=flag_default("dns_dnsmadeeasy"), help=("Obtain certificates using a DNS TXT record (if you are" "using DNS Made Easy for DNS).")) helpful.add(["plugins", "certonly"], "--dns-gehirn", action="store_true", default=flag_default("dns_gehirn"), help=("Obtain certificates using a DNS TXT record " "(if you are using Gehirn Infrastracture Service for DNS).")) helpful.add(["plugins", "certonly"], "--dns-google", action="store_true", default=flag_default("dns_google"), help=("Obtain certificates using a DNS TXT record (if you are " "using Google Cloud DNS).")) helpful.add(["plugins", "certonly"], "--dns-linode", action="store_true", default=flag_default("dns_linode"), help=("Obtain certificates using a DNS TXT record (if you are " "using Linode for DNS).")) helpful.add(["plugins", "certonly"], "--dns-luadns", action="store_true", default=flag_default("dns_luadns"), help=("Obtain certificates using a DNS TXT record (if you are " "using LuaDNS for DNS).")) helpful.add(["plugins", "certonly"], "--dns-nsone", action="store_true", default=flag_default("dns_nsone"), help=("Obtain certificates using a DNS TXT record (if you are " "using NS1 for DNS).")) helpful.add(["plugins", "certonly"], "--dns-ovh", action="store_true", default=flag_default("dns_ovh"), help=("Obtain certificates using a DNS TXT record (if you are " "using OVH for DNS).")) helpful.add(["plugins", "certonly"], "--dns-rfc2136", action="store_true", default=flag_default("dns_rfc2136"), help="Obtain certificates using a DNS TXT record (if you are using BIND for DNS).") helpful.add(["plugins", "certonly"], "--dns-route53", action="store_true", default=flag_default("dns_route53"), help=("Obtain certificates using a DNS TXT record (if you are using Route53 for " "DNS).")) helpful.add(["plugins", "certonly"], "--dns-sakuracloud", action="store_true", default=flag_default("dns_sakuracloud"), help=("Obtain certificates using a DNS TXT record " "(if you are using Sakura Cloud for DNS).")) # things should not be reorder past/pre this comment: # plugins_group should be displayed in --help before plugin # specific groups (so that plugins_group.description makes sense) helpful.add_plugin_args(plugins) class _EncodeReasonAction(argparse.Action): """Action class for parsing revocation reason.""" def __call__(self, parser, namespace, reason, option_string=None): """Encodes the reason for certificate revocation.""" code = constants.REVOCATION_REASONS[reason.lower()] setattr(namespace, self.dest, code) class _DomainsAction(argparse.Action): """Action class for parsing domains.""" def __call__(self, parser, namespace, domain, option_string=None): """Just wrap add_domains in argparseese.""" add_domains(namespace, domain) def add_domains(args_or_config, domains): """Registers new domains to be used during the current client run. Domains are not added to the list of requested domains if they have already been registered. :param args_or_config: parsed command line arguments :type args_or_config: argparse.Namespace or configuration.NamespaceConfig :param str domain: one or more comma separated domains :returns: domains after they have been normalized and validated :rtype: `list` of `str` """ validated_domains = [] for domain in domains.split(","): domain = util.enforce_domain_sanity(domain.strip()) validated_domains.append(domain) if domain not in args_or_config.domains: args_or_config.domains.append(domain) return validated_domains class _PrefChallAction(argparse.Action): """Action class for parsing preferred challenges.""" def __call__(self, parser, namespace, pref_challs, option_string=None): try: challs = parse_preferred_challenges(pref_challs.split(",")) except errors.Error as error: raise argparse.ArgumentError(self, str(error)) namespace.pref_challs.extend(challs) def parse_preferred_challenges(pref_challs): """Translate and validate preferred challenges. :param pref_challs: list of preferred challenge types :type pref_challs: `list` of `str` :returns: validated list of preferred challenge types :rtype: `list` of `str` :raises errors.Error: if pref_challs is invalid """ aliases = {"dns": "dns-01", "http": "http-01", "tls-sni": "tls-sni-01"} challs = [c.strip() for c in pref_challs] challs = [aliases.get(c, c) for c in challs] unrecognized = ", ".join(name for name in challs if name not in challenges.Challenge.TYPES) if unrecognized: raise errors.Error( "Unrecognized challenges: {0}".format(unrecognized)) return challs def _user_agent_comment_type(value): if "(" in value or ")" in value: raise argparse.ArgumentTypeError("may not contain parentheses") return value class _DeployHookAction(argparse.Action): """Action class for parsing deploy hooks.""" def __call__(self, parser, namespace, values, option_string=None): renew_hook_set = namespace.deploy_hook != namespace.renew_hook if renew_hook_set and namespace.renew_hook != values: raise argparse.ArgumentError( self, "conflicts with --renew-hook value") namespace.deploy_hook = namespace.renew_hook = values class _RenewHookAction(argparse.Action): """Action class for parsing renew hooks.""" def __call__(self, parser, namespace, values, option_string=None): deploy_hook_set = namespace.deploy_hook is not None if deploy_hook_set and namespace.deploy_hook != values: raise argparse.ArgumentError( self, "conflicts with --deploy-hook value") namespace.renew_hook = values def nonnegative_int(value): """Converts value to an int and checks that it is not negative. This function should used as the type parameter for argparse arguments. :param str value: value provided on the command line :returns: integer representation of value :rtype: int :raises argparse.ArgumentTypeError: if value isn't a non-negative integer """ try: int_value = int(value) except ValueError: raise argparse.ArgumentTypeError("value must be an integer") if int_value < 0: raise argparse.ArgumentTypeError("value must be non-negative") return int_value certbot-0.27.0/certbot/crypto_util.py0000644000175000017500000003611513344054434020035 0ustar ericaerica00000000000000"""Certbot client crypto utility functions. .. todo:: Make the transition to use PSS rather than PKCS1_v1_5 when the server is capable of handling the signatures. """ import hashlib import logging import os import warnings import pyrfc3339 import six import zope.component from cryptography.exceptions import InvalidSignature from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric.ec import ECDSA from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey # https://github.com/python/typeshed/tree/master/third_party/2/cryptography from cryptography import x509 # type: ignore from OpenSSL import crypto from OpenSSL import SSL # type: ignore from acme import crypto_util as acme_crypto_util from acme.magic_typing import IO # pylint: disable=unused-import, no-name-in-module from certbot import errors from certbot import interfaces from certbot import util logger = logging.getLogger(__name__) # High level functions def init_save_key(key_size, key_dir, keyname="key-certbot.pem"): """Initializes and saves a privkey. Inits key and saves it in PEM format on the filesystem. .. note:: keyname is the attempted filename, it may be different if a file already exists at the path. :param int key_size: RSA key size in bits :param str key_dir: Key save directory. :param str keyname: Filename of key :returns: Key :rtype: :class:`certbot.util.Key` :raises ValueError: If unable to generate the key given key_size. """ try: key_pem = make_key(key_size) except ValueError as err: logger.error("", exc_info=True) raise err config = zope.component.getUtility(interfaces.IConfig) # Save file util.make_or_verify_dir(key_dir, 0o700, os.geteuid(), config.strict_permissions) key_f, key_path = util.unique_file( os.path.join(key_dir, keyname), 0o600, "wb") with key_f: key_f.write(key_pem) logger.debug("Generating key (%d bits): %s", key_size, key_path) return util.Key(key_path, key_pem) def init_save_csr(privkey, names, path): """Initialize a CSR with the given private key. :param privkey: Key to include in the CSR :type privkey: :class:`certbot.util.Key` :param set names: `str` names to include in the CSR :param str path: Certificate save directory. :returns: CSR :rtype: :class:`certbot.util.CSR` """ config = zope.component.getUtility(interfaces.IConfig) csr_pem = acme_crypto_util.make_csr( privkey.pem, names, must_staple=config.must_staple) # Save CSR util.make_or_verify_dir(path, 0o755, os.geteuid(), config.strict_permissions) csr_f, csr_filename = util.unique_file( os.path.join(path, "csr-certbot.pem"), 0o644, "wb") with csr_f: csr_f.write(csr_pem) logger.debug("Creating CSR: %s", csr_filename) return util.CSR(csr_filename, csr_pem, "pem") # WARNING: the csr and private key file are possible attack vectors for TOCTOU # We should either... # A. Do more checks to verify that the CSR is trusted/valid # B. Audit the parsing code for vulnerabilities def valid_csr(csr): """Validate CSR. Check if `csr` is a valid CSR for the given domains. :param str csr: CSR in PEM. :returns: Validity of CSR. :rtype: bool """ try: req = crypto.load_certificate_request( crypto.FILETYPE_PEM, csr) return req.verify(req.get_pubkey()) except crypto.Error: logger.debug("", exc_info=True) return False def csr_matches_pubkey(csr, privkey): """Does private key correspond to the subject public key in the CSR? :param str csr: CSR in PEM. :param str privkey: Private key file contents (PEM) :returns: Correspondence of private key to CSR subject public key. :rtype: bool """ req = crypto.load_certificate_request( crypto.FILETYPE_PEM, csr) pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, privkey) try: return req.verify(pkey) except crypto.Error: logger.debug("", exc_info=True) return False def import_csr_file(csrfile, data): """Import a CSR file, which can be either PEM or DER. :param str csrfile: CSR filename :param str data: contents of the CSR file :returns: (`crypto.FILETYPE_PEM`, util.CSR object representing the CSR, list of domains requested in the CSR) :rtype: tuple """ PEM = crypto.FILETYPE_PEM load = crypto.load_certificate_request try: # Try to parse as DER first, then fall back to PEM. csr = load(crypto.FILETYPE_ASN1, data) except crypto.Error: try: csr = load(PEM, data) except crypto.Error: raise errors.Error("Failed to parse CSR file: {0}".format(csrfile)) domains = _get_names_from_loaded_cert_or_req(csr) # Internally we always use PEM, so re-encode as PEM before returning. data_pem = crypto.dump_certificate_request(PEM, csr) return PEM, util.CSR(file=csrfile, data=data_pem, form="pem"), domains def make_key(bits): """Generate PEM encoded RSA key. :param int bits: Number of bits, at least 1024. :returns: new RSA key in PEM form with specified number of bits :rtype: str """ assert bits >= 1024 # XXX key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, bits) return crypto.dump_privatekey(crypto.FILETYPE_PEM, key) def valid_privkey(privkey): """Is valid RSA private key? :param str privkey: Private key file contents in PEM :returns: Validity of private key. :rtype: bool """ try: return crypto.load_privatekey( crypto.FILETYPE_PEM, privkey).check() except (TypeError, crypto.Error): return False def verify_renewable_cert(renewable_cert): """For checking that your certs were not corrupted on disk. Several things are checked: 1. Signature verification for the cert. 2. That fullchain matches cert and chain when concatenated. 3. Check that the private key matches the certificate. :param `.storage.RenewableCert` renewable_cert: cert to verify :raises errors.Error: If verification fails. """ verify_renewable_cert_sig(renewable_cert) verify_fullchain(renewable_cert) verify_cert_matches_priv_key(renewable_cert.cert, renewable_cert.privkey) def verify_renewable_cert_sig(renewable_cert): """ Verifies the signature of a `.storage.RenewableCert` object. :param `.storage.RenewableCert` renewable_cert: cert to verify :raises errors.Error: If signature verification fails. """ try: with open(renewable_cert.chain, 'rb') as chain_file: # type: IO[bytes] chain = x509.load_pem_x509_certificate(chain_file.read(), default_backend()) with open(renewable_cert.cert, 'rb') as cert_file: # type: IO[bytes] cert = x509.load_pem_x509_certificate(cert_file.read(), default_backend()) pk = chain.public_key() with warnings.catch_warnings(): warnings.simplefilter("ignore") if isinstance(pk, RSAPublicKey): # https://github.com/python/typeshed/blob/master/third_party/2/cryptography/hazmat/primitives/asymmetric/rsa.pyi verifier = pk.verifier( # type: ignore cert.signature, PKCS1v15(), cert.signature_hash_algorithm ) verifier.update(cert.tbs_certificate_bytes) verifier.verify() elif isinstance(pk, EllipticCurvePublicKey): verifier = pk.verifier( cert.signature, ECDSA(cert.signature_hash_algorithm) ) verifier.update(cert.tbs_certificate_bytes) verifier.verify() else: raise errors.Error("Unsupported public key type") except (IOError, ValueError, InvalidSignature) as e: error_str = "verifying the signature of the cert located at {0} has failed. \ Details: {1}".format(renewable_cert.cert, e) logger.exception(error_str) raise errors.Error(error_str) def verify_cert_matches_priv_key(cert_path, key_path): """ Verifies that the private key and cert match. :param str cert_path: path to a cert in PEM format :param str key_path: path to a private key file :raises errors.Error: If they don't match. """ try: context = SSL.Context(SSL.SSLv23_METHOD) context.use_certificate_file(cert_path) context.use_privatekey_file(key_path) context.check_privatekey() except (IOError, SSL.Error) as e: error_str = "verifying the cert located at {0} matches the \ private key located at {1} has failed. \ Details: {2}".format(cert_path, key_path, e) logger.exception(error_str) raise errors.Error(error_str) def verify_fullchain(renewable_cert): """ Verifies that fullchain is indeed cert concatenated with chain. :param `.storage.RenewableCert` renewable_cert: cert to verify :raises errors.Error: If cert and chain do not combine to fullchain. """ try: with open(renewable_cert.chain) as chain_file: # type: IO[str] chain = chain_file.read() with open(renewable_cert.cert) as cert_file: # type: IO[str] cert = cert_file.read() with open(renewable_cert.fullchain) as fullchain_file: # type: IO[str] fullchain = fullchain_file.read() if (cert + chain) != fullchain: error_str = "fullchain does not match cert + chain for {0}!" error_str = error_str.format(renewable_cert.lineagename) raise errors.Error(error_str) except IOError as e: error_str = "reading one of cert, chain, or fullchain has failed: {0}".format(e) logger.exception(error_str) raise errors.Error(error_str) except errors.Error as e: raise e def pyopenssl_load_certificate(data): """Load PEM/DER certificate. :raises errors.Error: """ openssl_errors = [] for file_type in (crypto.FILETYPE_PEM, crypto.FILETYPE_ASN1): try: return crypto.load_certificate(file_type, data), file_type except crypto.Error as error: # TODO: other errors? openssl_errors.append(error) raise errors.Error("Unable to load: {0}".format(",".join( str(error) for error in openssl_errors))) def _load_cert_or_req(cert_or_req_str, load_func, typ=crypto.FILETYPE_PEM): try: return load_func(typ, cert_or_req_str) except crypto.Error: logger.error("", exc_info=True) raise def _get_sans_from_cert_or_req(cert_or_req_str, load_func, typ=crypto.FILETYPE_PEM): # pylint: disable=protected-access return acme_crypto_util._pyopenssl_cert_or_req_san(_load_cert_or_req( cert_or_req_str, load_func, typ)) def get_sans_from_cert(cert, typ=crypto.FILETYPE_PEM): """Get a list of Subject Alternative Names from a certificate. :param str cert: Certificate (encoded). :param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1` :returns: A list of Subject Alternative Names. :rtype: list """ return _get_sans_from_cert_or_req( cert, crypto.load_certificate, typ) def _get_names_from_cert_or_req(cert_or_req, load_func, typ): loaded_cert_or_req = _load_cert_or_req(cert_or_req, load_func, typ) return _get_names_from_loaded_cert_or_req(loaded_cert_or_req) def _get_names_from_loaded_cert_or_req(loaded_cert_or_req): # pylint: disable=protected-access return acme_crypto_util._pyopenssl_cert_or_req_all_names(loaded_cert_or_req) def get_names_from_cert(csr, typ=crypto.FILETYPE_PEM): """Get a list of domains from a cert, including the CN if it is set. :param str cert: Certificate (encoded). :param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1` :returns: A list of domain names. :rtype: list """ return _get_names_from_cert_or_req( csr, crypto.load_certificate, typ) def dump_pyopenssl_chain(chain, filetype=crypto.FILETYPE_PEM): """Dump certificate chain into a bundle. :param list chain: List of `crypto.X509` (or wrapped in :class:`josepy.util.ComparableX509`). """ # XXX: returns empty string when no chain is available, which # shuts up RenewableCert, but might not be the best solution... return acme_crypto_util.dump_pyopenssl_chain(chain, filetype) def notBefore(cert_path): """When does the cert at cert_path start being valid? :param str cert_path: path to a cert in PEM format :returns: the notBefore value from the cert at cert_path :rtype: :class:`datetime.datetime` """ return _notAfterBefore(cert_path, crypto.X509.get_notBefore) def notAfter(cert_path): """When does the cert at cert_path stop being valid? :param str cert_path: path to a cert in PEM format :returns: the notAfter value from the cert at cert_path :rtype: :class:`datetime.datetime` """ return _notAfterBefore(cert_path, crypto.X509.get_notAfter) def _notAfterBefore(cert_path, method): """Internal helper function for finding notbefore/notafter. :param str cert_path: path to a cert in PEM format :param function method: one of ``crypto.X509.get_notBefore`` or ``crypto.X509.get_notAfter`` :returns: the notBefore or notAfter value from the cert at cert_path :rtype: :class:`datetime.datetime` """ # pylint: disable=redefined-outer-name with open(cert_path) as f: x509 = crypto.load_certificate(crypto.FILETYPE_PEM, f.read()) # pyopenssl always returns bytes timestamp = method(x509) reformatted_timestamp = [timestamp[0:4], b"-", timestamp[4:6], b"-", timestamp[6:8], b"T", timestamp[8:10], b":", timestamp[10:12], b":", timestamp[12:]] timestamp_str = b"".join(reformatted_timestamp) # pyrfc3339 uses "native" strings. That is, bytes on Python 2 and unicode # on Python 3 if six.PY3: timestamp_str = timestamp_str.decode('ascii') return pyrfc3339.parse(timestamp_str) def sha256sum(filename): """Compute a sha256sum of a file. :param str filename: path to the file whose hash will be computed :returns: sha256 digest of the file in hexadecimal :rtype: str """ sha256 = hashlib.sha256() with open(filename, 'rb') as f: sha256.update(f.read()) return sha256.hexdigest() def cert_and_chain_from_fullchain(fullchain_pem): """Split fullchain_pem into cert_pem and chain_pem :param str fullchain_pem: concatenated cert + chain :returns: tuple of string cert_pem and chain_pem :rtype: tuple """ cert = crypto.dump_certificate(crypto.FILETYPE_PEM, crypto.load_certificate(crypto.FILETYPE_PEM, fullchain_pem)).decode() chain = fullchain_pem[len(cert):].lstrip() return (cert, chain) certbot-0.27.0/certbot/updater.py0000644000175000017500000000756213344054434017130 0ustar ericaerica00000000000000"""Updaters run at renewal""" import logging from certbot import errors from certbot import interfaces from certbot.plugins import selection as plug_sel import certbot.plugins.enhancements as enhancements logger = logging.getLogger(__name__) def run_generic_updaters(config, lineage, plugins): """Run updaters that the plugin supports :param config: Configuration object :type config: interfaces.IConfig :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param plugins: List of plugins :type plugins: `list` of `str` :returns: `None` :rtype: None """ if config.dry_run: logger.debug("Skipping updaters in dry-run mode.") return try: installer = plug_sel.get_unprepared_installer(config, plugins) except errors.Error as e: logger.warning("Could not choose appropriate plugin for updaters: %s", e) return if installer: _run_updaters(lineage, installer, config) _run_enhancement_updaters(lineage, installer, config) def run_renewal_deployer(config, lineage, installer): """Helper function to run deployer interface method if supported by the used installer plugin. :param config: Configuration object :type config: interfaces.IConfig :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.IInstaller :returns: `None` :rtype: None """ if config.dry_run: logger.debug("Skipping renewal deployer in dry-run mode.") return if not config.disable_renew_updates and isinstance(installer, interfaces.RenewDeployer): installer.renew_deploy(lineage) _run_enhancement_deployers(lineage, installer, config) def _run_updaters(lineage, installer, config): """Helper function to run the updater interface methods if supported by the used installer plugin. :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.IInstaller :returns: `None` :rtype: None """ if not config.disable_renew_updates: if isinstance(installer, interfaces.GenericUpdater): installer.generic_updates(lineage) def _run_enhancement_updaters(lineage, installer, config): """Iterates through known enhancement interfaces. If the installer implements an enhancement interface and the enhance interface has an updater method, the updater method gets run. :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.IInstaller :param config: Configuration object :type config: interfaces.IConfig """ if config.disable_renew_updates: return for enh in enhancements._INDEX: # pylint: disable=protected-access if isinstance(installer, enh["class"]) and enh["updater_function"]: getattr(installer, enh["updater_function"])(lineage) def _run_enhancement_deployers(lineage, installer, config): """Iterates through known enhancement interfaces. If the installer implements an enhancement interface and the enhance interface has an deployer method, the deployer method gets run. :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.IInstaller :param config: Configuration object :type config: interfaces.IConfig """ if config.disable_renew_updates: return for enh in enhancements._INDEX: # pylint: disable=protected-access if isinstance(installer, enh["class"]) and enh["deployer_function"]: getattr(installer, enh["deployer_function"])(lineage) certbot-0.27.0/certbot/reverter.py0000644000175000017500000005642113344054434017320 0ustar ericaerica00000000000000"""Reverter class saves configuration checkpoints and allows for recovery.""" import csv import glob import logging import os import shutil import time import traceback import six import zope.component from certbot import constants from certbot import errors from certbot import interfaces from certbot import util logger = logging.getLogger(__name__) class Reverter(object): """Reverter Class - save and revert configuration checkpoints. This class can be used by the plugins, especially Installers, to undo changes made to the user's system. Modifications to files and commands to do undo actions taken by the plugin should be registered with this class before the action is taken. Once a change has been registered with this class, there are three states the change can be in. First, the change can be a temporary change. This should be used for changes that will soon be reverted, such as config changes for the purpose of solving a challenge. Changes are added to this state through calls to :func:`~add_to_temp_checkpoint` and reverted when :func:`~revert_temporary_config` or :func:`~recovery_routine` is called. The second state a change can be in is in progress. These changes are not temporary, however, they also have not been finalized in a checkpoint. A change must become in progress before it can be finalized. Changes are added to this state through calls to :func:`~add_to_checkpoint` and reverted when :func:`~recovery_routine` is called. The last state a change can be in is finalized in a checkpoint. A change is put into this state by first becoming an in progress change and then calling :func:`~finalize_checkpoint`. Changes in this state can be reverted through calls to :func:`~rollback_checkpoints`. As a final note, creating new files and registering undo commands are handled specially and use the methods :func:`~register_file_creation` and :func:`~register_undo_command` respectively. Both of these methods can be used to create either temporary or in progress changes. .. note:: Consider moving everything over to CSV format. :param config: Configuration. :type config: :class:`certbot.interfaces.IConfig` """ def __init__(self, config): self.config = config util.make_or_verify_dir( config.backup_dir, constants.CONFIG_DIRS_MODE, os.geteuid(), self.config.strict_permissions) def revert_temporary_config(self): """Reload users original configuration files after a temporary save. This function should reinstall the users original configuration files for all saves with temporary=True :raises .ReverterError: when unable to revert config """ if os.path.isdir(self.config.temp_checkpoint_dir): try: self._recover_checkpoint(self.config.temp_checkpoint_dir) except errors.ReverterError: # We have a partial or incomplete recovery logger.critical( "Incomplete or failed recovery for %s", self.config.temp_checkpoint_dir, ) raise errors.ReverterError("Unable to revert temporary config") def rollback_checkpoints(self, rollback=1): """Revert 'rollback' number of configuration checkpoints. :param int rollback: Number of checkpoints to reverse. A str num will be cast to an integer. So "2" is also acceptable. :raises .ReverterError: if there is a problem with the input or if the function is unable to correctly revert the configuration checkpoints """ try: rollback = int(rollback) except ValueError: logger.error("Rollback argument must be a positive integer") raise errors.ReverterError("Invalid Input") # Sanity check input if rollback < 0: logger.error("Rollback argument must be a positive integer") raise errors.ReverterError("Invalid Input") backups = os.listdir(self.config.backup_dir) backups.sort() if not backups: logger.warning( "Certbot hasn't modified your configuration, so rollback " "isn't available.") elif len(backups) < rollback: logger.warning("Unable to rollback %d checkpoints, only %d exist", rollback, len(backups)) while rollback > 0 and backups: cp_dir = os.path.join(self.config.backup_dir, backups.pop()) try: self._recover_checkpoint(cp_dir) except errors.ReverterError: logger.critical("Failed to load checkpoint during rollback") raise errors.ReverterError( "Unable to load checkpoint during rollback") rollback -= 1 def view_config_changes(self, for_logging=False, num=None): """Displays all saved checkpoints. All checkpoints are printed by :meth:`certbot.interfaces.IDisplay.notification`. .. todo:: Decide on a policy for error handling, OSError IOError... :raises .errors.ReverterError: If invalid directory structure. """ backups = os.listdir(self.config.backup_dir) backups.sort(reverse=True) if num: backups = backups[:num] if not backups: logger.info("Certbot has not saved backups of your configuration") return # Make sure there isn't anything unexpected in the backup folder # There should only be timestamped (float) directories try: for bkup in backups: float(bkup) except ValueError: raise errors.ReverterError( "Invalid directories in {0}".format(self.config.backup_dir)) output = [] for bkup in backups: output.append(time.ctime(float(bkup))) cur_dir = os.path.join(self.config.backup_dir, bkup) with open(os.path.join(cur_dir, "CHANGES_SINCE")) as changes_fd: output.append(changes_fd.read()) output.append("Affected files:") with open(os.path.join(cur_dir, "FILEPATHS")) as paths_fd: filepaths = paths_fd.read().splitlines() for path in filepaths: output.append(" {0}".format(path)) if os.path.isfile(os.path.join(cur_dir, "NEW_FILES")): with open(os.path.join(cur_dir, "NEW_FILES")) as new_fd: output.append("New Configuration Files:") filepaths = new_fd.read().splitlines() for path in filepaths: output.append(" {0}".format(path)) output.append(os.linesep) if for_logging: return os.linesep.join(output) zope.component.getUtility(interfaces.IDisplay).notification( os.linesep.join(output), force_interactive=True, pause=False) def add_to_temp_checkpoint(self, save_files, save_notes): """Add files to temporary checkpoint. :param set save_files: set of filepaths to save :param str save_notes: notes about changes during the save """ self._add_to_checkpoint_dir( self.config.temp_checkpoint_dir, save_files, save_notes) def add_to_checkpoint(self, save_files, save_notes): """Add files to a permanent checkpoint. :param set save_files: set of filepaths to save :param str save_notes: notes about changes during the save """ # Check to make sure we are not overwriting a temp file self._check_tempfile_saves(save_files) self._add_to_checkpoint_dir( self.config.in_progress_dir, save_files, save_notes) def _add_to_checkpoint_dir(self, cp_dir, save_files, save_notes): """Add save files to checkpoint directory. :param str cp_dir: Checkpoint directory filepath :param set save_files: set of files to save :param str save_notes: notes about changes made during the save :raises IOError: if unable to open cp_dir + FILEPATHS file :raises .ReverterError: if unable to add checkpoint """ util.make_or_verify_dir( cp_dir, constants.CONFIG_DIRS_MODE, os.geteuid(), self.config.strict_permissions) op_fd, existing_filepaths = self._read_and_append( os.path.join(cp_dir, "FILEPATHS")) idx = len(existing_filepaths) for filename in save_files: # No need to copy/index already existing files # The oldest copy already exists in the directory... if filename not in existing_filepaths: # Tag files with index so multiple files can # have the same filename logger.debug("Creating backup of %s", filename) try: shutil.copy2(filename, os.path.join( cp_dir, os.path.basename(filename) + "_" + str(idx))) op_fd.write(filename + os.linesep) # http://stackoverflow.com/questions/4726260/effective-use-of-python-shutil-copy2 except IOError: op_fd.close() logger.error( "Unable to add file %s to checkpoint %s", filename, cp_dir) raise errors.ReverterError( "Unable to add file {0} to checkpoint " "{1}".format(filename, cp_dir)) idx += 1 op_fd.close() with open(os.path.join(cp_dir, "CHANGES_SINCE"), "a") as notes_fd: notes_fd.write(save_notes) def _read_and_append(self, filepath): # pylint: disable=no-self-use """Reads the file lines and returns a file obj. Read the file returning the lines, and a pointer to the end of the file. """ # Open up filepath differently depending on if it already exists if os.path.isfile(filepath): op_fd = open(filepath, "r+") lines = op_fd.read().splitlines() else: lines = [] op_fd = open(filepath, "w") return op_fd, lines def _recover_checkpoint(self, cp_dir): """Recover a specific checkpoint. Recover a specific checkpoint provided by cp_dir Note: this function does not reload augeas. :param str cp_dir: checkpoint directory file path :raises errors.ReverterError: If unable to recover checkpoint """ # Undo all commands if os.path.isfile(os.path.join(cp_dir, "COMMANDS")): self._run_undo_commands(os.path.join(cp_dir, "COMMANDS")) # Revert all changed files if os.path.isfile(os.path.join(cp_dir, "FILEPATHS")): try: with open(os.path.join(cp_dir, "FILEPATHS")) as paths_fd: filepaths = paths_fd.read().splitlines() for idx, path in enumerate(filepaths): shutil.copy2(os.path.join( cp_dir, os.path.basename(path) + "_" + str(idx)), path) except (IOError, OSError): # This file is required in all checkpoints. logger.error("Unable to recover files from %s", cp_dir) raise errors.ReverterError( "Unable to recover files from %s" % cp_dir) # Remove any newly added files if they exist self._remove_contained_files(os.path.join(cp_dir, "NEW_FILES")) try: shutil.rmtree(cp_dir) except OSError: logger.error("Unable to remove directory: %s", cp_dir) raise errors.ReverterError( "Unable to remove directory: %s" % cp_dir) def _run_undo_commands(self, filepath): # pylint: disable=no-self-use """Run all commands in a file.""" # NOTE: csv module uses native strings. That is, bytes on Python 2 and # unicode on Python 3 with open(filepath, 'r') as csvfile: csvreader = csv.reader(csvfile) for command in reversed(list(csvreader)): try: util.run_script(command) except errors.SubprocessError: logger.error( "Unable to run undo command: %s", " ".join(command)) def _check_tempfile_saves(self, save_files): """Verify save isn't overwriting any temporary files. :param set save_files: Set of files about to be saved. :raises certbot.errors.ReverterError: when save is attempting to overwrite a temporary file. """ protected_files = [] # Get temp modified files temp_path = os.path.join(self.config.temp_checkpoint_dir, "FILEPATHS") if os.path.isfile(temp_path): with open(temp_path, "r") as protected_fd: protected_files.extend(protected_fd.read().splitlines()) # Get temp new files new_path = os.path.join(self.config.temp_checkpoint_dir, "NEW_FILES") if os.path.isfile(new_path): with open(new_path, "r") as protected_fd: protected_files.extend(protected_fd.read().splitlines()) # Verify no save_file is in protected_files for filename in protected_files: if filename in save_files: raise errors.ReverterError( "Attempting to overwrite challenge " "file - %s" % filename) def register_file_creation(self, temporary, *files): r"""Register the creation of all files during certbot execution. Call this method before writing to the file to make sure that the file will be cleaned up if the program exits unexpectedly. (Before a save occurs) :param bool temporary: If the file creation registry is for a temp or permanent save. :param \*files: file paths (str) to be registered :raises certbot.errors.ReverterError: If call does not contain necessary parameters or if the file creation is unable to be registered. """ # Make sure some files are provided... as this is an error # Made this mistake in my initial implementation of apache.dvsni.py if not files: raise errors.ReverterError("Forgot to provide files to registration call") cp_dir = self._get_cp_dir(temporary) # Append all new files (that aren't already registered) new_fd = None try: new_fd, ex_files = self._read_and_append(os.path.join(cp_dir, "NEW_FILES")) for path in files: if path not in ex_files: new_fd.write("{0}{1}".format(path, os.linesep)) except (IOError, OSError): logger.error("Unable to register file creation(s) - %s", files) raise errors.ReverterError( "Unable to register file creation(s) - {0}".format(files)) finally: if new_fd is not None: new_fd.close() def register_undo_command(self, temporary, command): """Register a command to be run to undo actions taken. .. warning:: This function does not enforce order of operations in terms of file modification vs. command registration. All undo commands are run first before all normal files are reverted to their previous state. If you need to maintain strict order, you may create checkpoints before and after the the command registration. This function may be improved in the future based on demand. :param bool temporary: Whether the command should be saved in the IN_PROGRESS or TEMPORARY checkpoints. :param command: Command to be run. :type command: list of str """ commands_fp = os.path.join(self._get_cp_dir(temporary), "COMMANDS") command_file = None try: if os.path.isfile(commands_fp): command_file = open(commands_fp, "a") else: command_file = open(commands_fp, "w") csvwriter = csv.writer(command_file) csvwriter.writerow(command) except (IOError, OSError): logger.error("Unable to register undo command") raise errors.ReverterError( "Unable to register undo command.") finally: if command_file is not None: command_file.close() def _get_cp_dir(self, temporary): """Return the proper reverter directory.""" if temporary: cp_dir = self.config.temp_checkpoint_dir else: cp_dir = self.config.in_progress_dir util.make_or_verify_dir( cp_dir, constants.CONFIG_DIRS_MODE, os.geteuid(), self.config.strict_permissions) return cp_dir def recovery_routine(self): """Revert configuration to most recent finalized checkpoint. Remove all changes (temporary and permanent) that have not been finalized. This is useful to protect against crashes and other execution interruptions. :raises .errors.ReverterError: If unable to recover the configuration """ # First, any changes found in IConfig.temp_checkpoint_dir are removed, # then IN_PROGRESS changes are removed The order is important. # IN_PROGRESS is unable to add files that are already added by a TEMP # change. Thus TEMP must be rolled back first because that will be the # 'latest' occurrence of the file. self.revert_temporary_config() if os.path.isdir(self.config.in_progress_dir): try: self._recover_checkpoint(self.config.in_progress_dir) except errors.ReverterError: # We have a partial or incomplete recovery logger.critical("Incomplete or failed recovery for IN_PROGRESS " "checkpoint - %s", self.config.in_progress_dir) raise errors.ReverterError( "Incomplete or failed recovery for IN_PROGRESS checkpoint " "- %s" % self.config.in_progress_dir) def _remove_contained_files(self, file_list): # pylint: disable=no-self-use """Erase all files contained within file_list. :param str file_list: file containing list of file paths to be deleted :returns: Success :rtype: bool :raises certbot.errors.ReverterError: If all files within file_list cannot be removed """ # Check to see that file exists to differentiate can't find file_list # and can't remove filepaths within file_list errors. if not os.path.isfile(file_list): return False try: with open(file_list, "r") as list_fd: filepaths = list_fd.read().splitlines() for path in filepaths: # Files are registered before they are added... so # check to see if file exists first if os.path.lexists(path): os.remove(path) else: logger.warning( "File: %s - Could not be found to be deleted %s - " "Certbot probably shut down unexpectedly", os.linesep, path) except (IOError, OSError): logger.critical( "Unable to remove filepaths contained within %s", file_list) raise errors.ReverterError( "Unable to remove filepaths contained within " "{0}".format(file_list)) return True def finalize_checkpoint(self, title): """Finalize the checkpoint. Timestamps and permanently saves all changes made through the use of :func:`~add_to_checkpoint` and :func:`~register_file_creation` :param str title: Title describing checkpoint :raises certbot.errors.ReverterError: when the checkpoint is not able to be finalized. """ # Check to make sure an "in progress" directory exists if not os.path.isdir(self.config.in_progress_dir): return changes_since_path = os.path.join(self.config.in_progress_dir, "CHANGES_SINCE") changes_since_tmp_path = os.path.join(self.config.in_progress_dir, "CHANGES_SINCE.tmp") if not os.path.exists(changes_since_path): logger.info("Rollback checkpoint is empty (no changes made?)") with open(changes_since_path, 'w') as f: f.write("No changes\n") # Add title to self.config.in_progress_dir CHANGES_SINCE try: with open(changes_since_tmp_path, "w") as changes_tmp: changes_tmp.write("-- %s --\n" % title) with open(changes_since_path, "r") as changes_orig: changes_tmp.write(changes_orig.read()) # Move self.config.in_progress_dir to Backups directory shutil.move(changes_since_tmp_path, changes_since_path) except (IOError, OSError): logger.error("Unable to finalize checkpoint - adding title") logger.debug("Exception was:\n%s", traceback.format_exc()) raise errors.ReverterError("Unable to add title") # rename the directory as a timestamp self._timestamp_progress_dir() def _checkpoint_timestamp(self): "Determine the timestamp of the checkpoint, enforcing monotonicity." timestamp = str(time.time()) others = glob.glob(os.path.join(self.config.backup_dir, "[0-9]*")) others = [os.path.basename(d) for d in others] others.append(timestamp) others.sort() if others[-1] != timestamp: timetravel = str(float(others[-1]) + 1) logger.warning("Current timestamp %s does not correspond to newest reverter " "checkpoint; your clock probably jumped. Time travelling to %s", timestamp, timetravel) timestamp = timetravel elif len(others) > 1 and others[-2] == timestamp: # It is possible if the checkpoints are made extremely quickly # that will result in a name collision. logger.debug("Race condition with timestamp %s, incrementing by 0.01", timestamp) timetravel = str(float(others[-1]) + 0.01) timestamp = timetravel return timestamp def _timestamp_progress_dir(self): """Timestamp the checkpoint.""" # It is possible save checkpoints faster than 1 per second resulting in # collisions in the naming convention. for _ in six.moves.range(2): timestamp = self._checkpoint_timestamp() final_dir = os.path.join(self.config.backup_dir, timestamp) try: os.rename(self.config.in_progress_dir, final_dir) return except OSError: logger.warning("Extreme, unexpected race condition, retrying (%s)", timestamp) # After 10 attempts... something is probably wrong here... logger.error( "Unable to finalize checkpoint, %s -> %s", self.config.in_progress_dir, final_dir) raise errors.ReverterError( "Unable to finalize checkpoint renaming") certbot-0.27.0/certbot/__init__.py0000644000175000017500000000016213344054435017211 0ustar ericaerica00000000000000"""Certbot client.""" # version number like 1.2.3a0, must have at least 2 parts, like 1.2 __version__ = '0.27.0' certbot-0.27.0/certbot/plugins/0002755000175000017500000000000013344054435016564 5ustar ericaerica00000000000000certbot-0.27.0/certbot/plugins/dns_common_lexicon.py0000644000175000017500000000741113344054434023013 0ustar ericaerica00000000000000"""Common code for DNS Authenticator Plugins built on Lexicon.""" import logging from requests.exceptions import HTTPError, RequestException from certbot import errors from certbot.plugins import dns_common logger = logging.getLogger(__name__) class LexiconClient(object): """ Encapsulates all communication with a DNS provider via Lexicon. """ def __init__(self): self.provider = None def add_txt_record(self, domain, record_name, record_content): """ Add a TXT record using the supplied information. :param str domain: The domain to use to look up the managed zone. :param str record_name: The record name (typically beginning with '_acme-challenge.'). :param str record_content: The record content (typically the challenge validation). :raises errors.PluginError: if an error occurs communicating with the DNS Provider API """ self._find_domain_id(domain) try: self.provider.create_record(type='TXT', name=record_name, content=record_content) except RequestException as e: logger.debug('Encountered error adding TXT record: %s', e, exc_info=True) raise errors.PluginError('Error adding TXT record: {0}'.format(e)) def del_txt_record(self, domain, record_name, record_content): """ Delete a TXT record using the supplied information. :param str domain: The domain to use to look up the managed zone. :param str record_name: The record name (typically beginning with '_acme-challenge.'). :param str record_content: The record content (typically the challenge validation). :raises errors.PluginError: if an error occurs communicating with the DNS Provider API """ try: self._find_domain_id(domain) except errors.PluginError as e: logger.debug('Encountered error finding domain_id during deletion: %s', e, exc_info=True) return try: self.provider.delete_record(type='TXT', name=record_name, content=record_content) except RequestException as e: logger.debug('Encountered error deleting TXT record: %s', e, exc_info=True) def _find_domain_id(self, domain): """ Find the domain_id for a given domain. :param str domain: The domain for which to find the domain_id. :raises errors.PluginError: if the domain_id cannot be found. """ domain_name_guesses = dns_common.base_domain_name_guesses(domain) for domain_name in domain_name_guesses: try: self.provider.options['domain'] = domain_name self.provider.authenticate() return # If `authenticate` doesn't throw an exception, we've found the right name except HTTPError as e: result = self._handle_http_error(e, domain_name) if result: raise result except Exception as e: # pylint: disable=broad-except result = self._handle_general_error(e, domain_name) if result: raise result raise errors.PluginError('Unable to determine zone identifier for {0} using zone names: {1}' .format(domain, domain_name_guesses)) def _handle_http_error(self, e, domain_name): return errors.PluginError('Error determining zone identifier for {0}: {1}.' .format(domain_name, e)) def _handle_general_error(self, e, domain_name): if not str(e).startswith('No domain found'): return errors.PluginError('Unexpected error determining zone identifier for {0}: {1}' .format(domain_name, e)) certbot-0.27.0/certbot/plugins/storage_test.py0000644000175000017500000001257213344054434021645 0ustar ericaerica00000000000000"""Tests for certbot.plugins.storage.PluginStorage""" import json import mock import os import unittest from certbot import errors from certbot.plugins import common from certbot.tests import util as test_util class PluginStorageTest(test_util.ConfigTestCase): """Test for certbot.plugins.storage.PluginStorage""" def setUp(self): super(PluginStorageTest, self).setUp() self.plugin_cls = common.Installer os.mkdir(self.config.config_dir) with mock.patch("certbot.reverter.util"): self.plugin = self.plugin_cls(config=self.config, name="mockplugin") def test_load_errors_cant_read(self): with open(os.path.join(self.config.config_dir, ".pluginstorage.json"), "w") as fh: fh.write("dummy") # When unable to read file that exists mock_open = mock.mock_open() mock_open.side_effect = IOError self.plugin.storage.storagepath = os.path.join(self.config.config_dir, ".pluginstorage.json") with mock.patch("six.moves.builtins.open", mock_open): with mock.patch('os.path.isfile', return_value=True): with mock.patch("certbot.reverter.util"): self.assertRaises(errors.PluginStorageError, self.plugin.storage._load) # pylint: disable=protected-access def test_load_errors_empty(self): with open(os.path.join(self.config.config_dir, ".pluginstorage.json"), "w") as fh: fh.write('') with mock.patch("certbot.plugins.storage.logger.debug") as mock_log: # Should not error out but write a debug log line instead with mock.patch("certbot.reverter.util"): nocontent = self.plugin_cls(self.config, "mockplugin") self.assertRaises(KeyError, nocontent.storage.fetch, "value") self.assertTrue(mock_log.called) self.assertTrue("no values loaded" in mock_log.call_args[0][0]) def test_load_errors_corrupted(self): with open(os.path.join(self.config.config_dir, ".pluginstorage.json"), "w") as fh: fh.write('invalid json') with mock.patch("certbot.plugins.storage.logger.error") as mock_log: with mock.patch("certbot.reverter.util"): corrupted = self.plugin_cls(self.config, "mockplugin") self.assertRaises(errors.PluginError, corrupted.storage.fetch, "value") self.assertTrue("is corrupted" in mock_log.call_args[0][0]) def test_save_errors_cant_serialize(self): with mock.patch("certbot.plugins.storage.logger.error") as mock_log: # Set data as something that can't be serialized self.plugin.storage._initialized = True # pylint: disable=protected-access self.plugin.storage.storagepath = "/tmp/whatever" self.plugin.storage._data = self.plugin_cls # pylint: disable=protected-access self.assertRaises(errors.PluginStorageError, self.plugin.storage.save) self.assertTrue("Could not serialize" in mock_log.call_args[0][0]) def test_save_errors_unable_to_write_file(self): mock_open = mock.mock_open() mock_open.side_effect = IOError with mock.patch("os.open", mock_open): with mock.patch("certbot.plugins.storage.logger.error") as mock_log: self.plugin.storage._data = {"valid": "data"} # pylint: disable=protected-access self.plugin.storage._initialized = True # pylint: disable=protected-access self.assertRaises(errors.PluginStorageError, self.plugin.storage.save) self.assertTrue("Could not write" in mock_log.call_args[0][0]) def test_save_uninitialized(self): with mock.patch("certbot.reverter.util"): self.assertRaises(errors.PluginStorageError, self.plugin_cls(self.config, "x").storage.save) def test_namespace_isolation(self): with mock.patch("certbot.reverter.util"): plugin1 = self.plugin_cls(self.config, "first") plugin2 = self.plugin_cls(self.config, "second") plugin1.storage.put("first_key", "first_value") self.assertRaises(KeyError, plugin2.storage.fetch, "first_key") self.assertRaises(KeyError, plugin2.storage.fetch, "first") self.assertEqual(plugin1.storage.fetch("first_key"), "first_value") def test_saved_state(self): self.plugin.storage.put("testkey", "testvalue") # Write to disk self.plugin.storage.save() with mock.patch("certbot.reverter.util"): another = self.plugin_cls(self.config, "mockplugin") self.assertEqual(another.storage.fetch("testkey"), "testvalue") with open(os.path.join(self.config.config_dir, ".pluginstorage.json"), 'r') as fh: psdata = fh.read() psjson = json.loads(psdata) self.assertTrue("mockplugin" in psjson.keys()) self.assertEqual(len(psjson), 1) self.assertEqual(psjson["mockplugin"]["testkey"], "testvalue") if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/manual_test.py0000644000175000017500000001603213344054434021451 0ustar ericaerica00000000000000"""Tests for certbot.plugins.manual""" import os import unittest import six import mock from acme import challenges from certbot import errors from certbot.tests import acme_util from certbot.tests import util as test_util class AuthenticatorTest(test_util.TempDirTestCase): """Tests for certbot.plugins.manual.Authenticator.""" def setUp(self): super(AuthenticatorTest, self).setUp() self.http_achall = acme_util.HTTP01_A self.dns_achall = acme_util.DNS01_A self.tls_sni_achall = acme_util.TLSSNI01_A self.achalls = [self.http_achall, self.dns_achall, self.tls_sni_achall] for d in ["config_dir", "work_dir", "in_progress"]: os.mkdir(os.path.join(self.tempdir, d)) # "backup_dir" and "temp_checkpoint_dir" get created in # certbot.util.make_or_verify_dir() during the Reverter # initialization. self.config = mock.MagicMock( http01_port=0, manual_auth_hook=None, manual_cleanup_hook=None, manual_public_ip_logging_ok=False, noninteractive_mode=False, validate_hooks=False, config_dir=os.path.join(self.tempdir, "config_dir"), work_dir=os.path.join(self.tempdir, "work_dir"), backup_dir=os.path.join(self.tempdir, "backup_dir"), temp_checkpoint_dir=os.path.join( self.tempdir, "temp_checkpoint_dir"), in_progress_dir=os.path.join(self.tempdir, "in_progess"), tls_sni_01_port=5001) from certbot.plugins.manual import Authenticator self.auth = Authenticator(self.config, name='manual') def test_prepare_no_hook_noninteractive(self): self.config.noninteractive_mode = True self.assertRaises(errors.PluginError, self.auth.prepare) def test_prepare_bad_hook(self): self.config.manual_auth_hook = os.path.abspath(os.sep) # is / on UNIX self.config.validate_hooks = True self.assertRaises(errors.HookCommandNotFound, self.auth.prepare) def test_more_info(self): self.assertTrue(isinstance(self.auth.more_info(), six.string_types)) def test_get_chall_pref(self): self.assertEqual(self.auth.get_chall_pref('example.org'), [challenges.HTTP01, challenges.DNS01, challenges.TLSSNI01]) @test_util.patch_get_utility() def test_ip_logging_not_ok(self, mock_get_utility): mock_get_utility().yesno.return_value = False self.assertRaises(errors.PluginError, self.auth.perform, []) @test_util.patch_get_utility() def test_ip_logging_ok(self, mock_get_utility): mock_get_utility().yesno.return_value = True self.auth.perform([]) self.assertTrue(self.config.manual_public_ip_logging_ok) def test_script_perform(self): self.config.manual_public_ip_logging_ok = True self.config.manual_auth_hook = ( 'echo ${CERTBOT_DOMAIN}; ' 'echo ${CERTBOT_TOKEN:-notoken}; ' 'echo ${CERTBOT_CERT_PATH:-nocert}; ' 'echo ${CERTBOT_KEY_PATH:-nokey}; ' 'echo ${CERTBOT_SNI_DOMAIN:-nosnidomain}; ' 'echo ${CERTBOT_VALIDATION:-novalidation};') dns_expected = '{0}\n{1}\n{2}\n{3}\n{4}\n{5}'.format( self.dns_achall.domain, 'notoken', 'nocert', 'nokey', 'nosnidomain', self.dns_achall.validation(self.dns_achall.account_key)) http_expected = '{0}\n{1}\n{2}\n{3}\n{4}\n{5}'.format( self.http_achall.domain, self.http_achall.chall.encode('token'), 'nocert', 'nokey', 'nosnidomain', self.http_achall.validation(self.http_achall.account_key)) self.assertEqual( self.auth.perform(self.achalls), [achall.response(achall.account_key) for achall in self.achalls]) self.assertEqual( self.auth.env[self.dns_achall]['CERTBOT_AUTH_OUTPUT'], dns_expected) self.assertEqual( self.auth.env[self.http_achall]['CERTBOT_AUTH_OUTPUT'], http_expected) # tls_sni_01 challenge must be perform()ed above before we can # get the cert_path and key_path. tls_sni_expected = '{0}\n{1}\n{2}\n{3}\n{4}\n{5}'.format( self.tls_sni_achall.domain, 'notoken', self.auth.tls_sni_01.get_cert_path(self.tls_sni_achall), self.auth.tls_sni_01.get_key_path(self.tls_sni_achall), self.auth.tls_sni_01.get_z_domain(self.tls_sni_achall), 'novalidation') self.assertEqual( self.auth.env[self.tls_sni_achall]['CERTBOT_AUTH_OUTPUT'], tls_sni_expected) @test_util.patch_get_utility() def test_manual_perform(self, mock_get_utility): self.config.manual_public_ip_logging_ok = True self.assertEqual( self.auth.perform(self.achalls), [achall.response(achall.account_key) for achall in self.achalls]) for i, (args, kwargs) in enumerate(mock_get_utility().notification.call_args_list): achall = self.achalls[i] if isinstance(achall.chall, challenges.TLSSNI01): self.assertTrue( self.auth.tls_sni_01.get_cert_path( self.tls_sni_achall) in args[0]) else: self.assertTrue( achall.validation(achall.account_key) in args[0]) self.assertFalse(kwargs['wrap']) def test_cleanup(self): self.config.manual_public_ip_logging_ok = True self.config.manual_auth_hook = 'echo foo;' self.config.manual_cleanup_hook = '# cleanup' self.auth.perform(self.achalls) for achall in self.achalls: self.auth.cleanup([achall]) self.assertEqual(os.environ['CERTBOT_AUTH_OUTPUT'], 'foo') self.assertEqual(os.environ['CERTBOT_DOMAIN'], achall.domain) if (isinstance(achall.chall, challenges.HTTP01) or isinstance(achall.chall, challenges.DNS01)): self.assertEqual( os.environ['CERTBOT_VALIDATION'], achall.validation(achall.account_key)) if isinstance(achall.chall, challenges.HTTP01): self.assertEqual( os.environ['CERTBOT_TOKEN'], achall.chall.encode('token')) else: self.assertFalse('CERTBOT_TOKEN' in os.environ) if isinstance(achall.chall, challenges.TLSSNI01): self.assertEqual( os.environ['CERTBOT_CERT_PATH'], self.auth.tls_sni_01.get_cert_path(achall)) self.assertEqual( os.environ['CERTBOT_KEY_PATH'], self.auth.tls_sni_01.get_key_path(achall)) self.assertFalse( os.path.exists(os.environ['CERTBOT_CERT_PATH'])) self.assertFalse( os.path.exists(os.environ['CERTBOT_KEY_PATH'])) if __name__ == '__main__': unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/null.py0000644000175000017500000000253013344054434020105 0ustar ericaerica00000000000000"""Null plugin.""" import logging import zope.component import zope.interface from certbot import interfaces from certbot.plugins import common logger = logging.getLogger(__name__) @zope.interface.implementer(interfaces.IInstaller) @zope.interface.provider(interfaces.IPluginFactory) class Installer(common.Plugin): """Null installer.""" description = "Null Installer" hidden = True # pylint: disable=missing-docstring,no-self-use def prepare(self): pass # pragma: no cover def more_info(self): return "Installer that doesn't do anything (for testing)." def get_all_names(self): return [] def deploy_cert(self, domain, cert_path, key_path, chain_path=None, fullchain_path=None): pass # pragma: no cover def enhance(self, domain, enhancement, options=None): pass # pragma: no cover def supported_enhancements(self): return [] def save(self, title=None, temporary=False): pass # pragma: no cover def rollback_checkpoints(self, rollback=1): pass # pragma: no cover def recovery_routine(self): pass # pragma: no cover def view_config_changes(self): pass # pragma: no cover def config_test(self): pass # pragma: no cover def restart(self): pass # pragma: no cover certbot-0.27.0/certbot/plugins/dns_common_lexicon_test.py0000644000175000017500000000121313344054434024044 0ustar ericaerica00000000000000"""Tests for certbot.plugins.dns_common_lexicon.""" import unittest import mock from certbot.plugins import dns_common_lexicon from certbot.plugins import dns_test_common_lexicon class LexiconClientTest(unittest.TestCase, dns_test_common_lexicon.BaseLexiconClientTest): class _FakeLexiconClient(dns_common_lexicon.LexiconClient): pass def setUp(self): super(LexiconClientTest, self).setUp() self.client = LexiconClientTest._FakeLexiconClient() self.provider_mock = mock.MagicMock() self.client.provider = self.provider_mock if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/standalone_test.py0000644000175000017500000002231213344054434022322 0ustar ericaerica00000000000000"""Tests for certbot.plugins.standalone.""" import argparse import socket import unittest # https://github.com/python/typeshed/blob/master/stdlib/2and3/socket.pyi from socket import errno as socket_errors # type: ignore import josepy as jose import mock import six import OpenSSL.crypto # pylint: disable=unused-import from acme import challenges from acme import standalone as acme_standalone # pylint: disable=unused-import from acme.magic_typing import Dict, Tuple, Set # pylint: disable=unused-import, no-name-in-module from certbot import achallenges from certbot import errors from certbot.tests import acme_util from certbot.tests import util as test_util class ServerManagerTest(unittest.TestCase): """Tests for certbot.plugins.standalone.ServerManager.""" def setUp(self): from certbot.plugins.standalone import ServerManager self.certs = {} # type: Dict[bytes, Tuple[OpenSSL.crypto.PKey, OpenSSL.crypto.X509]] self.http_01_resources = {} \ # type: Set[acme_standalone.HTTP01RequestHandler.HTTP01Resource] self.mgr = ServerManager(self.certs, self.http_01_resources) def test_init(self): self.assertTrue(self.mgr.certs is self.certs) self.assertTrue( self.mgr.http_01_resources is self.http_01_resources) def _test_run_stop(self, challenge_type): server = self.mgr.run(port=0, challenge_type=challenge_type) port = server.getsocknames()[0][1] # pylint: disable=no-member self.assertEqual(self.mgr.running(), {port: server}) self.mgr.stop(port=port) self.assertEqual(self.mgr.running(), {}) def test_run_stop_tls_sni_01(self): self._test_run_stop(challenges.TLSSNI01) def test_run_stop_http_01(self): self._test_run_stop(challenges.HTTP01) def test_run_idempotent(self): server = self.mgr.run(port=0, challenge_type=challenges.HTTP01) port = server.getsocknames()[0][1] # pylint: disable=no-member server2 = self.mgr.run(port=port, challenge_type=challenges.HTTP01) self.assertEqual(self.mgr.running(), {port: server}) self.assertTrue(server is server2) self.mgr.stop(port) self.assertEqual(self.mgr.running(), {}) def test_run_bind_error(self): some_server = socket.socket(socket.AF_INET6) some_server.bind(("", 0)) port = some_server.getsockname()[1] maybe_another_server = socket.socket() try: maybe_another_server.bind(("", port)) except socket.error: pass self.assertRaises( errors.StandaloneBindError, self.mgr.run, port, challenge_type=challenges.HTTP01) self.assertEqual(self.mgr.running(), {}) class SupportedChallengesActionTest(unittest.TestCase): """Tests for plugins.standalone.SupportedChallengesAction.""" def _call(self, value): with mock.patch("certbot.plugins.standalone.logger") as mock_logger: # stderr is mocked to prevent potential argparse error # output from cluttering test output with mock.patch("sys.stderr"): config = self.parser.parse_args([self.flag, value]) self.assertTrue(mock_logger.warning.called) return getattr(config, self.dest) def setUp(self): self.flag = "--standalone-supported-challenges" self.dest = self.flag[2:].replace("-", "_") self.parser = argparse.ArgumentParser() from certbot.plugins.standalone import SupportedChallengesAction self.parser.add_argument(self.flag, action=SupportedChallengesAction) def test_correct(self): self.assertEqual("tls-sni-01", self._call("tls-sni-01")) self.assertEqual("http-01", self._call("http-01")) self.assertEqual("tls-sni-01,http-01", self._call("tls-sni-01,http-01")) self.assertEqual("http-01,tls-sni-01", self._call("http-01,tls-sni-01")) def test_unrecognized(self): assert "foo" not in challenges.Challenge.TYPES self.assertRaises(SystemExit, self._call, "foo") def test_not_subset(self): self.assertRaises(SystemExit, self._call, "dns") def test_dvsni(self): self.assertEqual("tls-sni-01", self._call("dvsni")) self.assertEqual("http-01,tls-sni-01", self._call("http-01,dvsni")) self.assertEqual("tls-sni-01,http-01", self._call("dvsni,http-01")) def get_open_port(): """Gets an open port number from the OS.""" open_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) open_socket.bind(("", 0)) port = open_socket.getsockname()[1] open_socket.close() return port class AuthenticatorTest(unittest.TestCase): """Tests for certbot.plugins.standalone.Authenticator.""" def setUp(self): from certbot.plugins.standalone import Authenticator self.config = mock.MagicMock( tls_sni_01_port=get_open_port(), http01_port=get_open_port(), standalone_supported_challenges="tls-sni-01,http-01") self.auth = Authenticator(self.config, name="standalone") self.auth.servers = mock.MagicMock() def test_supported_challenges(self): self.assertEqual(self.auth.supported_challenges, [challenges.TLSSNI01, challenges.HTTP01]) def test_supported_challenges_configured(self): self.config.standalone_supported_challenges = "tls-sni-01" self.assertEqual(self.auth.supported_challenges, [challenges.TLSSNI01]) def test_more_info(self): self.assertTrue(isinstance(self.auth.more_info(), six.string_types)) def test_get_chall_pref(self): self.assertEqual(self.auth.get_chall_pref(domain=None), [challenges.TLSSNI01, challenges.HTTP01]) def test_get_chall_pref_configured(self): self.config.standalone_supported_challenges = "tls-sni-01" self.assertEqual(self.auth.get_chall_pref(domain=None), [challenges.TLSSNI01]) def test_perform(self): achalls = self._get_achalls() response = self.auth.perform(achalls) expected = [achall.response(achall.account_key) for achall in achalls] self.assertEqual(response, expected) @test_util.patch_get_utility() def test_perform_eaddrinuse_retry(self, mock_get_utility): mock_utility = mock_get_utility() errno = socket_errors.EADDRINUSE error = errors.StandaloneBindError(mock.MagicMock(errno=errno), -1) self.auth.servers.run.side_effect = [error] + 2 * [mock.MagicMock()] mock_yesno = mock_utility.yesno mock_yesno.return_value = True self.test_perform() self._assert_correct_yesno_call(mock_yesno) @test_util.patch_get_utility() def test_perform_eaddrinuse_no_retry(self, mock_get_utility): mock_utility = mock_get_utility() mock_yesno = mock_utility.yesno mock_yesno.return_value = False errno = socket_errors.EADDRINUSE self.assertRaises(errors.PluginError, self._fail_perform, errno) self._assert_correct_yesno_call(mock_yesno) def _assert_correct_yesno_call(self, mock_yesno): yesno_args, yesno_kwargs = mock_yesno.call_args self.assertTrue("in use" in yesno_args[0]) self.assertFalse(yesno_kwargs.get("default", True)) def test_perform_eacces(self): errno = socket_errors.EACCES self.assertRaises(errors.PluginError, self._fail_perform, errno) def test_perform_unexpected_socket_error(self): errno = socket_errors.ENOTCONN self.assertRaises( errors.StandaloneBindError, self._fail_perform, errno) def _fail_perform(self, errno): error = errors.StandaloneBindError(mock.MagicMock(errno=errno), -1) self.auth.servers.run.side_effect = error self.auth.perform(self._get_achalls()) @classmethod def _get_achalls(cls): domain = b'localhost' key = jose.JWK.load(test_util.load_vector('rsa512_key.pem')) http_01 = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.HTTP01_P, domain=domain, account_key=key) tls_sni_01 = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.TLSSNI01_P, domain=domain, account_key=key) return [http_01, tls_sni_01] def test_cleanup(self): self.auth.servers.running.return_value = { 1: "server1", 2: "server2", } self.auth.served["server1"].add("chall1") self.auth.served["server2"].update(["chall2", "chall3"]) self.auth.cleanup(["chall1"]) self.assertEqual(self.auth.served, { "server1": set(), "server2": set(["chall2", "chall3"])}) self.auth.servers.stop.assert_called_once_with(1) self.auth.servers.running.return_value = { 2: "server2", } self.auth.cleanup(["chall2"]) self.assertEqual(self.auth.served, { "server1": set(), "server2": set(["chall3"])}) self.assertEqual(1, self.auth.servers.stop.call_count) self.auth.cleanup(["chall3"]) self.assertEqual(self.auth.served, { "server1": set(), "server2": set([])}) self.auth.servers.stop.assert_called_with(2) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/webroot_test.py0000644000175000017500000002767513344054434021674 0ustar ericaerica00000000000000"""Tests for certbot.plugins.webroot.""" from __future__ import print_function import argparse import errno import os import shutil import stat import tempfile import unittest import josepy as jose import mock import six from acme import challenges from certbot import achallenges from certbot import errors from certbot.display import util as display_util from certbot.tests import acme_util from certbot.tests import util as test_util KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem")) class AuthenticatorTest(unittest.TestCase): """Tests for certbot.plugins.webroot.Authenticator.""" achall = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.HTTP01_P, domain="thing.com", account_key=KEY) def setUp(self): from certbot.plugins.webroot import Authenticator self.path = tempfile.mkdtemp() self.partial_root_challenge_path = os.path.join( self.path, ".well-known") self.root_challenge_path = os.path.join( self.path, ".well-known", "acme-challenge") self.validation_path = os.path.join( self.root_challenge_path, "ZXZhR3hmQURzNnBTUmIyTEF2OUlaZjE3RHQzanV4R0orUEN0OTJ3citvQQ") self.config = mock.MagicMock(webroot_path=self.path, webroot_map={"thing.com": self.path}) self.auth = Authenticator(self.config, "webroot") def tearDown(self): shutil.rmtree(self.path) def test_more_info(self): more_info = self.auth.more_info() self.assertTrue(isinstance(more_info, six.string_types)) self.assertTrue(self.path in more_info) def test_add_parser_arguments(self): add = mock.MagicMock() self.auth.add_parser_arguments(add) self.assertEqual(2, add.call_count) def test_prepare(self): self.auth.prepare() # shouldn't raise any exceptions @test_util.patch_get_utility() def test_webroot_from_list(self, mock_get_utility): self.config.webroot_path = [] self.config.webroot_map = {"otherthing.com": self.path} mock_display = mock_get_utility() mock_display.menu.return_value = (display_util.OK, 1,) self.auth.perform([self.achall]) self.assertTrue(mock_display.menu.called) for call in mock_display.menu.call_args_list: self.assertTrue(self.achall.domain in call[0][0]) self.assertTrue(all( webroot in call[0][1] for webroot in six.itervalues(self.config.webroot_map))) self.assertEqual(self.config.webroot_map[self.achall.domain], self.path) @test_util.patch_get_utility() def test_webroot_from_list_help_and_cancel(self, mock_get_utility): self.config.webroot_path = [] self.config.webroot_map = {"otherthing.com": self.path} mock_display = mock_get_utility() mock_display.menu.side_effect = ((display_util.CANCEL, -1),) self.assertRaises(errors.PluginError, self.auth.perform, [self.achall]) self.assertTrue(mock_display.menu.called) for call in mock_display.menu.call_args_list: self.assertTrue(self.achall.domain in call[0][0]) self.assertTrue(all( webroot in call[0][1] for webroot in six.itervalues(self.config.webroot_map))) @test_util.patch_get_utility() def test_new_webroot(self, mock_get_utility): self.config.webroot_path = [] self.config.webroot_map = {"something.com": self.path} mock_display = mock_get_utility() mock_display.menu.return_value = (display_util.OK, 0,) with mock.patch('certbot.display.ops.validated_directory') as m: m.side_effect = ((display_util.CANCEL, -1), (display_util.OK, self.path,)) self.auth.perform([self.achall]) self.assertEqual(self.config.webroot_map[self.achall.domain], self.path) @test_util.patch_get_utility() def test_new_webroot_empty_map_cancel(self, mock_get_utility): self.config.webroot_path = [] self.config.webroot_map = {} mock_display = mock_get_utility() mock_display.menu.return_value = (display_util.OK, 0,) with mock.patch('certbot.display.ops.validated_directory') as m: m.return_value = (display_util.CANCEL, -1) self.assertRaises(errors.PluginError, self.auth.perform, [self.achall]) def test_perform_missing_root(self): self.config.webroot_path = None self.config.webroot_map = {} self.assertRaises(errors.PluginError, self.auth.perform, []) def test_perform_reraises_other_errors(self): self.auth.full_path = os.path.join(self.path, "null") permission_canary = os.path.join(self.path, "rnd") with open(permission_canary, "w") as f: f.write("thingimy") os.chmod(self.path, 0o000) try: open(permission_canary, "r") print("Warning, running tests as root skips permissions tests...") except IOError: # ok, permissions work, test away... self.assertRaises(errors.PluginError, self.auth.perform, []) os.chmod(self.path, 0o700) @mock.patch("certbot.plugins.webroot.os.chown") def test_failed_chown(self, mock_chown): mock_chown.side_effect = OSError(errno.EACCES, "msg") self.auth.perform([self.achall]) # exception caught and logged @test_util.patch_get_utility() def test_perform_new_webroot_not_in_map(self, mock_get_utility): new_webroot = tempfile.mkdtemp() self.config.webroot_path = [] self.config.webroot_map = {"whatever.com": self.path} mock_display = mock_get_utility() mock_display.menu.side_effect = ((display_util.OK, 0), (display_util.OK, new_webroot)) achall = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.HTTP01_P, domain="something.com", account_key=KEY) with mock.patch('certbot.display.ops.validated_directory') as m: m.return_value = (display_util.OK, new_webroot,) self.auth.perform([achall]) self.assertEqual(self.config.webroot_map[achall.domain], new_webroot) def test_perform_permissions(self): self.auth.prepare() # Remove exec bit from permission check, so that it # matches the file self.auth.perform([self.achall]) path_permissions = stat.S_IMODE(os.stat(self.validation_path).st_mode) self.assertEqual(path_permissions, 0o644) # Check permissions of the directories for dirpath, dirnames, _ in os.walk(self.path): for directory in dirnames: full_path = os.path.join(dirpath, directory) dir_permissions = stat.S_IMODE(os.stat(full_path).st_mode) self.assertEqual(dir_permissions, 0o755) parent_gid = os.stat(self.path).st_gid parent_uid = os.stat(self.path).st_uid self.assertEqual(os.stat(self.validation_path).st_gid, parent_gid) self.assertEqual(os.stat(self.validation_path).st_uid, parent_uid) def test_perform_cleanup(self): self.auth.prepare() responses = self.auth.perform([self.achall]) self.assertEqual(1, len(responses)) self.assertTrue(os.path.exists(self.validation_path)) with open(self.validation_path) as validation_f: validation = validation_f.read() self.assertTrue( challenges.KeyAuthorizationChallengeResponse( key_authorization=validation).verify( self.achall.chall, KEY.public_key())) self.auth.cleanup([self.achall]) self.assertFalse(os.path.exists(self.validation_path)) self.assertFalse(os.path.exists(self.root_challenge_path)) self.assertFalse(os.path.exists(self.partial_root_challenge_path)) def test_perform_cleanup_existing_dirs(self): os.mkdir(self.partial_root_challenge_path) self.auth.prepare() self.auth.perform([self.achall]) self.auth.cleanup([self.achall]) # Ensure we don't "clean up" directories that previously existed self.assertFalse(os.path.exists(self.validation_path)) self.assertFalse(os.path.exists(self.root_challenge_path)) def test_perform_cleanup_multiple_challenges(self): bingo_achall = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.chall_to_challb( challenges.HTTP01(token=b"bingo"), "pending"), domain="thing.com", account_key=KEY) bingo_validation_path = "YmluZ28" os.mkdir(self.partial_root_challenge_path) self.auth.prepare() self.auth.perform([bingo_achall, self.achall]) self.auth.cleanup([self.achall]) self.assertFalse(os.path.exists(bingo_validation_path)) self.assertTrue(os.path.exists(self.root_challenge_path)) self.auth.cleanup([bingo_achall]) self.assertFalse(os.path.exists(self.validation_path)) self.assertFalse(os.path.exists(self.root_challenge_path)) def test_cleanup_leftovers(self): self.auth.prepare() self.auth.perform([self.achall]) leftover_path = os.path.join(self.root_challenge_path, 'leftover') os.mkdir(leftover_path) self.auth.cleanup([self.achall]) self.assertFalse(os.path.exists(self.validation_path)) self.assertTrue(os.path.exists(self.root_challenge_path)) os.rmdir(leftover_path) @mock.patch('os.rmdir') def test_cleanup_failure(self, mock_rmdir): self.auth.prepare() self.auth.perform([self.achall]) os_error = OSError() os_error.errno = errno.EACCES mock_rmdir.side_effect = os_error self.auth.cleanup([self.achall]) self.assertFalse(os.path.exists(self.validation_path)) self.assertTrue(os.path.exists(self.root_challenge_path)) class WebrootActionTest(unittest.TestCase): """Tests for webroot argparse actions.""" achall = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.HTTP01_P, domain="thing.com", account_key=KEY) def setUp(self): from certbot.plugins.webroot import Authenticator self.path = tempfile.mkdtemp() self.parser = argparse.ArgumentParser() self.parser.add_argument("-d", "--domains", action="append", default=[]) Authenticator.inject_parser_options(self.parser, "webroot") def test_webroot_map_action(self): args = self.parser.parse_args( ["--webroot-map", '{{"thing.com":"{0}"}}'.format(self.path)]) self.assertEqual(args.webroot_map["thing.com"], self.path) def test_domain_before_webroot(self): args = self.parser.parse_args( "-d {0} -w {1}".format(self.achall.domain, self.path).split()) config = self._get_config_after_perform(args) self.assertEqual(config.webroot_map[self.achall.domain], self.path) def test_domain_before_webroot_error(self): self.assertRaises(errors.PluginError, self.parser.parse_args, "-d foo -w bar -w baz".split()) self.assertRaises(errors.PluginError, self.parser.parse_args, "-d foo -w bar -d baz -w qux".split()) def test_multiwebroot(self): args = self.parser.parse_args("-w {0} -d {1} -w {2} -d bar".format( self.path, self.achall.domain, tempfile.mkdtemp()).split()) self.assertEqual(args.webroot_map[self.achall.domain], self.path) config = self._get_config_after_perform(args) self.assertEqual( config.webroot_map[self.achall.domain], self.path) def _get_config_after_perform(self, config): from certbot.plugins.webroot import Authenticator auth = Authenticator(config, "webroot") auth.perform([self.achall]) return auth.config if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/webroot.py0000644000175000017500000002736013344054434020624 0ustar ericaerica00000000000000"""Webroot plugin.""" import argparse import collections import errno import json import logging import os import six import zope.component import zope.interface from acme import challenges # pylint: disable=unused-import # pylint: disable=unused-import, no-name-in-module from acme.magic_typing import Dict, Set, DefaultDict, List # pylint: enable=unused-import, no-name-in-module from certbot import achallenges # pylint: disable=unused-import from certbot import cli from certbot import errors from certbot import interfaces from certbot.display import util as display_util from certbot.display import ops from certbot.plugins import common from certbot.plugins import util logger = logging.getLogger(__name__) @zope.interface.implementer(interfaces.IAuthenticator) @zope.interface.provider(interfaces.IPluginFactory) class Authenticator(common.Plugin): """Webroot Authenticator.""" description = "Place files in webroot directory" MORE_INFO = """\ Authenticator plugin that performs http-01 challenge by saving necessary validation resources to appropriate paths on the file system. It expects that there is some other HTTP server configured to serve all files under specified web root ({0}).""" def more_info(self): # pylint: disable=missing-docstring,no-self-use return self.MORE_INFO.format(self.conf("path")) @classmethod def add_parser_arguments(cls, add): add("path", "-w", default=[], action=_WebrootPathAction, help="public_html / webroot path. This can be specified multiple " "times to handle different domains; each domain will have " "the webroot path that preceded it. For instance: `-w " "/var/www/example -d example.com -d www.example.com -w " "/var/www/thing -d thing.net -d m.thing.net` (default: Ask)") add("map", default={}, action=_WebrootMapAction, help="JSON dictionary mapping domains to webroot paths; this " "implies -d for each entry. You may need to escape this from " "your shell. E.g.: --webroot-map " '\'{"eg1.is,m.eg1.is":"/www/eg1/", "eg2.is":"/www/eg2"}\' ' "This option is merged with, but takes precedence over, -w / " "-d entries. At present, if you put webroot-map in a config " "file, it needs to be on a single line, like: webroot-map = " '{"example.com":"/var/www"}.') def get_chall_pref(self, domain): # pragma: no cover # pylint: disable=missing-docstring,no-self-use,unused-argument return [challenges.HTTP01] def __init__(self, *args, **kwargs): super(Authenticator, self).__init__(*args, **kwargs) self.full_roots = {} # type: Dict[str, str] self.performed = collections.defaultdict(set) \ # type: DefaultDict[str, Set[achallenges.KeyAuthorizationAnnotatedChallenge]] # stack of dirs successfully created by this authenticator self._created_dirs = [] # type: List[str] def prepare(self): # pylint: disable=missing-docstring pass def perform(self, achalls): # pylint: disable=missing-docstring self._set_webroots(achalls) self._create_challenge_dirs() return [self._perform_single(achall) for achall in achalls] def _set_webroots(self, achalls): if self.conf("path"): webroot_path = self.conf("path")[-1] logger.info("Using the webroot path %s for all unmatched domains.", webroot_path) for achall in achalls: self.conf("map").setdefault(achall.domain, webroot_path) else: known_webroots = list(set(six.itervalues(self.conf("map")))) for achall in achalls: if achall.domain not in self.conf("map"): new_webroot = self._prompt_for_webroot(achall.domain, known_webroots) # Put the most recently input # webroot first for easy selection try: known_webroots.remove(new_webroot) except ValueError: pass known_webroots.insert(0, new_webroot) self.conf("map")[achall.domain] = new_webroot def _prompt_for_webroot(self, domain, known_webroots): webroot = None while webroot is None: if known_webroots: # Only show the menu if we have options for it webroot = self._prompt_with_webroot_list(domain, known_webroots) if webroot is None: webroot = self._prompt_for_new_webroot(domain) else: # Allow prompt to raise PluginError instead of looping forever webroot = self._prompt_for_new_webroot(domain, True) return webroot def _prompt_with_webroot_list(self, domain, known_webroots): display = zope.component.getUtility(interfaces.IDisplay) path_flag = "--" + self.option_name("path") while True: code, index = display.menu( "Select the webroot for {0}:".format(domain), ["Enter a new webroot"] + known_webroots, cli_flag=path_flag, force_interactive=True) if code == display_util.CANCEL: raise errors.PluginError( "Every requested domain must have a " "webroot when using the webroot plugin.") else: # code == display_util.OK return None if index == 0 else known_webroots[index - 1] def _prompt_for_new_webroot(self, domain, allowraise=False): code, webroot = ops.validated_directory( _validate_webroot, "Input the webroot for {0}:".format(domain), force_interactive=True) if code == display_util.CANCEL: if not allowraise: return None else: raise errors.PluginError( "Every requested domain must have a " "webroot when using the webroot plugin.") else: # code == display_util.OK return _validate_webroot(webroot) def _create_challenge_dirs(self): path_map = self.conf("map") if not path_map: raise errors.PluginError( "Missing parts of webroot configuration; please set either " "--webroot-path and --domains, or --webroot-map. Run with " " --help webroot for examples.") for name, path in path_map.items(): self.full_roots[name] = os.path.join(path, challenges.HTTP01.URI_ROOT_PATH) logger.debug("Creating root challenges validation dir at %s", self.full_roots[name]) # Change the permissions to be writable (GH #1389) # Umask is used instead of chmod to ensure the client can also # run as non-root (GH #1795) old_umask = os.umask(0o022) try: stat_path = os.stat(path) for prefix in sorted(util.get_prefixes(self.full_roots[name]), key=len): try: # This is coupled with the "umask" call above because # os.mkdir's "mode" parameter may not always work: # https://docs.python.org/3/library/os.html#os.mkdir os.mkdir(prefix, 0o0755) self._created_dirs.append(prefix) # Set owner as parent directory if possible try: os.chown(prefix, stat_path.st_uid, stat_path.st_gid) except OSError as exception: logger.info("Unable to change owner and uid of webroot directory") logger.debug("Error was: %s", exception) except OSError as exception: if exception.errno not in (errno.EEXIST, errno.EISDIR): raise errors.PluginError( "Couldn't create root for {0} http-01 " "challenge responses: {1}".format(name, exception)) finally: os.umask(old_umask) def _get_validation_path(self, root_path, achall): return os.path.join(root_path, achall.chall.encode("token")) def _perform_single(self, achall): response, validation = achall.response_and_validation() root_path = self.full_roots[achall.domain] validation_path = self._get_validation_path(root_path, achall) logger.debug("Attempting to save validation to %s", validation_path) # Change permissions to be world-readable, owner-writable (GH #1795) old_umask = os.umask(0o022) try: with open(validation_path, "wb") as validation_file: validation_file.write(validation.encode()) finally: os.umask(old_umask) self.performed[root_path].add(achall) return response def cleanup(self, achalls): # pylint: disable=missing-docstring for achall in achalls: root_path = self.full_roots.get(achall.domain, None) if root_path is not None: validation_path = self._get_validation_path(root_path, achall) logger.debug("Removing %s", validation_path) os.remove(validation_path) self.performed[root_path].remove(achall) not_removed = [] # type: List[str] while len(self._created_dirs) > 0: path = self._created_dirs.pop() try: os.rmdir(path) except OSError as exc: not_removed.insert(0, path) logger.info("Challenge directory %s was not empty, didn't remove", path) logger.debug("Error was: %s", exc) self._created_dirs = not_removed logger.debug("All challenges cleaned up") class _WebrootMapAction(argparse.Action): """Action class for parsing webroot_map.""" def __call__(self, parser, namespace, webroot_map, option_string=None): for domains, webroot_path in six.iteritems(json.loads(webroot_map)): webroot_path = _validate_webroot(webroot_path) namespace.webroot_map.update( (d, webroot_path) for d in cli.add_domains(namespace, domains)) class _WebrootPathAction(argparse.Action): """Action class for parsing webroot_path.""" def __init__(self, *args, **kwargs): super(_WebrootPathAction, self).__init__(*args, **kwargs) self._domain_before_webroot = False def __call__(self, parser, namespace, webroot_path, option_string=None): if self._domain_before_webroot: raise errors.PluginError( "If you specify multiple webroot paths, " "one of them must precede all domain flags") if namespace.webroot_path: # Apply previous webroot to all matched # domains before setting the new webroot path prev_webroot = namespace.webroot_path[-1] for domain in namespace.domains: namespace.webroot_map.setdefault(domain, prev_webroot) elif namespace.domains: self._domain_before_webroot = True namespace.webroot_path.append(_validate_webroot(webroot_path)) def _validate_webroot(webroot_path): """Validates and returns the absolute path of webroot_path. :param str webroot_path: path to the webroot directory :returns: absolute path of webroot_path :rtype: str """ if not os.path.isdir(webroot_path): raise errors.PluginError(webroot_path + " does not exist or is not a directory") return os.path.abspath(webroot_path) certbot-0.27.0/certbot/plugins/dns_common.py0000644000175000017500000002731513344054434021277 0ustar ericaerica00000000000000"""Common code for DNS Authenticator Plugins.""" import abc import logging import os import stat from time import sleep import configobj import zope.interface from acme import challenges from certbot import errors from certbot import interfaces from certbot.display import ops from certbot.display import util as display_util from certbot.plugins import common logger = logging.getLogger(__name__) @zope.interface.implementer(interfaces.IAuthenticator) @zope.interface.provider(interfaces.IPluginFactory) class DNSAuthenticator(common.Plugin): """Base class for DNS Authenticators""" def __init__(self, config, name): super(DNSAuthenticator, self).__init__(config, name) self._attempt_cleanup = False @classmethod def add_parser_arguments(cls, add, default_propagation_seconds=10): # pylint: disable=arguments-differ add('propagation-seconds', default=default_propagation_seconds, type=int, help='The number of seconds to wait for DNS to propagate before asking the ACME server ' 'to verify the DNS record.') def get_chall_pref(self, unused_domain): # pylint: disable=missing-docstring,no-self-use return [challenges.DNS01] def prepare(self): # pylint: disable=missing-docstring pass def perform(self, achalls): # pylint: disable=missing-docstring self._setup_credentials() self._attempt_cleanup = True responses = [] for achall in achalls: domain = achall.domain validation_domain_name = achall.validation_domain_name(domain) validation = achall.validation(achall.account_key) self._perform(domain, validation_domain_name, validation) responses.append(achall.response(achall.account_key)) # DNS updates take time to propagate and checking to see if the update has occurred is not # reliable (the machine this code is running on might be able to see an update before # the ACME server). So: we sleep for a short amount of time we believe to be long enough. logger.info("Waiting %d seconds for DNS changes to propagate", self.conf('propagation-seconds')) sleep(self.conf('propagation-seconds')) return responses def cleanup(self, achalls): # pylint: disable=missing-docstring if self._attempt_cleanup: for achall in achalls: domain = achall.domain validation_domain_name = achall.validation_domain_name(domain) validation = achall.validation(achall.account_key) self._cleanup(domain, validation_domain_name, validation) @abc.abstractmethod def _setup_credentials(self): # pragma: no cover """ Establish credentials, prompting if necessary. """ raise NotImplementedError() @abc.abstractmethod def _perform(self, domain, validation_domain_name, validation): # pragma: no cover """ Performs a dns-01 challenge by creating a DNS TXT record. :param str domain: The domain being validated. :param str validation_domain_name: The validation record domain name. :param str validation: The validation record content. :raises errors.PluginError: If the challenge cannot be performed """ raise NotImplementedError() @abc.abstractmethod def _cleanup(self, domain, validation_domain_name, validation): # pragma: no cover """ Deletes the DNS TXT record which would have been created by `_perform_achall`. Fails gracefully if no such record exists. :param str domain: The domain being validated. :param str validation_domain_name: The validation record domain name. :param str validation: The validation record content. """ raise NotImplementedError() def _configure(self, key, label): """ Ensure that a configuration value is available. If necessary, prompts the user and stores the result. :param str key: The configuration key. :param str label: The user-friendly label for this piece of information. """ configured_value = self.conf(key) if not configured_value: new_value = self._prompt_for_data(label) setattr(self.config, self.dest(key), new_value) def _configure_file(self, key, label, validator=None): """ Ensure that a configuration value is available for a path. If necessary, prompts the user and stores the result. :param str key: The configuration key. :param str label: The user-friendly label for this piece of information. """ configured_value = self.conf(key) if not configured_value: new_value = self._prompt_for_file(label, validator) setattr(self.config, self.dest(key), os.path.abspath(os.path.expanduser(new_value))) def _configure_credentials(self, key, label, required_variables=None, validator=None): """ As `_configure_file`, but for a credential configuration file. If necessary, prompts the user and stores the result. Always stores absolute paths to avoid issues during renewal. :param str key: The configuration key. :param str label: The user-friendly label for this piece of information. :param dict required_variables: Map of variable which must be present to error to display. :param callable validator: A method which will be called to validate the `CredentialsConfiguration` resulting from the supplied input after it has been validated to contain the `required_variables`. Should throw a `~certbot.errors.PluginError` to indicate any issue. """ def __validator(filename): configuration = CredentialsConfiguration(filename, self.dest) if required_variables: configuration.require(required_variables) if validator: validator(configuration) self._configure_file(key, label, __validator) credentials_configuration = CredentialsConfiguration(self.conf(key), self.dest) if required_variables: credentials_configuration.require(required_variables) if validator: validator(credentials_configuration) return credentials_configuration @staticmethod def _prompt_for_data(label): """ Prompt the user for a piece of information. :param str label: The user-friendly label for this piece of information. :returns: The user's response (guaranteed non-empty). :rtype: str """ def __validator(i): if not i: raise errors.PluginError('Please enter your {0}.'.format(label)) code, response = ops.validated_input( __validator, 'Input your {0}'.format(label), force_interactive=True) if code == display_util.OK: return response else: raise errors.PluginError('{0} required to proceed.'.format(label)) @staticmethod def _prompt_for_file(label, validator=None): """ Prompt the user for a path. :param str label: The user-friendly label for the file. :param callable validator: A method which will be called to validate the supplied input after it has been validated to be a non-empty path to an existing file. Should throw a `~certbot.errors.PluginError` to indicate any issue. :returns: The user's response (guaranteed to exist). :rtype: str """ def __validator(filename): if not filename: raise errors.PluginError('Please enter a valid path to your {0}.'.format(label)) filename = os.path.expanduser(filename) validate_file(filename) if validator: validator(filename) code, response = ops.validated_directory( __validator, 'Input the path to your {0}'.format(label), force_interactive=True) if code == display_util.OK: return response else: raise errors.PluginError('{0} required to proceed.'.format(label)) class CredentialsConfiguration(object): """Represents a user-supplied filed which stores API credentials.""" def __init__(self, filename, mapper=lambda x: x): """ :param str filename: A path to the configuration file. :param callable mapper: A transformation to apply to configuration key names :raises errors.PluginError: If the file does not exist or is not a valid format. """ validate_file_permissions(filename) try: self.confobj = configobj.ConfigObj(filename) except configobj.ConfigObjError as e: logger.debug("Error parsing credentials configuration: %s", e, exc_info=True) raise errors.PluginError("Error parsing credentials configuration: {0}".format(e)) self.mapper = mapper def require(self, required_variables): """Ensures that the supplied set of variables are all present in the file. :param dict required_variables: Map of variable which must be present to error to display. :raises errors.PluginError: If one or more are missing. """ messages = [] for var in required_variables: if not self._has(var): messages.append('Property "{0}" not found (should be {1}).' .format(self.mapper(var), required_variables[var])) elif not self._get(var): messages.append('Property "{0}" not set (should be {1}).' .format(self.mapper(var), required_variables[var])) if messages: raise errors.PluginError( 'Missing {0} in credentials configuration file {1}:\n * {2}'.format( 'property' if len(messages) == 1 else 'properties', self.confobj.filename, '\n * '.join(messages) ) ) def conf(self, var): """Find a configuration value for variable `var`, as transformed by `mapper`. :param str var: The variable to get. :returns: The value of the variable. :rtype: str """ return self._get(var) def _has(self, var): return self.mapper(var) in self.confobj def _get(self, var): return self.confobj.get(self.mapper(var)) def validate_file(filename): """Ensure that the specified file exists.""" if not os.path.exists(filename): raise errors.PluginError('File not found: {0}'.format(filename)) if not os.path.isfile(filename): raise errors.PluginError('Path is not a file: {0}'.format(filename)) def validate_file_permissions(filename): """Ensure that the specified file exists and warn about unsafe permissions.""" validate_file(filename) permissions = stat.S_IMODE(os.stat(filename).st_mode) if permissions & stat.S_IRWXO: logger.warning('Unsafe permissions on credentials configuration file: %s', filename) def base_domain_name_guesses(domain): """Return a list of progressively less-specific domain names. One of these will probably be the domain name known to the DNS provider. :Example: >>> base_domain_name_guesses('foo.bar.baz.example.com') ['foo.bar.baz.example.com', 'bar.baz.example.com', 'baz.example.com', 'example.com', 'com'] :param str domain: The domain for which to return guesses. :returns: The a list of less specific domain names. :rtype: list """ fragments = domain.split('.') return ['.'.join(fragments[i:]) for i in range(0, len(fragments))] certbot-0.27.0/certbot/plugins/util.py0000644000175000017500000000313713344054434020114 0ustar ericaerica00000000000000"""Plugin utilities.""" import logging import os from certbot import util logger = logging.getLogger(__name__) def get_prefixes(path): """Retrieves all possible path prefixes of a path, in descending order of length. For instance, /a/b/c/ => ['/a/b/c/', '/a/b/c', '/a/b', '/a', '/'] :param str path: the path to break into prefixes :returns: all possible path prefixes of given path in descending order :rtype: `list` of `str` """ prefix = path prefixes = [] while len(prefix) > 0: prefixes.append(prefix) prefix, _ = os.path.split(prefix) # break once we hit '/' if prefix == prefixes[-1]: break return prefixes def path_surgery(cmd): """Attempt to perform PATH surgery to find cmd Mitigates https://github.com/certbot/certbot/issues/1833 :param str cmd: the command that is being searched for in the PATH :returns: True if the operation succeeded, False otherwise """ dirs = ("/usr/sbin", "/usr/local/bin", "/usr/local/sbin") path = os.environ["PATH"] added = [] for d in dirs: if d not in path: path += os.pathsep + d added.append(d) if any(added): logger.debug("Can't find %s, attempting PATH mitigation by adding %s", cmd, os.pathsep.join(added)) os.environ["PATH"] = path if util.exe_exists(cmd): return True else: expanded = " expanded" if any(added) else "" logger.debug("Failed to find executable %s in%s PATH: %s", cmd, expanded, path) return False certbot-0.27.0/certbot/plugins/disco.py0000644000175000017500000002365613344054434020250 0ustar ericaerica00000000000000"""Utilities for plugins discovery and selection.""" import collections import itertools import logging import pkg_resources import six from collections import OrderedDict import zope.interface import zope.interface.verify from acme.magic_typing import Dict # pylint: disable=unused-import, no-name-in-module from certbot import constants from certbot import errors from certbot import interfaces logger = logging.getLogger(__name__) class PluginEntryPoint(object): """Plugin entry point.""" PREFIX_FREE_DISTRIBUTIONS = [ "certbot", "certbot-apache", "certbot-dns-cloudflare", "certbot-dns-cloudxns", "certbot-dns-digitalocean", "certbot-dns-dnsimple", "certbot-dns-dnsmadeeasy", "certbot-dns-gehirn", "certbot-dns-google", "certbot-dns-linode", "certbot-dns-luadns", "certbot-dns-nsone", "certbot-dns-ovh", "certbot-dns-rfc2136", "certbot-dns-route53", "certbot-dns-sakuracloud", "certbot-nginx", "certbot-postfix", ] """Distributions for which prefix will be omitted.""" # this object is mutable, don't allow it to be hashed! __hash__ = None # type: ignore def __init__(self, entry_point): self.name = self.entry_point_to_plugin_name(entry_point) self.plugin_cls = entry_point.load() self.entry_point = entry_point self._initialized = None self._prepared = None @classmethod def entry_point_to_plugin_name(cls, entry_point): """Unique plugin name for an ``entry_point``""" if entry_point.dist.key in cls.PREFIX_FREE_DISTRIBUTIONS: return entry_point.name return entry_point.dist.key + ":" + entry_point.name @property def description(self): """Description of the plugin.""" return self.plugin_cls.description @property def description_with_name(self): """Description with name. Handy for UI.""" return "{0} ({1})".format(self.description, self.name) @property def long_description(self): """Long description of the plugin.""" try: return self.plugin_cls.long_description except AttributeError: return self.description @property def hidden(self): """Should this plugin be hidden from UI?""" return getattr(self.plugin_cls, "hidden", False) def ifaces(self, *ifaces_groups): """Does plugin implements specified interface groups?""" return not ifaces_groups or any( all(iface.implementedBy(self.plugin_cls) for iface in ifaces) for ifaces in ifaces_groups) @property def initialized(self): """Has the plugin been initialized already?""" return self._initialized is not None def init(self, config=None): """Memoized plugin initialization.""" if not self.initialized: self.entry_point.require() # fetch extras! self._initialized = self.plugin_cls(config, self.name) return self._initialized def verify(self, ifaces): """Verify that the plugin conforms to the specified interfaces.""" assert self.initialized for iface in ifaces: # zope.interface.providedBy(plugin) try: zope.interface.verify.verifyObject(iface, self.init()) except zope.interface.exceptions.BrokenImplementation as error: if iface.implementedBy(self.plugin_cls): logger.debug( "%s implements %s but object does not verify: %s", self.plugin_cls, iface.__name__, error, exc_info=True) return False return True @property def prepared(self): """Has the plugin been prepared already?""" if not self.initialized: logger.debug(".prepared called on uninitialized %r", self) return self._prepared is not None def prepare(self): """Memoized plugin preparation.""" assert self.initialized if self._prepared is None: try: self._initialized.prepare() except errors.MisconfigurationError as error: logger.debug("Misconfigured %r: %s", self, error, exc_info=True) self._prepared = error except errors.NoInstallationError as error: logger.debug( "No installation (%r): %s", self, error, exc_info=True) self._prepared = error except errors.PluginError as error: logger.debug("Other error:(%r): %s", self, error, exc_info=True) self._prepared = error else: self._prepared = True return self._prepared @property def misconfigured(self): """Is plugin misconfigured?""" return isinstance(self._prepared, errors.MisconfigurationError) @property def problem(self): """Return the Exception raised during plugin setup, or None if all is well""" if isinstance(self._prepared, Exception): return self._prepared return None @property def available(self): """Is plugin available, i.e. prepared or misconfigured?""" return self._prepared is True or self.misconfigured def __repr__(self): return "PluginEntryPoint#{0}".format(self.name) def __str__(self): lines = [ "* {0}".format(self.name), "Description: {0}".format(self.plugin_cls.description), "Interfaces: {0}".format(", ".join( iface.__name__ for iface in zope.interface.implementedBy( self.plugin_cls))), "Entry point: {0}".format(self.entry_point), ] if self.initialized: lines.append("Initialized: {0}".format(self.init())) if self.prepared: lines.append("Prep: {0}".format(self.prepare())) return "\n".join(lines) class PluginsRegistry(collections.Mapping): """Plugins registry.""" def __init__(self, plugins): # plugins are sorted so the same order is used between runs. # This prevents deadlock caused by plugins acquiring a lock # and ensures at least one concurrent Certbot instance will run # successfully. self._plugins = OrderedDict(sorted(six.iteritems(plugins))) @classmethod def find_all(cls): """Find plugins using setuptools entry points.""" plugins = {} # type: Dict[str, PluginEntryPoint] # pylint: disable=not-callable entry_points = itertools.chain( pkg_resources.iter_entry_points( constants.SETUPTOOLS_PLUGINS_ENTRY_POINT), pkg_resources.iter_entry_points( constants.OLD_SETUPTOOLS_PLUGINS_ENTRY_POINT),) for entry_point in entry_points: plugin_ep = PluginEntryPoint(entry_point) assert plugin_ep.name not in plugins, ( "PREFIX_FREE_DISTRIBUTIONS messed up") # providedBy | pylint: disable=no-member if interfaces.IPluginFactory.providedBy(plugin_ep.plugin_cls): plugins[plugin_ep.name] = plugin_ep else: # pragma: no cover logger.warning( "%r does not provide IPluginFactory, skipping", plugin_ep) return cls(plugins) def __getitem__(self, name): return self._plugins[name] def __iter__(self): return iter(self._plugins) def __len__(self): return len(self._plugins) def init(self, config): """Initialize all plugins in the registry.""" return [plugin_ep.init(config) for plugin_ep in six.itervalues(self._plugins)] def filter(self, pred): """Filter plugins based on predicate.""" return type(self)(dict((name, plugin_ep) for name, plugin_ep in six.iteritems(self._plugins) if pred(plugin_ep))) def visible(self): """Filter plugins based on visibility.""" return self.filter(lambda plugin_ep: not plugin_ep.hidden) def ifaces(self, *ifaces_groups): """Filter plugins based on interfaces.""" # pylint: disable=star-args return self.filter(lambda p_ep: p_ep.ifaces(*ifaces_groups)) def verify(self, ifaces): """Filter plugins based on verification.""" return self.filter(lambda p_ep: p_ep.verify(ifaces)) def prepare(self): """Prepare all plugins in the registry.""" return [plugin_ep.prepare() for plugin_ep in six.itervalues(self._plugins)] def available(self): """Filter plugins based on availability.""" return self.filter(lambda p_ep: p_ep.available) # successfully prepared + misconfigured def find_init(self, plugin): """Find an initialized plugin. This is particularly useful for finding a name for the plugin (although `.IPluginFactory.__call__` takes ``name`` as one of the arguments, ``IPlugin.name`` is not part of the interface):: # plugin is an instance providing IPlugin, initialized # somewhere else in the code plugin_registry.find_init(plugin).name Returns ``None`` if ``plugin`` is not found in the registry. """ # use list instead of set because PluginEntryPoint is not hashable candidates = [plugin_ep for plugin_ep in six.itervalues(self._plugins) if plugin_ep.initialized and plugin_ep.init() is plugin] assert len(candidates) <= 1 if candidates: return candidates[0] else: return None def __repr__(self): return "{0}({1})".format( self.__class__.__name__, ','.join( repr(p_ep) for p_ep in six.itervalues(self._plugins))) def __str__(self): if not self._plugins: return "No plugins" return "\n\n".join(str(p_ep) for p_ep in six.itervalues(self._plugins)) certbot-0.27.0/certbot/plugins/disco_test.py0000644000175000017500000002653413344054434021305 0ustar ericaerica00000000000000"""Tests for certbot.plugins.disco.""" import functools import string import unittest import mock import pkg_resources import six import zope.interface from acme.magic_typing import List # pylint: disable=unused-import, no-name-in-module from certbot import errors from certbot import interfaces from certbot.plugins import standalone from certbot.plugins import webroot EP_SA = pkg_resources.EntryPoint( "sa", "certbot.plugins.standalone", attrs=("Authenticator",), dist=mock.MagicMock(key="certbot")) EP_WR = pkg_resources.EntryPoint( "wr", "certbot.plugins.webroot", attrs=("Authenticator",), dist=mock.MagicMock(key="certbot")) class PluginEntryPointTest(unittest.TestCase): """Tests for certbot.plugins.disco.PluginEntryPoint.""" def setUp(self): self.ep1 = pkg_resources.EntryPoint( "ep1", "p1.ep1", dist=mock.MagicMock(key="p1")) self.ep1prim = pkg_resources.EntryPoint( "ep1", "p2.ep2", dist=mock.MagicMock(key="p2")) # nested self.ep2 = pkg_resources.EntryPoint( "ep2", "p2.foo.ep2", dist=mock.MagicMock(key="p2")) # project name != top-level package name self.ep3 = pkg_resources.EntryPoint( "ep3", "a.ep3", dist=mock.MagicMock(key="p3")) from certbot.plugins.disco import PluginEntryPoint self.plugin_ep = PluginEntryPoint(EP_SA) def test_entry_point_to_plugin_name(self): from certbot.plugins.disco import PluginEntryPoint names = { self.ep1: "p1:ep1", self.ep1prim: "p2:ep1", self.ep2: "p2:ep2", self.ep3: "p3:ep3", EP_SA: "sa", } for entry_point, name in six.iteritems(names): self.assertEqual( name, PluginEntryPoint.entry_point_to_plugin_name(entry_point)) def test_description(self): self.assertTrue("temporary webserver" in self.plugin_ep.description) def test_description_with_name(self): self.plugin_ep.plugin_cls = mock.MagicMock(description="Desc") self.assertEqual( "Desc (sa)", self.plugin_ep.description_with_name) def test_long_description(self): self.plugin_ep.plugin_cls = mock.MagicMock( long_description="Long desc") self.assertEqual( "Long desc", self.plugin_ep.long_description) def test_long_description_nonexistent(self): self.plugin_ep.plugin_cls = mock.MagicMock( description="Long desc not found", spec=["description"]) self.assertEqual( "Long desc not found", self.plugin_ep.long_description) def test_ifaces(self): self.assertTrue(self.plugin_ep.ifaces((interfaces.IAuthenticator,))) self.assertFalse(self.plugin_ep.ifaces((interfaces.IInstaller,))) self.assertFalse(self.plugin_ep.ifaces(( interfaces.IInstaller, interfaces.IAuthenticator))) def test__init__(self): self.assertFalse(self.plugin_ep.initialized) self.assertFalse(self.plugin_ep.prepared) self.assertFalse(self.plugin_ep.misconfigured) self.assertFalse(self.plugin_ep.available) self.assertTrue(self.plugin_ep.problem is None) self.assertTrue(self.plugin_ep.entry_point is EP_SA) self.assertEqual("sa", self.plugin_ep.name) self.assertTrue(self.plugin_ep.plugin_cls is standalone.Authenticator) def test_init(self): config = mock.MagicMock() plugin = self.plugin_ep.init(config=config) self.assertTrue(self.plugin_ep.initialized) self.assertTrue(plugin.config is config) # memoize! self.assertTrue(self.plugin_ep.init() is plugin) self.assertTrue(plugin.config is config) # try to give different config self.assertTrue(self.plugin_ep.init(123) is plugin) self.assertTrue(plugin.config is config) self.assertFalse(self.plugin_ep.prepared) self.assertFalse(self.plugin_ep.misconfigured) self.assertFalse(self.plugin_ep.available) def test_verify(self): iface1 = mock.MagicMock(__name__="iface1") iface2 = mock.MagicMock(__name__="iface2") iface3 = mock.MagicMock(__name__="iface3") # pylint: disable=protected-access self.plugin_ep._initialized = plugin = mock.MagicMock() exceptions = zope.interface.exceptions with mock.patch("certbot.plugins." "disco.zope.interface") as mock_zope: mock_zope.exceptions = exceptions def verify_object(iface, obj): # pylint: disable=missing-docstring assert obj is plugin assert iface is iface1 or iface is iface2 or iface is iface3 if iface is iface3: raise mock_zope.exceptions.BrokenImplementation(None, None) mock_zope.verify.verifyObject.side_effect = verify_object self.assertTrue(self.plugin_ep.verify((iface1,))) self.assertTrue(self.plugin_ep.verify((iface1, iface2))) self.assertFalse(self.plugin_ep.verify((iface3,))) self.assertFalse(self.plugin_ep.verify((iface1, iface3))) def test_prepare(self): config = mock.MagicMock() self.plugin_ep.init(config=config) self.plugin_ep.prepare() self.assertTrue(self.plugin_ep.prepared) self.assertFalse(self.plugin_ep.misconfigured) # output doesn't matter that much, just test if it runs str(self.plugin_ep) def test_prepare_misconfigured(self): plugin = mock.MagicMock() plugin.prepare.side_effect = errors.MisconfigurationError # pylint: disable=protected-access self.plugin_ep._initialized = plugin self.assertTrue(isinstance(self.plugin_ep.prepare(), errors.MisconfigurationError)) self.assertTrue(self.plugin_ep.prepared) self.assertTrue(self.plugin_ep.misconfigured) self.assertTrue(isinstance(self.plugin_ep.problem, errors.MisconfigurationError)) self.assertTrue(self.plugin_ep.available) def test_prepare_no_installation(self): plugin = mock.MagicMock() plugin.prepare.side_effect = errors.NoInstallationError # pylint: disable=protected-access self.plugin_ep._initialized = plugin self.assertTrue(isinstance(self.plugin_ep.prepare(), errors.NoInstallationError)) self.assertTrue(self.plugin_ep.prepared) self.assertFalse(self.plugin_ep.misconfigured) self.assertFalse(self.plugin_ep.available) def test_prepare_generic_plugin_error(self): plugin = mock.MagicMock() plugin.prepare.side_effect = errors.PluginError # pylint: disable=protected-access self.plugin_ep._initialized = plugin self.assertTrue(isinstance(self.plugin_ep.prepare(), errors.PluginError)) self.assertTrue(self.plugin_ep.prepared) self.assertFalse(self.plugin_ep.misconfigured) self.assertFalse(self.plugin_ep.available) def test_repr(self): self.assertEqual("PluginEntryPoint#sa", repr(self.plugin_ep)) class PluginsRegistryTest(unittest.TestCase): """Tests for certbot.plugins.disco.PluginsRegistry.""" @classmethod def _create_new_registry(cls, plugins): from certbot.plugins.disco import PluginsRegistry return PluginsRegistry(plugins) def setUp(self): self.plugin_ep = mock.MagicMock() self.plugin_ep.name = "mock" self.plugin_ep.__hash__.side_effect = TypeError self.plugins = {self.plugin_ep.name: self.plugin_ep} self.reg = self._create_new_registry(self.plugins) def test_find_all(self): from certbot.plugins.disco import PluginsRegistry with mock.patch("certbot.plugins.disco.pkg_resources") as mock_pkg: mock_pkg.iter_entry_points.side_effect = [iter([EP_SA]), iter([EP_WR])] plugins = PluginsRegistry.find_all() self.assertTrue(plugins["sa"].plugin_cls is standalone.Authenticator) self.assertTrue(plugins["sa"].entry_point is EP_SA) self.assertTrue(plugins["wr"].plugin_cls is webroot.Authenticator) self.assertTrue(plugins["wr"].entry_point is EP_WR) def test_getitem(self): self.assertEqual(self.plugin_ep, self.reg["mock"]) def test_iter(self): self.assertEqual(["mock"], list(self.reg)) def test_len(self): self.assertEqual(0, len(self._create_new_registry({}))) self.assertEqual(1, len(self.reg)) def test_init(self): self.plugin_ep.init.return_value = "baz" self.assertEqual(["baz"], self.reg.init("bar")) self.plugin_ep.init.assert_called_once_with("bar") def test_filter(self): self.assertEqual( self.plugins, self.reg.filter(lambda p_ep: p_ep.name.startswith("m"))) self.assertEqual( {}, self.reg.filter(lambda p_ep: p_ep.name.startswith("b"))) def test_ifaces(self): self.plugin_ep.ifaces.return_value = True # pylint: disable=protected-access self.assertEqual(self.plugins, self.reg.ifaces()._plugins) self.plugin_ep.ifaces.return_value = False self.assertEqual({}, self.reg.ifaces()._plugins) def test_verify(self): self.plugin_ep.verify.return_value = True # pylint: disable=protected-access self.assertEqual( self.plugins, self.reg.verify(mock.MagicMock())._plugins) self.plugin_ep.verify.return_value = False self.assertEqual({}, self.reg.verify(mock.MagicMock())._plugins) def test_prepare(self): self.plugin_ep.prepare.return_value = "baz" self.assertEqual(["baz"], self.reg.prepare()) self.plugin_ep.prepare.assert_called_once_with() def test_prepare_order(self): order = [] # type: List[str] plugins = dict( (c, mock.MagicMock(prepare=functools.partial(order.append, c))) for c in string.ascii_letters) reg = self._create_new_registry(plugins) reg.prepare() # order of prepare calls must be sorted to prevent deadlock # caused by plugins acquiring locks during prepare self.assertEqual(order, sorted(string.ascii_letters)) def test_available(self): self.plugin_ep.available = True # pylint: disable=protected-access self.assertEqual(self.plugins, self.reg.available()._plugins) self.plugin_ep.available = False self.assertEqual({}, self.reg.available()._plugins) def test_find_init(self): self.assertTrue(self.reg.find_init(mock.Mock()) is None) self.plugin_ep.initialized = True self.assertTrue( self.reg.find_init(self.plugin_ep.init()) is self.plugin_ep) def test_repr(self): self.plugin_ep.__repr__ = lambda _: "PluginEntryPoint#mock" self.assertEqual("PluginsRegistry(PluginEntryPoint#mock)", repr(self.reg)) def test_str(self): self.assertEqual("No plugins", str(self._create_new_registry({}))) self.plugin_ep.__str__ = lambda _: "Mock" self.assertEqual("Mock", str(self.reg)) plugins = {self.plugin_ep.name: self.plugin_ep, "foo": "Bar"} reg = self._create_new_registry(plugins) self.assertEqual("Bar\n\nMock", str(reg)) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/storage.py0000644000175000017500000001012713344054434020600 0ustar ericaerica00000000000000"""Plugin storage class.""" import json import logging import os from acme.magic_typing import Any, Dict # pylint: disable=unused-import, no-name-in-module from certbot import errors logger = logging.getLogger(__name__) class PluginStorage(object): """Class implementing storage functionality for plugins""" def __init__(self, config, classkey): """Initializes PluginStorage object storing required configuration options. :param .configuration.NamespaceConfig config: Configuration object :param str classkey: class name to use as root key in storage file """ self._config = config self._classkey = classkey self._initialized = False self._data = None self._storagepath = None def _initialize_storage(self): """Initializes PluginStorage data and reads current state from the disk if the storage json exists.""" self._storagepath = os.path.join(self._config.config_dir, ".pluginstorage.json") self._load() self._initialized = True def _load(self): """Reads PluginStorage content from the disk to a dict structure :raises .errors.PluginStorageError: when unable to open or read the file """ data = dict() # type: Dict[str, Any] filedata = "" try: with open(self._storagepath, 'r') as fh: filedata = fh.read() except IOError as e: errmsg = "Could not read PluginStorage data file: {0} : {1}".format( self._storagepath, str(e)) if os.path.isfile(self._storagepath): # Only error out if file exists, but cannot be read logger.error(errmsg) raise errors.PluginStorageError(errmsg) try: data = json.loads(filedata) except ValueError: if not filedata: logger.debug("Plugin storage file %s was empty, no values loaded", self._storagepath) else: errmsg = "PluginStorage file {0} is corrupted.".format( self._storagepath) logger.error(errmsg) raise errors.PluginStorageError(errmsg) self._data = data def save(self): """Saves PluginStorage content to disk :raises .errors.PluginStorageError: when unable to serialize the data or write it to the filesystem """ if not self._initialized: errmsg = "Unable to save, no values have been added to PluginStorage." logger.error(errmsg) raise errors.PluginStorageError(errmsg) try: serialized = json.dumps(self._data) except TypeError as e: errmsg = "Could not serialize PluginStorage data: {0}".format( str(e)) logger.error(errmsg) raise errors.PluginStorageError(errmsg) try: with os.fdopen(os.open(self._storagepath, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w') as fh: fh.write(serialized) except IOError as e: errmsg = "Could not write PluginStorage data to file {0} : {1}".format( self._storagepath, str(e)) logger.error(errmsg) raise errors.PluginStorageError(errmsg) def put(self, key, value): """Put configuration value to PluginStorage :param str key: Key to store the value to :param value: Data to store """ if not self._initialized: self._initialize_storage() if not self._classkey in self._data.keys(): self._data[self._classkey] = dict() self._data[self._classkey][key] = value def fetch(self, key): """Get configuration value from PluginStorage :param str key: Key to get value from the storage :raises KeyError: If the key doesn't exist in the storage """ if not self._initialized: self._initialize_storage() return self._data[self._classkey][key] certbot-0.27.0/certbot/plugins/dns_test_common_lexicon.py0000644000175000017500000001275713344054434024063 0ustar ericaerica00000000000000"""Base test class for DNS authenticators built on Lexicon.""" import josepy as jose import mock from requests.exceptions import HTTPError, RequestException from certbot import errors from certbot.plugins import dns_test_common from certbot.tests import util as test_util DOMAIN = 'example.com' KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem")) # These classes are intended to be subclassed/mixed in, so not all members are defined. # pylint: disable=no-member class BaseLexiconAuthenticatorTest(dns_test_common.BaseAuthenticatorTest): def test_perform(self): self.auth.perform([self.achall]) expected = [mock.call.add_txt_record(DOMAIN, '_acme-challenge.'+DOMAIN, mock.ANY)] self.assertEqual(expected, self.mock_client.mock_calls) def test_cleanup(self): self.auth._attempt_cleanup = True # _attempt_cleanup | pylint: disable=protected-access self.auth.cleanup([self.achall]) expected = [mock.call.del_txt_record(DOMAIN, '_acme-challenge.'+DOMAIN, mock.ANY)] self.assertEqual(expected, self.mock_client.mock_calls) class BaseLexiconClientTest(object): DOMAIN_NOT_FOUND = Exception('No domain found') GENERIC_ERROR = RequestException LOGIN_ERROR = HTTPError('400 Client Error: ...') UNKNOWN_LOGIN_ERROR = HTTPError('500 Surprise! Error: ...') record_prefix = "_acme-challenge" record_name = record_prefix + "." + DOMAIN record_content = "bar" def test_add_txt_record(self): self.client.add_txt_record(DOMAIN, self.record_name, self.record_content) self.provider_mock.create_record.assert_called_with(type='TXT', name=self.record_name, content=self.record_content) def test_add_txt_record_try_twice_to_find_domain(self): self.provider_mock.authenticate.side_effect = [self.DOMAIN_NOT_FOUND, ''] self.client.add_txt_record(DOMAIN, self.record_name, self.record_content) self.provider_mock.create_record.assert_called_with(type='TXT', name=self.record_name, content=self.record_content) def test_add_txt_record_fail_to_find_domain(self): self.provider_mock.authenticate.side_effect = [self.DOMAIN_NOT_FOUND, self.DOMAIN_NOT_FOUND, self.DOMAIN_NOT_FOUND,] self.assertRaises(errors.PluginError, self.client.add_txt_record, DOMAIN, self.record_name, self.record_content) def test_add_txt_record_fail_to_authenticate(self): self.provider_mock.authenticate.side_effect = self.LOGIN_ERROR self.assertRaises(errors.PluginError, self.client.add_txt_record, DOMAIN, self.record_name, self.record_content) def test_add_txt_record_fail_to_authenticate_with_unknown_error(self): self.provider_mock.authenticate.side_effect = self.UNKNOWN_LOGIN_ERROR self.assertRaises(errors.PluginError, self.client.add_txt_record, DOMAIN, self.record_name, self.record_content) def test_add_txt_record_error_finding_domain(self): self.provider_mock.authenticate.side_effect = self.GENERIC_ERROR self.assertRaises(errors.PluginError, self.client.add_txt_record, DOMAIN, self.record_name, self.record_content) def test_add_txt_record_error_adding_record(self): self.provider_mock.create_record.side_effect = self.GENERIC_ERROR self.assertRaises(errors.PluginError, self.client.add_txt_record, DOMAIN, self.record_name, self.record_content) def test_del_txt_record(self): self.client.del_txt_record(DOMAIN, self.record_name, self.record_content) self.provider_mock.delete_record.assert_called_with(type='TXT', name=self.record_name, content=self.record_content) def test_del_txt_record_fail_to_find_domain(self): self.provider_mock.authenticate.side_effect = [self.DOMAIN_NOT_FOUND, self.DOMAIN_NOT_FOUND, self.DOMAIN_NOT_FOUND, ] self.client.del_txt_record(DOMAIN, self.record_name, self.record_content) def test_del_txt_record_fail_to_authenticate(self): self.provider_mock.authenticate.side_effect = self.LOGIN_ERROR self.client.del_txt_record(DOMAIN, self.record_name, self.record_content) def test_del_txt_record_fail_to_authenticate_with_unknown_error(self): self.provider_mock.authenticate.side_effect = self.UNKNOWN_LOGIN_ERROR self.client.del_txt_record(DOMAIN, self.record_name, self.record_content) def test_del_txt_record_error_finding_domain(self): self.provider_mock.authenticate.side_effect = self.GENERIC_ERROR self.client.del_txt_record(DOMAIN, self.record_name, self.record_content) def test_del_txt_record_error_deleting_record(self): self.provider_mock.delete_record.side_effect = self.GENERIC_ERROR self.client.del_txt_record(DOMAIN, self.record_name, self.record_content) certbot-0.27.0/certbot/plugins/common_test.py0000644000175000017500000004104213344054434021463 0ustar ericaerica00000000000000"""Tests for certbot.plugins.common.""" import functools import os import shutil import tempfile import unittest import josepy as jose import mock import OpenSSL from acme import challenges from certbot import achallenges from certbot import crypto_util from certbot import errors from certbot.tests import acme_util from certbot.tests import util as test_util AUTH_KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem")) ACHALLS = [ achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.chall_to_challb( challenges.TLSSNI01(token=b'token1'), "pending"), domain="encryption-example.demo", account_key=AUTH_KEY), achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.chall_to_challb( challenges.TLSSNI01(token=b'token2'), "pending"), domain="certbot.demo", account_key=AUTH_KEY), ] class NamespaceFunctionsTest(unittest.TestCase): """Tests for certbot.plugins.common.*_namespace functions.""" def test_option_namespace(self): from certbot.plugins.common import option_namespace self.assertEqual("foo-", option_namespace("foo")) def test_dest_namespace(self): from certbot.plugins.common import dest_namespace self.assertEqual("foo_", dest_namespace("foo")) def test_dest_namespace_with_dashes(self): from certbot.plugins.common import dest_namespace self.assertEqual("foo_bar_", dest_namespace("foo-bar")) class PluginTest(unittest.TestCase): """Test for certbot.plugins.common.Plugin.""" def setUp(self): from certbot.plugins.common import Plugin class MockPlugin(Plugin): # pylint: disable=missing-docstring @classmethod def add_parser_arguments(cls, add): add("foo-bar", dest="different_to_foo_bar", x=1, y=None) self.plugin_cls = MockPlugin self.config = mock.MagicMock() self.plugin = MockPlugin(config=self.config, name="mock") def test_init(self): self.assertEqual("mock", self.plugin.name) self.assertEqual(self.config, self.plugin.config) def test_option_namespace(self): self.assertEqual("mock-", self.plugin.option_namespace) def test_option_name(self): self.assertEqual("mock-foo_bar", self.plugin.option_name("foo_bar")) def test_dest_namespace(self): self.assertEqual("mock_", self.plugin.dest_namespace) def test_dest(self): self.assertEqual("mock_foo_bar", self.plugin.dest("foo-bar")) self.assertEqual("mock_foo_bar", self.plugin.dest("foo_bar")) def test_conf(self): self.assertEqual(self.config.mock_foo_bar, self.plugin.conf("foo-bar")) def test_inject_parser_options(self): parser = mock.MagicMock() self.plugin_cls.inject_parser_options(parser, "mock") # note that inject_parser_options doesn't check if dest has # correct prefix parser.add_argument.assert_called_once_with( "--mock-foo-bar", dest="different_to_foo_bar", x=1, y=None) class InstallerTest(test_util.ConfigTestCase): """Tests for certbot.plugins.common.Installer.""" def setUp(self): super(InstallerTest, self).setUp() os.mkdir(self.config.config_dir) from certbot.plugins.common import Installer with mock.patch("certbot.plugins.common.reverter.Reverter"): self.installer = Installer(config=self.config, name="Installer") self.reverter = self.installer.reverter def test_add_to_real_checkpoint(self): files = set(("foo.bar", "baz.qux",)) save_notes = "foo bar baz qux" self._test_wrapped_method("add_to_checkpoint", files, save_notes) def test_add_to_real_checkpoint2(self): self._test_add_to_checkpoint_common(False) def test_add_to_temporary_checkpoint(self): self._test_add_to_checkpoint_common(True) def _test_add_to_checkpoint_common(self, temporary): files = set(("foo.bar", "baz.qux",)) save_notes = "foo bar baz qux" installer_func = functools.partial(self.installer.add_to_checkpoint, temporary=temporary) if temporary: reverter_func = self.reverter.add_to_temp_checkpoint else: reverter_func = self.reverter.add_to_checkpoint self._test_adapted_method( installer_func, reverter_func, files, save_notes) def test_finalize_checkpoint(self): self._test_wrapped_method("finalize_checkpoint", "foo") def test_recovery_routine(self): self._test_wrapped_method("recovery_routine") def test_revert_temporary_config(self): self._test_wrapped_method("revert_temporary_config") def test_rollback_checkpoints(self): self._test_wrapped_method("rollback_checkpoints", 42) def test_view_config_changes(self): self._test_wrapped_method("view_config_changes") def _test_wrapped_method(self, name, *args, **kwargs): """Test a wrapped reverter method. :param str name: name of the method to test :param tuple args: position arguments to method :param dict kwargs: keyword arguments to method """ installer_func = getattr(self.installer, name) reverter_func = getattr(self.reverter, name) self._test_adapted_method( installer_func, reverter_func, *args, **kwargs) def _test_adapted_method(self, installer_func, reverter_func, *passed_args, **passed_kwargs): """Test an adapted reverter method :param callable installer_func: installer method to test :param mock.MagicMock reverter_func: mocked adapated reverter method :param tuple passed_args: positional arguments passed from installer method to the reverter method :param dict passed_kargs: keyword arguments passed from installer method to the reverter method """ installer_func(*passed_args, **passed_kwargs) reverter_func.assert_called_once_with(*passed_args, **passed_kwargs) reverter_func.side_effect = errors.ReverterError self.assertRaises( errors.PluginError, installer_func, *passed_args, **passed_kwargs) def test_install_ssl_dhparams(self): self.installer.install_ssl_dhparams() self.assertTrue(os.path.isfile(self.installer.ssl_dhparams)) def _current_ssl_dhparams_hash(self): from certbot.constants import SSL_DHPARAMS_SRC return crypto_util.sha256sum(SSL_DHPARAMS_SRC) def test_current_file_hash_in_all_hashes(self): from certbot.constants import ALL_SSL_DHPARAMS_HASHES self.assertTrue(self._current_ssl_dhparams_hash() in ALL_SSL_DHPARAMS_HASHES, "Constants.ALL_SSL_DHPARAMS_HASHES must be appended" " with the sha256 hash of self.config.ssl_dhparams when it is updated.") class AddrTest(unittest.TestCase): """Tests for certbot.client.plugins.common.Addr.""" def setUp(self): from certbot.plugins.common import Addr self.addr1 = Addr.fromstring("192.168.1.1") self.addr2 = Addr.fromstring("192.168.1.1:*") self.addr3 = Addr.fromstring("192.168.1.1:80") self.addr4 = Addr.fromstring("[fe00::1]") self.addr5 = Addr.fromstring("[fe00::1]:*") self.addr6 = Addr.fromstring("[fe00::1]:80") self.addr7 = Addr.fromstring("[fe00::1]:5") self.addr8 = Addr.fromstring("[fe00:1:2:3:4:5:6:7:8:9]:8080") def test_fromstring(self): self.assertEqual(self.addr1.get_addr(), "192.168.1.1") self.assertEqual(self.addr1.get_port(), "") self.assertEqual(self.addr2.get_addr(), "192.168.1.1") self.assertEqual(self.addr2.get_port(), "*") self.assertEqual(self.addr3.get_addr(), "192.168.1.1") self.assertEqual(self.addr3.get_port(), "80") self.assertEqual(self.addr4.get_addr(), "[fe00::1]") self.assertEqual(self.addr4.get_port(), "") self.assertEqual(self.addr5.get_addr(), "[fe00::1]") self.assertEqual(self.addr5.get_port(), "*") self.assertEqual(self.addr6.get_addr(), "[fe00::1]") self.assertEqual(self.addr6.get_port(), "80") self.assertEqual(self.addr6.get_ipv6_exploded(), "fe00:0:0:0:0:0:0:1") self.assertEqual(self.addr1.get_ipv6_exploded(), "") self.assertEqual(self.addr7.get_port(), "5") self.assertEqual(self.addr8.get_ipv6_exploded(), "fe00:1:2:3:4:5:6:7") def test_str(self): self.assertEqual(str(self.addr1), "192.168.1.1") self.assertEqual(str(self.addr2), "192.168.1.1:*") self.assertEqual(str(self.addr3), "192.168.1.1:80") self.assertEqual(str(self.addr4), "[fe00::1]") self.assertEqual(str(self.addr5), "[fe00::1]:*") self.assertEqual(str(self.addr6), "[fe00::1]:80") def test_get_addr_obj(self): self.assertEqual(str(self.addr1.get_addr_obj("443")), "192.168.1.1:443") self.assertEqual(str(self.addr2.get_addr_obj("")), "192.168.1.1") self.assertEqual(str(self.addr1.get_addr_obj("*")), "192.168.1.1:*") self.assertEqual(str(self.addr4.get_addr_obj("443")), "[fe00::1]:443") self.assertEqual(str(self.addr5.get_addr_obj("")), "[fe00::1]") self.assertEqual(str(self.addr4.get_addr_obj("*")), "[fe00::1]:*") def test_eq(self): self.assertEqual(self.addr1, self.addr2.get_addr_obj("")) self.assertNotEqual(self.addr1, self.addr2) self.assertFalse(self.addr1 == 3333) self.assertEqual(self.addr4, self.addr4.get_addr_obj("")) self.assertNotEqual(self.addr4, self.addr5) self.assertFalse(self.addr4 == 3333) from certbot.plugins.common import Addr self.assertEqual(self.addr4, Addr.fromstring("[fe00:0:0::1]")) self.assertEqual(self.addr4, Addr.fromstring("[fe00:0::0:0:1]")) def test_set_inclusion(self): from certbot.plugins.common import Addr set_a = set([self.addr1, self.addr2]) addr1b = Addr.fromstring("192.168.1.1") addr2b = Addr.fromstring("192.168.1.1:*") set_b = set([addr1b, addr2b]) self.assertEqual(set_a, set_b) set_c = set([self.addr4, self.addr5]) addr4b = Addr.fromstring("[fe00::1]") addr5b = Addr.fromstring("[fe00::1]:*") set_d = set([addr4b, addr5b]) self.assertEqual(set_c, set_d) class ChallengePerformerTest(unittest.TestCase): """Tests for certbot.plugins.common.ChallengePerformer.""" def setUp(self): configurator = mock.MagicMock() from certbot.plugins.common import ChallengePerformer self.performer = ChallengePerformer(configurator) def test_add_chall(self): self.performer.add_chall(ACHALLS[0], 0) self.assertEqual(1, len(self.performer.achalls)) self.assertEqual([0], self.performer.indices) def test_perform(self): self.assertRaises(NotImplementedError, self.performer.perform) class TLSSNI01Test(unittest.TestCase): """Tests for certbot.plugins.common.TLSSNI01.""" def setUp(self): self.tempdir = tempfile.mkdtemp() configurator = mock.MagicMock() configurator.config.config_dir = os.path.join(self.tempdir, "config") configurator.config.work_dir = os.path.join(self.tempdir, "work") from certbot.plugins.common import TLSSNI01 self.sni = TLSSNI01(configurator=configurator) def tearDown(self): shutil.rmtree(self.tempdir) def test_setup_challenge_cert(self): # This is a helper function that can be used for handling # open context managers more elegantly. It avoids dealing with # __enter__ and __exit__ calls. # http://www.voidspace.org.uk/python/mock/helpers.html#mock.mock_open mock_open, mock_safe_open = mock.mock_open(), mock.mock_open() response = challenges.TLSSNI01Response() achall = mock.MagicMock() achall.chall.encode.return_value = "token" key = test_util.load_pyopenssl_private_key("rsa512_key.pem") achall.response_and_validation.return_value = ( response, (test_util.load_cert("cert_512.pem"), key)) with mock.patch("certbot.plugins.common.open", mock_open, create=True): with mock.patch("certbot.plugins.common.util.safe_open", mock_safe_open): # pylint: disable=protected-access self.assertEqual(response, self.sni._setup_challenge_cert( achall, "randomS1")) # pylint: disable=no-member mock_open.assert_called_once_with(self.sni.get_cert_path(achall), "wb") mock_open.return_value.write.assert_called_once_with( test_util.load_vector("cert_512.pem")) mock_safe_open.assert_called_once_with( self.sni.get_key_path(achall), "wb", chmod=0o400) mock_safe_open.return_value.write.assert_called_once_with( OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key)) def test_get_z_domain(self): achall = ACHALLS[0] self.assertEqual(self.sni.get_z_domain(achall), achall.response(achall.account_key).z_domain.decode("utf-8")) class InstallVersionControlledFileTest(test_util.TempDirTestCase): """Tests for certbot.plugins.common.install_version_controlled_file.""" def setUp(self): super(InstallVersionControlledFileTest, self).setUp() self.hashes = ["someotherhash"] self.dest_path = os.path.join(self.tempdir, "options-ssl-dest.conf") self.hash_path = os.path.join(self.tempdir, ".options-ssl-conf.txt") self.old_path = os.path.join(self.tempdir, "options-ssl-old.conf") self.source_path = os.path.join(self.tempdir, "options-ssl-src.conf") for path in (self.source_path, self.old_path,): with open(path, "w") as f: f.write(path) self.hashes.append(crypto_util.sha256sum(path)) def _call(self): from certbot.plugins.common import install_version_controlled_file install_version_controlled_file(self.dest_path, self.hash_path, self.source_path, self.hashes) def _current_file_hash(self): return crypto_util.sha256sum(self.source_path) def _assert_current_file(self): self.assertTrue(os.path.isfile(self.dest_path)) self.assertEqual(crypto_util.sha256sum(self.dest_path), self._current_file_hash()) def test_no_file(self): self.assertFalse(os.path.isfile(self.dest_path)) self._call() self._assert_current_file() def test_current_file(self): # 1st iteration installs the file, the 2nd checks if it needs updating for _ in range(2): self._call() self._assert_current_file() def test_prev_file_updates_to_current(self): shutil.copyfile(self.old_path, self.dest_path) self._call() self._assert_current_file() def test_manually_modified_current_file_does_not_update(self): self._call() with open(self.dest_path, "a") as mod_ssl_conf: mod_ssl_conf.write("a new line for the wrong hash\n") with mock.patch("certbot.plugins.common.logger") as mock_logger: self._call() self.assertFalse(mock_logger.warning.called) self.assertTrue(os.path.isfile(self.dest_path)) self.assertEqual(crypto_util.sha256sum(self.source_path), self._current_file_hash()) self.assertNotEqual(crypto_util.sha256sum(self.dest_path), self._current_file_hash()) def test_manually_modified_past_file_warns(self): with open(self.dest_path, "a") as mod_ssl_conf: mod_ssl_conf.write("a new line for the wrong hash\n") with open(self.hash_path, "w") as f: f.write("hashofanoldversion") with mock.patch("certbot.plugins.common.logger") as mock_logger: self._call() self.assertEqual(mock_logger.warning.call_args[0][0], "%s has been manually modified; updated file " "saved to %s. We recommend updating %s for security purposes.") self.assertEqual(crypto_util.sha256sum(self.source_path), self._current_file_hash()) # only print warning once with mock.patch("certbot.plugins.common.logger") as mock_logger: self._call() self.assertFalse(mock_logger.warning.called) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/dns_common_test.py0000644000175000017500000002040213344054434022324 0ustar ericaerica00000000000000"""Tests for certbot.plugins.dns_common.""" import collections import logging import os import unittest import mock from certbot import errors from certbot.display import util as display_util from certbot.plugins import dns_common from certbot.plugins import dns_test_common from certbot.tests import util class DNSAuthenticatorTest(util.TempDirTestCase, dns_test_common.BaseAuthenticatorTest): # pylint: disable=protected-access class _FakeDNSAuthenticator(dns_common.DNSAuthenticator): _setup_credentials = mock.MagicMock() _perform = mock.MagicMock() _cleanup = mock.MagicMock() def __init__(self, *args, **kwargs): # pylint: disable=protected-access super(DNSAuthenticatorTest._FakeDNSAuthenticator, self).__init__(*args, **kwargs) def more_info(self): # pylint: disable=missing-docstring,no-self-use return 'A fake authenticator for testing.' class _FakeConfig(object): fake_propagation_seconds = 0 fake_config_key = 1 fake_other_key = None fake_file_path = None def setUp(self): super(DNSAuthenticatorTest, self).setUp() self.config = DNSAuthenticatorTest._FakeConfig() self.auth = DNSAuthenticatorTest._FakeDNSAuthenticator(self.config, "fake") def test_perform(self): self.auth.perform([self.achall]) self.auth._perform.assert_called_once_with(dns_test_common.DOMAIN, mock.ANY, mock.ANY) def test_cleanup(self): self.auth._attempt_cleanup = True self.auth.cleanup([self.achall]) self.auth._cleanup.assert_called_once_with(dns_test_common.DOMAIN, mock.ANY, mock.ANY) @util.patch_get_utility() def test_prompt(self, mock_get_utility): mock_display = mock_get_utility() mock_display.input.side_effect = ((display_util.OK, "",), (display_util.OK, "value",)) self.auth._configure("other_key", "") self.assertEqual(self.auth.config.fake_other_key, "value") @util.patch_get_utility() def test_prompt_canceled(self, mock_get_utility): mock_display = mock_get_utility() mock_display.input.side_effect = ((display_util.CANCEL, "c",),) self.assertRaises(errors.PluginError, self.auth._configure, "other_key", "") @util.patch_get_utility() def test_prompt_file(self, mock_get_utility): path = os.path.join(self.tempdir, 'file.ini') open(path, "wb").close() mock_display = mock_get_utility() mock_display.directory_select.side_effect = ((display_util.OK, "",), (display_util.OK, "not-a-file.ini",), (display_util.OK, self.tempdir), (display_util.OK, path,)) self.auth._configure_file("file_path", "") self.assertEqual(self.auth.config.fake_file_path, path) @util.patch_get_utility() def test_prompt_file_canceled(self, mock_get_utility): mock_display = mock_get_utility() mock_display.directory_select.side_effect = ((display_util.CANCEL, "c",),) self.assertRaises(errors.PluginError, self.auth._configure_file, "file_path", "") def test_configure_credentials(self): path = os.path.join(self.tempdir, 'file.ini') dns_test_common.write({"fake_test": "value"}, path) setattr(self.config, "fake_credentials", path) credentials = self.auth._configure_credentials("credentials", "", {"test": ""}) self.assertEqual(credentials.conf("test"), "value") @util.patch_get_utility() def test_prompt_credentials(self, mock_get_utility): bad_path = os.path.join(self.tempdir, 'bad-file.ini') dns_test_common.write({"fake_other": "other_value"}, bad_path) path = os.path.join(self.tempdir, 'file.ini') dns_test_common.write({"fake_test": "value"}, path) setattr(self.config, "fake_credentials", "") mock_display = mock_get_utility() mock_display.directory_select.side_effect = ((display_util.OK, "",), (display_util.OK, "not-a-file.ini",), (display_util.OK, self.tempdir), (display_util.OK, bad_path), (display_util.OK, path,)) credentials = self.auth._configure_credentials("credentials", "", {"test": ""}) self.assertEqual(credentials.conf("test"), "value") class CredentialsConfigurationTest(util.TempDirTestCase): class _MockLoggingHandler(logging.Handler): messages = None def __init__(self, *args, **kwargs): self.reset() logging.Handler.__init__(self, *args, **kwargs) def emit(self, record): self.messages[record.levelname.lower()].append(record.getMessage()) def reset(self): """Allows the handler to be reset between tests.""" self.messages = collections.defaultdict(list) def test_valid_file(self): path = os.path.join(self.tempdir, 'too-permissive-file.ini') dns_test_common.write({"test": "value", "other": 1}, path) credentials_configuration = dns_common.CredentialsConfiguration(path) self.assertEqual("value", credentials_configuration.conf("test")) self.assertEqual("1", credentials_configuration.conf("other")) def test_nonexistent_file(self): path = os.path.join(self.tempdir, 'not-a-file.ini') self.assertRaises(errors.PluginError, dns_common.CredentialsConfiguration, path) def test_valid_file_with_unsafe_permissions(self): log = self._MockLoggingHandler() dns_common.logger.addHandler(log) path = os.path.join(self.tempdir, 'too-permissive-file.ini') open(path, "wb").close() dns_common.CredentialsConfiguration(path) self.assertEqual(1, len([_ for _ in log.messages['warning'] if _.startswith("Unsafe")])) class CredentialsConfigurationRequireTest(util.TempDirTestCase): def setUp(self): super(CredentialsConfigurationRequireTest, self).setUp() self.path = os.path.join(self.tempdir, 'file.ini') def _write(self, values): dns_test_common.write(values, self.path) def test_valid(self): self._write({"test": "value", "other": 1}) credentials_configuration = dns_common.CredentialsConfiguration(self.path) credentials_configuration.require({"test": "", "other": ""}) def test_valid_but_extra(self): self._write({"test": "value", "other": 1}) credentials_configuration = dns_common.CredentialsConfiguration(self.path) credentials_configuration.require({"test": ""}) def test_valid_empty(self): self._write({}) credentials_configuration = dns_common.CredentialsConfiguration(self.path) credentials_configuration.require({}) def test_missing(self): self._write({}) credentials_configuration = dns_common.CredentialsConfiguration(self.path) self.assertRaises(errors.PluginError, credentials_configuration.require, {"test": ""}) def test_blank(self): self._write({"test": ""}) credentials_configuration = dns_common.CredentialsConfiguration(self.path) self.assertRaises(errors.PluginError, credentials_configuration.require, {"test": ""}) def test_typo(self): self._write({"tets": "typo!"}) credentials_configuration = dns_common.CredentialsConfiguration(self.path) self.assertRaises(errors.PluginError, credentials_configuration.require, {"test": ""}) class DomainNameGuessTest(unittest.TestCase): def test_simple_case(self): self.assertTrue( 'example.com' in dns_common.base_domain_name_guesses("example.com") ) def test_sub_domain(self): self.assertTrue( 'example.com' in dns_common.base_domain_name_guesses("foo.bar.baz.example.com") ) def test_second_level_domain(self): self.assertTrue( 'example.co.uk' in dns_common.base_domain_name_guesses("foo.bar.baz.example.co.uk") ) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/standalone.py0000644000175000017500000002655613344054434021301 0ustar ericaerica00000000000000"""Standalone Authenticator.""" import argparse import collections import logging import socket # https://github.com/python/typeshed/blob/master/stdlib/2and3/socket.pyi from socket import errno as socket_errors # type: ignore import OpenSSL import six import zope.interface from acme import challenges from acme import standalone as acme_standalone # pylint: disable=unused-import, no-name-in-module from acme.magic_typing import DefaultDict, Dict, Set, Tuple, List, Type, TYPE_CHECKING from certbot import achallenges # pylint: disable=unused-import from certbot import errors from certbot import interfaces from certbot.plugins import common logger = logging.getLogger(__name__) if TYPE_CHECKING: ServedType = DefaultDict[ acme_standalone.BaseDualNetworkedServers, Set[achallenges.KeyAuthorizationAnnotatedChallenge] ] class ServerManager(object): """Standalone servers manager. Manager for `ACMEServer` and `ACMETLSServer` instances. `certs` and `http_01_resources` correspond to `acme.crypto_util.SSLSocket.certs` and `acme.crypto_util.SSLSocket.http_01_resources` respectively. All created servers share the same certificates and resources, so if you're running both TLS and non-TLS instances, HTTP01 handlers will serve the same URLs! """ def __init__(self, certs, http_01_resources): self._instances = {} # type: Dict[int, acme_standalone.BaseDualNetworkedServers] self.certs = certs self.http_01_resources = http_01_resources def run(self, port, challenge_type, listenaddr=""): """Run ACME server on specified ``port``. This method is idempotent, i.e. all calls with the same pair of ``(port, challenge_type)`` will reuse the same server. :param int port: Port to run the server on. :param challenge_type: Subclass of `acme.challenges.Challenge`, either `acme.challenge.HTTP01` or `acme.challenges.TLSSNI01`. :param str listenaddr: (optional) The address to listen on. Defaults to all addrs. :returns: DualNetworkedServers instance. :rtype: ACMEServerMixin """ assert challenge_type in (challenges.TLSSNI01, challenges.HTTP01) if port in self._instances: return self._instances[port] address = (listenaddr, port) try: if challenge_type is challenges.TLSSNI01: servers = acme_standalone.TLSSNI01DualNetworkedServers( address, self.certs) # type: acme_standalone.BaseDualNetworkedServers else: # challenges.HTTP01 servers = acme_standalone.HTTP01DualNetworkedServers( address, self.http_01_resources) except socket.error as error: raise errors.StandaloneBindError(error, port) servers.serve_forever() # if port == 0, then random free port on OS is taken # pylint: disable=no-member # both servers, if they exist, have the same port real_port = servers.getsocknames()[0][1] self._instances[real_port] = servers return servers def stop(self, port): """Stop ACME server running on the specified ``port``. :param int port: """ instance = self._instances[port] for sockname in instance.getsocknames(): logger.debug("Stopping server at %s:%d...", *sockname[:2]) # Not calling server_close causes problems when renewing multiple # certs with `certbot renew` using TLSSNI01 and PyOpenSSL 0.13 instance.shutdown_and_server_close() del self._instances[port] def running(self): """Return all running instances. Once the server is stopped using `stop`, it will not be returned. :returns: Mapping from ``port`` to ``servers``. :rtype: tuple """ return self._instances.copy() SUPPORTED_CHALLENGES = [challenges.TLSSNI01, challenges.HTTP01] \ # type: List[Type[challenges.KeyAuthorizationChallenge]] class SupportedChallengesAction(argparse.Action): """Action class for parsing standalone_supported_challenges.""" def __call__(self, parser, namespace, values, option_string=None): logger.warning( "The standalone specific supported challenges flag is " "deprecated. Please use the --preferred-challenges flag " "instead.") converted_values = self._convert_and_validate(values) namespace.standalone_supported_challenges = converted_values def _convert_and_validate(self, data): """Validate the value of supported challenges provided by the user. References to "dvsni" are automatically converted to "tls-sni-01". :param str data: comma delimited list of challenge types :returns: validated and converted list of challenge types :rtype: str """ challs = data.split(",") # tls-sni-01 was dvsni during private beta if "dvsni" in challs: logger.info( "Updating legacy standalone_supported_challenges value") challs = [challenges.TLSSNI01.typ if chall == "dvsni" else chall for chall in challs] data = ",".join(challs) unrecognized = [name for name in challs if name not in challenges.Challenge.TYPES] # argparse.ArgumentErrors raised out of argparse.Action objects # are caught by argparse which prints usage information and the # error that occurred before calling sys.exit. if unrecognized: raise argparse.ArgumentError( self, "Unrecognized challenges: {0}".format(", ".join(unrecognized))) choices = set(chall.typ for chall in SUPPORTED_CHALLENGES) if not set(challs).issubset(choices): raise argparse.ArgumentError( self, "Plugin does not support the following (valid) " "challenges: {0}".format(", ".join(set(challs) - choices))) return data @zope.interface.implementer(interfaces.IAuthenticator) @zope.interface.provider(interfaces.IPluginFactory) class Authenticator(common.Plugin): """Standalone Authenticator. This authenticator creates its own ephemeral TCP listener on the necessary port in order to respond to incoming tls-sni-01 and http-01 challenges from the certificate authority. Therefore, it does not rely on any existing server program. """ description = "Spin up a temporary webserver" def __init__(self, *args, **kwargs): super(Authenticator, self).__init__(*args, **kwargs) # one self-signed key for all tls-sni-01 certificates self.key = OpenSSL.crypto.PKey() self.key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048) self.served = collections.defaultdict(set) # type: ServedType # Stuff below is shared across threads (i.e. servers read # values, main thread writes). Due to the nature of CPython's # GIL, the operations are safe, c.f. # https://docs.python.org/2/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe self.certs = {} # type: Dict[bytes, Tuple[OpenSSL.crypto.PKey, OpenSSL.crypto.X509]] self.http_01_resources = set() \ # type: Set[acme_standalone.HTTP01RequestHandler.HTTP01Resource] self.servers = ServerManager(self.certs, self.http_01_resources) @classmethod def add_parser_arguments(cls, add): add("supported-challenges", help=argparse.SUPPRESS, action=SupportedChallengesAction, default=",".join(chall.typ for chall in SUPPORTED_CHALLENGES)) @property def supported_challenges(self): """Challenges supported by this plugin.""" return [challenges.Challenge.TYPES[name] for name in self.conf("supported-challenges").split(",")] def more_info(self): # pylint: disable=missing-docstring return("This authenticator creates its own ephemeral TCP listener " "on the necessary port in order to respond to incoming " "tls-sni-01 and http-01 challenges from the certificate " "authority. Therefore, it does not rely on any existing " "server program.") def prepare(self): # pylint: disable=missing-docstring pass def get_chall_pref(self, domain): # pylint: disable=unused-argument,missing-docstring return self.supported_challenges def perform(self, achalls): # pylint: disable=missing-docstring return [self._try_perform_single(achall) for achall in achalls] def _try_perform_single(self, achall): while True: try: return self._perform_single(achall) except errors.StandaloneBindError as error: _handle_perform_error(error) def _perform_single(self, achall): if isinstance(achall.chall, challenges.HTTP01): servers, response = self._perform_http_01(achall) else: # tls-sni-01 servers, response = self._perform_tls_sni_01(achall) self.served[servers].add(achall) return response def _perform_http_01(self, achall): port = self.config.http01_port addr = self.config.http01_address servers = self.servers.run(port, challenges.HTTP01, listenaddr=addr) response, validation = achall.response_and_validation() resource = acme_standalone.HTTP01RequestHandler.HTTP01Resource( chall=achall.chall, response=response, validation=validation) self.http_01_resources.add(resource) return servers, response def _perform_tls_sni_01(self, achall): port = self.config.tls_sni_01_port addr = self.config.tls_sni_01_address servers = self.servers.run(port, challenges.TLSSNI01, listenaddr=addr) response, (cert, _) = achall.response_and_validation(cert_key=self.key) self.certs[response.z_domain] = (self.key, cert) return servers, response def cleanup(self, achalls): # pylint: disable=missing-docstring # reduce self.served and close servers if no challenges are served for unused_servers, server_achalls in self.served.items(): for achall in achalls: if achall in server_achalls: server_achalls.remove(achall) for port, servers in six.iteritems(self.servers.running()): if not self.served[servers]: self.servers.stop(port) def _handle_perform_error(error): if error.socket_error.errno == socket_errors.EACCES: raise errors.PluginError( "Could not bind TCP port {0} because you don't have " "the appropriate permissions (for example, you " "aren't running this program as " "root).".format(error.port)) elif error.socket_error.errno == socket_errors.EADDRINUSE: display = zope.component.getUtility(interfaces.IDisplay) msg = ( "Could not bind TCP port {0} because it is already in " "use by another process on this system (such as a web " "server). Please stop the program in question and " "then try again.".format(error.port)) should_retry = display.yesno(msg, "Retry", "Cancel", default=False) if not should_retry: raise errors.PluginError(msg) else: raise certbot-0.27.0/certbot/plugins/common.py0000644000175000017500000004163113344054434020430 0ustar ericaerica00000000000000"""Plugin common functions.""" import logging import os import re import shutil import tempfile import OpenSSL import pkg_resources import zope.interface from josepy import util as jose_util from acme.magic_typing import List # pylint: disable=unused-import, no-name-in-module from certbot import achallenges # pylint: disable=unused-import from certbot import constants from certbot import crypto_util from certbot import errors from certbot import interfaces from certbot import reverter from certbot import util from certbot.plugins.storage import PluginStorage logger = logging.getLogger(__name__) def option_namespace(name): """ArgumentParser options namespace (prefix of all options).""" return name + "-" def dest_namespace(name): """ArgumentParser dest namespace (prefix of all destinations).""" return name.replace("-", "_") + "_" private_ips_regex = re.compile( r"(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|" r"(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)") hostname_regex = re.compile( r"^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*[a-z]+$", re.IGNORECASE) @zope.interface.implementer(interfaces.IPlugin) class Plugin(object): """Generic plugin.""" # provider is not inherited, subclasses must define it on their own # @zope.interface.provider(interfaces.IPluginFactory) def __init__(self, config, name): self.config = config self.name = name @jose_util.abstractclassmethod def add_parser_arguments(cls, add): """Add plugin arguments to the CLI argument parser. NOTE: If some of your flags interact with others, you can use cli.report_config_interaction to register this to ensure values are correctly saved/overridable during renewal. :param callable add: Function that proxies calls to `argparse.ArgumentParser.add_argument` prepending options with unique plugin name prefix. """ @classmethod def inject_parser_options(cls, parser, name): """Inject parser options. See `~.IPlugin.inject_parser_options` for docs. """ # dummy function, doesn't check if dest.startswith(self.dest_namespace) def add(arg_name_no_prefix, *args, **kwargs): # pylint: disable=missing-docstring return parser.add_argument( "--{0}{1}".format(option_namespace(name), arg_name_no_prefix), *args, **kwargs) return cls.add_parser_arguments(add) @property def option_namespace(self): """ArgumentParser options namespace (prefix of all options).""" return option_namespace(self.name) def option_name(self, name): """Option name (include plugin namespace).""" return self.option_namespace + name @property def dest_namespace(self): """ArgumentParser dest namespace (prefix of all destinations).""" return dest_namespace(self.name) def dest(self, var): """Find a destination for given variable ``var``.""" # this should do exactly the same what ArgumentParser(arg), # does to "arg" to compute "dest" return self.dest_namespace + var.replace("-", "_") def conf(self, var): """Find a configuration value for variable ``var``.""" return getattr(self.config, self.dest(var)) class Installer(Plugin): """An installer base class with reverter and ssl_dhparam methods defined. Installer plugins do not have to inherit from this class. """ def __init__(self, *args, **kwargs): super(Installer, self).__init__(*args, **kwargs) self.storage = PluginStorage(self.config, self.name) self.reverter = reverter.Reverter(self.config) def add_to_checkpoint(self, save_files, save_notes, temporary=False): """Add files to a checkpoint. :param set save_files: set of filepaths to save :param str save_notes: notes about changes during the save :param bool temporary: True if the files should be added to a temporary checkpoint rather than a permanent one. This is usually used for changes that will soon be reverted. :raises .errors.PluginError: when unable to add to checkpoint """ if temporary: checkpoint_func = self.reverter.add_to_temp_checkpoint else: checkpoint_func = self.reverter.add_to_checkpoint try: checkpoint_func(save_files, save_notes) except errors.ReverterError as err: raise errors.PluginError(str(err)) def finalize_checkpoint(self, title): """Timestamp and save changes made through the reverter. :param str title: Title describing checkpoint :raises .errors.PluginError: when an error occurs """ try: self.reverter.finalize_checkpoint(title) except errors.ReverterError as err: raise errors.PluginError(str(err)) def recovery_routine(self): """Revert all previously modified files. Reverts all modified files that have not been saved as a checkpoint :raises .errors.PluginError: If unable to recover the configuration """ try: self.reverter.recovery_routine() except errors.ReverterError as err: raise errors.PluginError(str(err)) def revert_temporary_config(self): """Rollback temporary checkpoint. :raises .errors.PluginError: when unable to revert config """ try: self.reverter.revert_temporary_config() except errors.ReverterError as err: raise errors.PluginError(str(err)) def rollback_checkpoints(self, rollback=1): """Rollback saved checkpoints. :param int rollback: Number of checkpoints to revert :raises .errors.PluginError: If there is a problem with the input or the function is unable to correctly revert the configuration """ try: self.reverter.rollback_checkpoints(rollback) except errors.ReverterError as err: raise errors.PluginError(str(err)) def view_config_changes(self): """Show all of the configuration changes that have taken place. :raises .errors.PluginError: If there is a problem while processing the checkpoints directories. """ try: self.reverter.view_config_changes() except errors.ReverterError as err: raise errors.PluginError(str(err)) @property def ssl_dhparams(self): """Full absolute path to ssl_dhparams file.""" return os.path.join(self.config.config_dir, constants.SSL_DHPARAMS_DEST) @property def updated_ssl_dhparams_digest(self): """Full absolute path to digest of updated ssl_dhparams file.""" return os.path.join(self.config.config_dir, constants.UPDATED_SSL_DHPARAMS_DIGEST) def install_ssl_dhparams(self): """Copy Certbot's ssl_dhparams file into the system's config dir if required.""" return install_version_controlled_file( self.ssl_dhparams, self.updated_ssl_dhparams_digest, constants.SSL_DHPARAMS_SRC, constants.ALL_SSL_DHPARAMS_HASHES) class Addr(object): r"""Represents an virtual host address. :param str addr: addr part of vhost address :param str port: port number or \*, or "" """ def __init__(self, tup, ipv6=False): self.tup = tup self.ipv6 = ipv6 @classmethod def fromstring(cls, str_addr): """Initialize Addr from string.""" if str_addr.startswith('['): # ipv6 addresses starts with [ endIndex = str_addr.rfind(']') host = str_addr[:endIndex + 1] port = '' if len(str_addr) > endIndex + 2 and str_addr[endIndex + 1] == ':': port = str_addr[endIndex + 2:] return cls((host, port), ipv6=True) else: tup = str_addr.partition(':') return cls((tup[0], tup[2])) def __str__(self): if self.tup[1]: return "%s:%s" % self.tup return self.tup[0] def normalized_tuple(self): """Normalized representation of addr/port tuple """ if self.ipv6: return (self.get_ipv6_exploded(), self.tup[1]) return self.tup def __eq__(self, other): if isinstance(other, self.__class__): # compare normalized to take different # styles of representation into account return self.normalized_tuple() == other.normalized_tuple() return False def __hash__(self): return hash(self.tup) def get_addr(self): """Return addr part of Addr object.""" return self.tup[0] def get_port(self): """Return port.""" return self.tup[1] def get_addr_obj(self, port): """Return new address object with same addr and new port.""" return self.__class__((self.tup[0], port), self.ipv6) def _normalize_ipv6(self, addr): """Return IPv6 address in normalized form, helper function""" addr = addr.lstrip("[") addr = addr.rstrip("]") return self._explode_ipv6(addr) def get_ipv6_exploded(self): """Return IPv6 in normalized form""" if self.ipv6: return ":".join(self._normalize_ipv6(self.tup[0])) return "" def _explode_ipv6(self, addr): """Explode IPv6 address for comparison""" result = ['0', '0', '0', '0', '0', '0', '0', '0'] addr_list = addr.split(":") if len(addr_list) > len(result): # too long, truncate addr_list = addr_list[0:len(result)] append_to_end = False for i in range(0, len(addr_list)): block = addr_list[i] if len(block) == 0: # encountered ::, so rest of the blocks should be # appended to the end append_to_end = True continue elif len(block) > 1: # remove leading zeros block = block.lstrip("0") if not append_to_end: result[i] = str(block) else: # count the location from the end using negative indices result[i-len(addr_list)] = str(block) return result class ChallengePerformer(object): """Abstract base for challenge performers. :ivar configurator: Authenticator and installer plugin :ivar achalls: Annotated challenges :vartype achalls: `list` of `.KeyAuthorizationAnnotatedChallenge` :ivar indices: Holds the indices of challenges from a larger array so the user of the class doesn't have to. :vartype indices: `list` of `int` """ def __init__(self, configurator): self.configurator = configurator self.achalls = [] # type: List[achallenges.KeyAuthorizationAnnotatedChallenge] self.indices = [] # type: List[int] def add_chall(self, achall, idx=None): """Store challenge to be performed when perform() is called. :param .KeyAuthorizationAnnotatedChallenge achall: Annotated challenge. :param int idx: index to challenge in a larger array """ self.achalls.append(achall) if idx is not None: self.indices.append(idx) def perform(self): """Perform all added challenges. :returns: challenge respones :rtype: `list` of `acme.challenges.KeyAuthorizationChallengeResponse` """ raise NotImplementedError() class TLSSNI01(ChallengePerformer): # pylint: disable=abstract-method """Abstract base for TLS-SNI-01 challenge performers""" def __init__(self, configurator): super(TLSSNI01, self).__init__(configurator) self.challenge_conf = os.path.join( configurator.config.config_dir, "le_tls_sni_01_cert_challenge.conf") # self.completed = 0 def get_cert_path(self, achall): """Returns standardized name for challenge certificate. :param .KeyAuthorizationAnnotatedChallenge achall: Annotated tls-sni-01 challenge. :returns: certificate file name :rtype: str """ return os.path.join(self.configurator.config.work_dir, achall.chall.encode("token") + ".crt") def get_key_path(self, achall): """Get standardized path to challenge key.""" return os.path.join(self.configurator.config.work_dir, achall.chall.encode("token") + '.pem') def get_z_domain(self, achall): """Returns z_domain (SNI) name for the challenge.""" return achall.response(achall.account_key).z_domain.decode("utf-8") def _setup_challenge_cert(self, achall, cert_key=None): """Generate and write out challenge certificate.""" cert_path = self.get_cert_path(achall) key_path = self.get_key_path(achall) # Register the path before you write out the file self.configurator.reverter.register_file_creation(True, key_path) self.configurator.reverter.register_file_creation(True, cert_path) response, (cert, key) = achall.response_and_validation( cert_key=cert_key) cert_pem = OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_PEM, cert) key_pem = OpenSSL.crypto.dump_privatekey( OpenSSL.crypto.FILETYPE_PEM, key) # Write out challenge cert and key with open(cert_path, "wb") as cert_chall_fd: cert_chall_fd.write(cert_pem) with util.safe_open(key_path, 'wb', chmod=0o400) as key_file: key_file.write(key_pem) return response def install_version_controlled_file(dest_path, digest_path, src_path, all_hashes): """Copy a file into an active location (likely the system's config dir) if required. :param str dest_path: destination path for version controlled file :param str digest_path: path to save a digest of the file in :param str src_path: path to version controlled file found in distribution :param list all_hashes: hashes of every released version of the file """ current_hash = crypto_util.sha256sum(src_path) def _write_current_hash(): with open(digest_path, "w") as f: f.write(current_hash) def _install_current_file(): shutil.copyfile(src_path, dest_path) _write_current_hash() # Check to make sure options-ssl.conf is installed if not os.path.isfile(dest_path): _install_current_file() return # there's already a file there. if it's up to date, do nothing. if it's not but # it matches a known file hash, we can update it. # otherwise, print a warning once per new version. active_file_digest = crypto_util.sha256sum(dest_path) if active_file_digest == current_hash: # already up to date return elif active_file_digest in all_hashes: # safe to update _install_current_file() else: # has been manually modified, not safe to update # did they modify the current version or an old version? if os.path.isfile(digest_path): with open(digest_path, "r") as f: saved_digest = f.read() # they modified it after we either installed or told them about this version, so return if saved_digest == current_hash: return # there's a new version but we couldn't update the file, or they deleted the digest. # save the current digest so we only print this once, and print a warning _write_current_hash() logger.warning("%s has been manually modified; updated file " "saved to %s. We recommend updating %s for security purposes.", dest_path, src_path, dest_path) # test utils used by certbot_apache/certbot_nginx (hence # "pragma: no cover") TODO: this might quickly lead to dead code (also # c.f. #383) def dir_setup(test_dir, pkg): # pragma: no cover """Setup the directories necessary for the configurator.""" def expanded_tempdir(prefix): """Return the real path of a temp directory with the specified prefix Some plugins rely on real paths of symlinks for working correctly. For example, certbot-apache uses real paths of configuration files to tell a virtual host from another. On systems where TMP itself is a symbolic link, (ex: OS X) such plugins will be confused. This function prevents such a case. """ return os.path.realpath(tempfile.mkdtemp(prefix)) temp_dir = expanded_tempdir("temp") config_dir = expanded_tempdir("config") work_dir = expanded_tempdir("work") os.chmod(temp_dir, constants.CONFIG_DIRS_MODE) os.chmod(config_dir, constants.CONFIG_DIRS_MODE) os.chmod(work_dir, constants.CONFIG_DIRS_MODE) test_configs = pkg_resources.resource_filename( pkg, os.path.join("testdata", test_dir)) shutil.copytree( test_configs, os.path.join(temp_dir, test_dir), symlinks=True) return temp_dir, config_dir, work_dir certbot-0.27.0/certbot/plugins/__init__.py0000644000175000017500000000003613344054434020671 0ustar ericaerica00000000000000"""Certbot client.plugins.""" certbot-0.27.0/certbot/plugins/null_test.py0000644000175000017500000000116013344054434021142 0ustar ericaerica00000000000000"""Tests for certbot.plugins.null.""" import unittest import six import mock class InstallerTest(unittest.TestCase): """Tests for certbot.plugins.null.Installer.""" def setUp(self): from certbot.plugins.null import Installer self.installer = Installer(config=mock.MagicMock(), name="null") def test_it(self): self.assertTrue(isinstance(self.installer.more_info(), six.string_types)) self.assertEqual([], self.installer.get_all_names()) self.assertEqual([], self.installer.supported_enhancements()) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/enhancements_test.py0000644000175000017500000000456313344054434022652 0ustar ericaerica00000000000000"""Tests for new style enhancements""" import unittest import mock from certbot.plugins import enhancements from certbot.plugins import null import certbot.tests.util as test_util class EnhancementTest(test_util.ConfigTestCase): """Tests for new style enhancements in certbot.plugins.enhancements""" def setUp(self): super(EnhancementTest, self).setUp() self.mockinstaller = mock.MagicMock(spec=enhancements.AutoHSTSEnhancement) @test_util.patch_get_utility() def test_enhancement_enabled_enhancements(self, _): FAKEINDEX = [ { "name": "autohsts", "cli_dest": "auto_hsts", }, { "name": "somethingelse", "cli_dest": "something", } ] with mock.patch("certbot.plugins.enhancements._INDEX", FAKEINDEX): self.config.auto_hsts = True self.config.something = True enabled = list(enhancements.enabled_enhancements(self.config)) self.assertEqual(len(enabled), 2) self.assertTrue([i for i in enabled if i["name"] == "autohsts"]) self.assertTrue([i for i in enabled if i["name"] == "somethingelse"]) def test_are_requested(self): self.assertEquals( len([i for i in enhancements.enabled_enhancements(self.config)]), 0) self.assertFalse(enhancements.are_requested(self.config)) self.config.auto_hsts = True self.assertEquals( len([i for i in enhancements.enabled_enhancements(self.config)]), 1) self.assertTrue(enhancements.are_requested(self.config)) def test_are_supported(self): self.config.auto_hsts = True unsupported = null.Installer(self.config, "null") self.assertTrue(enhancements.are_supported(self.config, self.mockinstaller)) self.assertFalse(enhancements.are_supported(self.config, unsupported)) def test_enable(self): self.config.auto_hsts = True domains = ["example.com", "www.example.com"] lineage = "lineage" enhancements.enable(lineage, domains, self.mockinstaller, self.config) self.assertTrue(self.mockinstaller.enable_autohsts.called) self.assertEquals(self.mockinstaller.enable_autohsts.call_args[0], (lineage, domains)) if __name__ == '__main__': unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/enhancements.py0000644000175000017500000001312613344054434021606 0ustar ericaerica00000000000000"""New interface style Certbot enhancements""" import abc import six from certbot import constants from acme.magic_typing import Dict, List, Any # pylint: disable=unused-import, no-name-in-module def enabled_enhancements(config): """ Generator to yield the enabled new style enhancements. :param config: Configuration. :type config: :class:`certbot.interfaces.IConfig` """ for enh in _INDEX: if getattr(config, enh["cli_dest"]): yield enh def are_requested(config): """ Checks if one or more of the requested enhancements are those of the new enhancement interfaces. :param config: Configuration. :type config: :class:`certbot.interfaces.IConfig` """ return any(enabled_enhancements(config)) def are_supported(config, installer): """ Checks that all of the requested enhancements are supported by the installer. :param config: Configuration. :type config: :class:`certbot.interfaces.IConfig` :param installer: Installer object :type installer: interfaces.IInstaller :returns: If all the requested enhancements are supported by the installer :rtype: bool """ for enh in enabled_enhancements(config): if not isinstance(installer, enh["class"]): return False return True def enable(lineage, domains, installer, config): """ Run enable method for each requested enhancement that is supported. :param lineage: Certificate lineage object :type lineage: certbot.storage.RenewableCert :param domains: List of domains in certificate to enhance :type domains: str :param installer: Installer object :type installer: interfaces.IInstaller :param config: Configuration. :type config: :class:`certbot.interfaces.IConfig` """ for enh in enabled_enhancements(config): getattr(installer, enh["enable_function"])(lineage, domains) def populate_cli(add): """ Populates the command line flags for certbot.cli.HelpfulParser :param add: Add function of certbot.cli.HelpfulParser :type add: func """ for enh in _INDEX: add(enh["cli_groups"], enh["cli_flag"], action=enh["cli_action"], dest=enh["cli_dest"], default=enh["cli_flag_default"], help=enh["cli_help"]) @six.add_metaclass(abc.ABCMeta) class AutoHSTSEnhancement(object): """ Enhancement interface that installer plugins can implement in order to provide functionality that configures the software to have a 'Strict-Transport-Security' with initially low max-age value that will increase over time. The plugins implementing new style enhancements are responsible of handling the saving of configuration checkpoints as well as calling possible restarts of managed software themselves. For update_autohsts method, the installer may have to call prepare() to finalize the plugin initialization. Methods: enable_autohsts is called when the header is initially installed using a low max-age value. update_autohsts is called every time when Certbot is run using 'renew' verb. The max-age value should be increased over time using this method. deploy_autohsts is called for every lineage that has had its certificate renewed. A long HSTS max-age value should be set here, as we should be confident that the user is able to automatically renew their certificates. """ @abc.abstractmethod def update_autohsts(self, lineage, *args, **kwargs): """ Gets called for each lineage every time Certbot is run with 'renew' verb. Implementation of this method should increase the max-age value. :param lineage: Certificate lineage object :type lineage: certbot.storage.RenewableCert .. note:: prepare() method inherited from `interfaces.IPlugin` might need to be called manually within implementation of this interface method to finalize the plugin initialization. """ @abc.abstractmethod def deploy_autohsts(self, lineage, *args, **kwargs): """ Gets called for a lineage when its certificate is successfully renewed. Long max-age value should be set in implementation of this method. :param lineage: Certificate lineage object :type lineage: certbot.storage.RenewableCert """ @abc.abstractmethod def enable_autohsts(self, lineage, domains, *args, **kwargs): """ Enables the AutoHSTS enhancement, installing Strict-Transport-Security header with a low initial value to be increased over the subsequent runs of Certbot renew. :param lineage: Certificate lineage object :type lineage: certbot.storage.RenewableCert :param domains: List of domains in certificate to enhance :type domains: str """ # This is used to configure internal new style enhancements in Certbot. These # enhancement interfaces need to be defined in this file. Please do not modify # this list from plugin code. _INDEX = [ { "name": "AutoHSTS", "cli_help": "Gradually increasing max-age value for HTTP Strict Transport "+ "Security security header", "cli_flag": "--auto-hsts", "cli_flag_default": constants.CLI_DEFAULTS["auto_hsts"], "cli_groups": ["security", "enhance"], "cli_dest": "auto_hsts", "cli_action": "store_true", "class": AutoHSTSEnhancement, "updater_function": "update_autohsts", "deployer_function": "deploy_autohsts", "enable_function": "enable_autohsts" } ] # type: List[Dict[str, Any]] certbot-0.27.0/certbot/plugins/manual.py0000644000175000017500000002312613344054434020414 0ustar ericaerica00000000000000"""Manual authenticator plugin""" import os import zope.component import zope.interface from acme import challenges from acme.magic_typing import Dict # pylint: disable=unused-import, no-name-in-module from certbot import achallenges # pylint: disable=unused-import from certbot import interfaces from certbot import errors from certbot import hooks from certbot import reverter from certbot.plugins import common class ManualTlsSni01(common.TLSSNI01): """TLS-SNI-01 authenticator for the Manual plugin :ivar configurator: Authenticator object :type configurator: :class:`~certbot.plugins.manual.Authenticator` :ivar list achalls: Annotated class:`~certbot.achallenges.KeyAuthorizationAnnotatedChallenge` challenges :param list indices: Meant to hold indices of challenges in a larger array. NginxTlsSni01 is capable of solving many challenges at once which causes an indexing issue within NginxConfigurator who must return all responses in order. Imagine NginxConfigurator maintaining state about where all of the http-01 Challenges, TLS-SNI-01 Challenges belong in the response array. This is an optional utility. :param str challenge_conf: location of the challenge config file """ def perform(self): """Create the SSL certificates and private keys""" for achall in self.achalls: self._setup_challenge_cert(achall) @zope.interface.implementer(interfaces.IAuthenticator) @zope.interface.provider(interfaces.IPluginFactory) class Authenticator(common.Plugin): """Manual authenticator This plugin allows the user to perform the domain validation challenge(s) themselves. This either be done manually by the user or through shell scripts provided to Certbot. """ description = 'Manual configuration or run your own shell scripts' hidden = True long_description = ( 'Authenticate through manual configuration or custom shell scripts. ' 'When using shell scripts, an authenticator script must be provided. ' 'The environment variables available to this script depend on the ' 'type of challenge. $CERTBOT_DOMAIN will always contain the domain ' 'being authenticated. For HTTP-01 and DNS-01, $CERTBOT_VALIDATION ' 'is the validation string, and $CERTBOT_TOKEN is the filename of the ' 'resource requested when performing an HTTP-01 challenge. When ' 'performing a TLS-SNI-01 challenge, $CERTBOT_SNI_DOMAIN will contain ' 'the SNI name for which the ACME server expects to be presented with ' 'the self-signed certificate located at $CERTBOT_CERT_PATH. The ' 'secret key needed to complete the TLS handshake is located at ' '$CERTBOT_KEY_PATH. An additional cleanup script can also be ' 'provided and can use the additional variable $CERTBOT_AUTH_OUTPUT ' 'which contains the stdout output from the auth script.') _DNS_INSTRUCTIONS = """\ Please deploy a DNS TXT record under the name {domain} with the following value: {validation} Before continuing, verify the record is deployed.""" _HTTP_INSTRUCTIONS = """\ Create a file containing just this data: {validation} And make it available on your web server at this URL: {uri} """ _TLSSNI_INSTRUCTIONS = """\ Configure the service listening on port {port} to present the certificate {cert} using the secret key {key} when it receives a TLS ClientHello with the SNI extension set to {sni_domain} """ def __init__(self, *args, **kwargs): super(Authenticator, self).__init__(*args, **kwargs) self.reverter = reverter.Reverter(self.config) self.reverter.recovery_routine() self.env = dict() \ # type: Dict[achallenges.KeyAuthorizationAnnotatedChallenge, Dict[str, str]] self.tls_sni_01 = None @classmethod def add_parser_arguments(cls, add): add('auth-hook', help='Path or command to execute for the authentication script') add('cleanup-hook', help='Path or command to execute for the cleanup script') add('public-ip-logging-ok', action='store_true', help='Automatically allows public IP logging (default: Ask)') def prepare(self): # pylint: disable=missing-docstring if self.config.noninteractive_mode and not self.conf('auth-hook'): raise errors.PluginError( 'An authentication script must be provided with --{0} when ' 'using the manual plugin non-interactively.'.format( self.option_name('auth-hook'))) self._validate_hooks() def _validate_hooks(self): if self.config.validate_hooks: for name in ('auth-hook', 'cleanup-hook'): hook = self.conf(name) if hook is not None: hook_prefix = self.option_name(name)[:-len('-hook')] hooks.validate_hook(hook, hook_prefix) def more_info(self): # pylint: disable=missing-docstring,no-self-use return ( 'This plugin allows the user to customize setup for domain ' 'validation challenges either through shell scripts provided by ' 'the user or by performing the setup manually.') def get_chall_pref(self, domain): # pylint: disable=missing-docstring,no-self-use,unused-argument return [challenges.HTTP01, challenges.DNS01, challenges.TLSSNI01] def perform(self, achalls): # pylint: disable=missing-docstring self._verify_ip_logging_ok() if self.conf('auth-hook'): perform_achall = self._perform_achall_with_script else: perform_achall = self._perform_achall_manually responses = [] for achall in achalls: if isinstance(achall.chall, challenges.TLSSNI01): # Make a new ManualTlsSni01 instance for each challenge # because the manual plugin deals with one challenge at a time. self.tls_sni_01 = ManualTlsSni01(self) self.tls_sni_01.add_chall(achall) self.tls_sni_01.perform() perform_achall(achall) responses.append(achall.response(achall.account_key)) return responses def _verify_ip_logging_ok(self): if not self.conf('public-ip-logging-ok'): cli_flag = '--{0}'.format(self.option_name('public-ip-logging-ok')) msg = ('NOTE: The IP of this machine will be publicly logged as ' "having requested this certificate. If you're running " 'certbot in manual mode on a machine that is not your ' "server, please ensure you're okay with that.\n\n" 'Are you OK with your IP being logged?') display = zope.component.getUtility(interfaces.IDisplay) if display.yesno(msg, cli_flag=cli_flag, force_interactive=True): setattr(self.config, self.dest('public-ip-logging-ok'), True) else: raise errors.PluginError('Must agree to IP logging to proceed') def _perform_achall_with_script(self, achall): env = dict(CERTBOT_DOMAIN=achall.domain, CERTBOT_VALIDATION=achall.validation(achall.account_key)) if isinstance(achall.chall, challenges.HTTP01): env['CERTBOT_TOKEN'] = achall.chall.encode('token') else: os.environ.pop('CERTBOT_TOKEN', None) if isinstance(achall.chall, challenges.TLSSNI01): env['CERTBOT_CERT_PATH'] = self.tls_sni_01.get_cert_path(achall) env['CERTBOT_KEY_PATH'] = self.tls_sni_01.get_key_path(achall) env['CERTBOT_SNI_DOMAIN'] = self.tls_sni_01.get_z_domain(achall) os.environ.pop('CERTBOT_VALIDATION', None) env.pop('CERTBOT_VALIDATION') else: os.environ.pop('CERTBOT_CERT_PATH', None) os.environ.pop('CERTBOT_KEY_PATH', None) os.environ.pop('CERTBOT_SNI_DOMAIN', None) os.environ.update(env) _, out = hooks.execute(self.conf('auth-hook')) env['CERTBOT_AUTH_OUTPUT'] = out.strip() self.env[achall] = env def _perform_achall_manually(self, achall): validation = achall.validation(achall.account_key) if isinstance(achall.chall, challenges.HTTP01): msg = self._HTTP_INSTRUCTIONS.format( achall=achall, encoded_token=achall.chall.encode('token'), port=self.config.http01_port, uri=achall.chall.uri(achall.domain), validation=validation) elif isinstance(achall.chall, challenges.DNS01): msg = self._DNS_INSTRUCTIONS.format( domain=achall.validation_domain_name(achall.domain), validation=validation) else: assert isinstance(achall.chall, challenges.TLSSNI01) msg = self._TLSSNI_INSTRUCTIONS.format( cert=self.tls_sni_01.get_cert_path(achall), key=self.tls_sni_01.get_key_path(achall), port=self.config.tls_sni_01_port, sni_domain=self.tls_sni_01.get_z_domain(achall)) display = zope.component.getUtility(interfaces.IDisplay) display.notification(msg, wrap=False, force_interactive=True) def cleanup(self, achalls): # pylint: disable=missing-docstring if self.conf('cleanup-hook'): for achall in achalls: env = self.env.pop(achall) if 'CERTBOT_TOKEN' not in env: os.environ.pop('CERTBOT_TOKEN', None) os.environ.update(env) hooks.execute(self.conf('cleanup-hook')) self.reverter.recovery_routine() certbot-0.27.0/certbot/plugins/dns_test_common.py0000644000175000017500000000316113344054434022327 0ustar ericaerica00000000000000"""Base test class for DNS authenticators.""" import os import configobj import josepy as jose import mock import six from acme import challenges from certbot import achallenges from certbot.tests import acme_util from certbot.tests import util as test_util DOMAIN = 'example.com' KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem")) class BaseAuthenticatorTest(object): """ A base test class to reduce duplication between test code for DNS Authenticator Plugins. Assumes: * That subclasses also subclass unittest.TestCase * That the authenticator is stored as self.auth """ achall = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.DNS01, domain=DOMAIN, account_key=KEY) def test_more_info(self): # pylint: disable=no-member self.assertTrue(isinstance(self.auth.more_info(), six.string_types)) def test_get_chall_pref(self): # pylint: disable=no-member self.assertEqual(self.auth.get_chall_pref(None), [challenges.DNS01]) def test_parser_arguments(self): m = mock.MagicMock() # pylint: disable=no-member self.auth.add_parser_arguments(m) m.assert_any_call('propagation-seconds', type=int, default=mock.ANY, help=mock.ANY) def write(values, path): """Write the specified values to a config file. :param dict values: A map of values to write. :param str path: Where to write the values. """ config = configobj.ConfigObj() for key in values: config[key] = values[key] with open(path, "wb") as f: config.write(outfile=f) os.chmod(path, 0o600) certbot-0.27.0/certbot/plugins/selection.py0000644000175000017500000003306013344054434021122 0ustar ericaerica00000000000000"""Decide which plugins to use for authentication & installation""" from __future__ import print_function import os import logging import six import zope.component from certbot import errors from certbot import interfaces from certbot.display import util as display_util logger = logging.getLogger(__name__) z_util = zope.component.getUtility def pick_configurator( config, default, plugins, question="How would you like to authenticate and install " "certificates?"): """Pick configurator plugin.""" return pick_plugin( config, default, plugins, question, (interfaces.IAuthenticator, interfaces.IInstaller)) def pick_installer(config, default, plugins, question="How would you like to install certificates?"): """Pick installer plugin.""" return pick_plugin( config, default, plugins, question, (interfaces.IInstaller,)) def pick_authenticator( config, default, plugins, question="How would you " "like to authenticate with the ACME CA?"): """Pick authentication plugin.""" return pick_plugin( config, default, plugins, question, (interfaces.IAuthenticator,)) def get_unprepared_installer(config, plugins): """ Get an unprepared interfaces.IInstaller object. :param certbot.interfaces.IConfig config: Configuration :param certbot.plugins.disco.PluginsRegistry plugins: All plugins registered as entry points. :returns: Unprepared installer plugin or None :rtype: IPlugin or None """ _, req_inst = cli_plugin_requests(config) if not req_inst: return None installers = plugins.filter(lambda p_ep: p_ep.name == req_inst) installers.init(config) installers = installers.verify((interfaces.IInstaller,)) if len(installers) > 1: raise errors.PluginSelectionError( "Found multiple installers with the name %s, Certbot is unable to " "determine which one to use. Skipping." % req_inst) if installers: inst = list(installers.values())[0] logger.debug("Selecting plugin: %s", inst) return inst.init(config) else: raise errors.PluginSelectionError( "Could not select or initialize the requested installer %s." % req_inst) def pick_plugin(config, default, plugins, question, ifaces): """Pick plugin. :param certbot.interfaces.IConfig: Configuration :param str default: Plugin name supplied by user or ``None``. :param certbot.plugins.disco.PluginsRegistry plugins: All plugins registered as entry points. :param str question: Question to be presented to the user in case multiple candidates are found. :param list ifaces: Interfaces that plugins must provide. :returns: Initialized plugin. :rtype: IPlugin """ if default is not None: # throw more UX-friendly error if default not in plugins filtered = plugins.filter(lambda p_ep: p_ep.name == default) else: if config.noninteractive_mode: # it's really bad to auto-select the single available plugin in # non-interactive mode, because an update could later add a second # available plugin raise errors.MissingCommandlineFlag( "Missing command line flags. For non-interactive execution, " "you will need to specify a plugin on the command line. Run " "with '--help plugins' to see a list of options, and see " "https://eff.org/letsencrypt-plugins for more detail on what " "the plugins do and how to use them.") filtered = plugins.visible().ifaces(ifaces) filtered.init(config) verified = filtered.verify(ifaces) verified.prepare() prepared = verified.available() if len(prepared) > 1: logger.debug("Multiple candidate plugins: %s", prepared) plugin_ep = choose_plugin(list(six.itervalues(prepared)), question) if plugin_ep is None: return None else: return plugin_ep.init() elif len(prepared) == 1: plugin_ep = list(prepared.values())[0] logger.debug("Single candidate plugin: %s", plugin_ep) if plugin_ep.misconfigured: return None return plugin_ep.init() else: logger.debug("No candidate plugin") return None def choose_plugin(prepared, question): """Allow the user to choose their plugin. :param list prepared: List of `~.PluginEntryPoint`. :param str question: Question to be presented to the user. :returns: Plugin entry point chosen by the user. :rtype: `~.PluginEntryPoint` """ opts = [plugin_ep.description_with_name + (" [Misconfigured]" if plugin_ep.misconfigured else "") for plugin_ep in prepared] names = set(plugin_ep.name for plugin_ep in prepared) while True: disp = z_util(interfaces.IDisplay) if "CERTBOT_AUTO" in os.environ and names == set(("apache", "nginx")): # The possibility of being offered exactly apache and nginx here # is new interactivity brought by https://github.com/certbot/certbot/issues/4079, # so set apache as a default for those kinds of non-interactive use # (the user will get a warning to set --non-interactive or --force-interactive) apache_idx = [n for n, p in enumerate(prepared) if p.name == "apache"][0] code, index = disp.menu(question, opts, default=apache_idx) else: code, index = disp.menu(question, opts, force_interactive=True) if code == display_util.OK: plugin_ep = prepared[index] if plugin_ep.misconfigured: z_util(interfaces.IDisplay).notification( "The selected plugin encountered an error while parsing " "your server configuration and cannot be used. The error " "was:\n\n{0}".format(plugin_ep.prepare()), pause=False) else: return plugin_ep else: return None noninstaller_plugins = ["webroot", "manual", "standalone", "dns-cloudflare", "dns-cloudxns", "dns-digitalocean", "dns-dnsimple", "dns-dnsmadeeasy", "dns-gehirn", "dns-google", "dns-linode", "dns-luadns", "dns-nsone", "dns-ovh", "dns-rfc2136", "dns-route53", "dns-sakuracloud"] def record_chosen_plugins(config, plugins, auth, inst): "Update the config entries to reflect the plugins we actually selected." config.authenticator = plugins.find_init(auth).name if auth else None config.installer = plugins.find_init(inst).name if inst else None logger.info("Plugins selected: Authenticator %s, Installer %s", config.authenticator, config.installer) def choose_configurator_plugins(config, plugins, verb): # pylint: disable=too-many-branches """ Figure out which configurator we're going to use, modifies config.authenticator and config.installer strings to reflect that choice if necessary. :raises errors.PluginSelectionError if there was a problem :returns: (an `IAuthenticator` or None, an `IInstaller` or None) :rtype: tuple """ req_auth, req_inst = cli_plugin_requests(config) installer_question = None if verb == "enhance": installer_question = ("Which installer would you like to use to " "configure the selected enhancements?") # Which plugins do we need? if verb == "run": need_inst = need_auth = True from certbot.cli import cli_command if req_auth in noninstaller_plugins and not req_inst: msg = ('With the {0} plugin, you probably want to use the "certonly" command, eg:{1}' '{1} {2} certonly --{0}{1}{1}' '(Alternatively, add a --installer flag. See https://eff.org/letsencrypt-plugins' '{1} and "--help plugins" for more information.)'.format( req_auth, os.linesep, cli_command)) raise errors.MissingCommandlineFlag(msg) else: need_inst = need_auth = False if verb == "certonly": need_auth = True if verb == "install" or verb == "enhance": need_inst = True if config.authenticator: logger.warning("Specifying an authenticator doesn't make sense when " "running Certbot with verb \"%s\"", verb) # Try to meet the user's request and/or ask them to pick plugins authenticator = installer = None if verb == "run" and req_auth == req_inst: # Unless the user has explicitly asked for different auth/install, # only consider offering a single choice authenticator = installer = pick_configurator(config, req_inst, plugins) else: if need_inst or req_inst: installer = pick_installer(config, req_inst, plugins, installer_question) if need_auth: authenticator = pick_authenticator(config, req_auth, plugins) logger.debug("Selected authenticator %s and installer %s", authenticator, installer) # Report on any failures if need_inst and not installer: diagnose_configurator_problem("installer", req_inst, plugins) if need_auth and not authenticator: diagnose_configurator_problem("authenticator", req_auth, plugins) record_chosen_plugins(config, plugins, authenticator, installer) return installer, authenticator def set_configurator(previously, now): """ Setting configurators multiple ways is okay, as long as they all agree :param str previously: previously identified request for the installer/authenticator :param str requested: the request currently being processed """ if not now: # we're not actually setting anything return previously if previously: if previously != now: msg = "Too many flags setting configurators/installers/authenticators {0} -> {1}" raise errors.PluginSelectionError(msg.format(repr(previously), repr(now))) return now def cli_plugin_requests(config): # pylint: disable=too-many-branches """ Figure out which plugins the user requested with CLI and config options :returns: (requested authenticator string or None, requested installer string or None) :rtype: tuple """ req_inst = req_auth = config.configurator req_inst = set_configurator(req_inst, config.installer) req_auth = set_configurator(req_auth, config.authenticator) if config.nginx: req_inst = set_configurator(req_inst, "nginx") req_auth = set_configurator(req_auth, "nginx") if config.apache: req_inst = set_configurator(req_inst, "apache") req_auth = set_configurator(req_auth, "apache") if config.standalone: req_auth = set_configurator(req_auth, "standalone") if config.webroot: req_auth = set_configurator(req_auth, "webroot") if config.manual: req_auth = set_configurator(req_auth, "manual") if config.dns_cloudflare: req_auth = set_configurator(req_auth, "dns-cloudflare") if config.dns_cloudxns: req_auth = set_configurator(req_auth, "dns-cloudxns") if config.dns_digitalocean: req_auth = set_configurator(req_auth, "dns-digitalocean") if config.dns_dnsimple: req_auth = set_configurator(req_auth, "dns-dnsimple") if config.dns_dnsmadeeasy: req_auth = set_configurator(req_auth, "dns-dnsmadeeasy") if config.dns_gehirn: req_auth = set_configurator(req_auth, "dns-gehirn") if config.dns_google: req_auth = set_configurator(req_auth, "dns-google") if config.dns_linode: req_auth = set_configurator(req_auth, "dns-linode") if config.dns_luadns: req_auth = set_configurator(req_auth, "dns-luadns") if config.dns_nsone: req_auth = set_configurator(req_auth, "dns-nsone") if config.dns_ovh: req_auth = set_configurator(req_auth, "dns-ovh") if config.dns_rfc2136: req_auth = set_configurator(req_auth, "dns-rfc2136") if config.dns_route53: req_auth = set_configurator(req_auth, "dns-route53") if config.dns_sakuracloud: req_auth = set_configurator(req_auth, "dns-sakuracloud") logger.debug("Requested authenticator %s and installer %s", req_auth, req_inst) return req_auth, req_inst def diagnose_configurator_problem(cfg_type, requested, plugins): """ Raise the most helpful error message about a plugin being unavailable :param str cfg_type: either "installer" or "authenticator" :param str requested: the plugin that was requested :param .PluginsRegistry plugins: available plugins :raises error.PluginSelectionError: if there was a problem """ if requested: if requested not in plugins: msg = "The requested {0} plugin does not appear to be installed".format(requested) else: msg = ("The {0} plugin is not working; there may be problems with " "your existing configuration.\nThe error was: {1!r}" .format(requested, plugins[requested].problem)) elif cfg_type == "installer": from certbot.cli import cli_command msg = ('Certbot doesn\'t know how to automatically configure the web ' 'server on this system. However, it can still get a certificate for ' 'you. Please run "{0} certonly" to do so. You\'ll need to ' 'manually configure your web server to use the resulting ' 'certificate.').format(cli_command) else: msg = "{0} could not be determined or is not installed".format(cfg_type) raise errors.PluginSelectionError(msg) certbot-0.27.0/certbot/plugins/selection_test.py0000644000175000017500000001742013344054434022163 0ustar ericaerica00000000000000"""Tests for letsencrypt.plugins.selection""" import os import sys import unittest import mock import zope.component from certbot import errors from certbot import interfaces from acme.magic_typing import List # pylint: disable=unused-import, no-name-in-module from certbot.display import util as display_util from certbot.plugins.disco import PluginsRegistry from certbot.tests import util as test_util class ConveniencePickPluginTest(unittest.TestCase): """Tests for certbot.plugins.selection.pick_*.""" def _test(self, fun, ifaces): config = mock.Mock() default = mock.Mock() plugins = mock.Mock() with mock.patch("certbot.plugins.selection.pick_plugin") as mock_p: mock_p.return_value = "foo" self.assertEqual("foo", fun(config, default, plugins, "Question?")) mock_p.assert_called_once_with( config, default, plugins, "Question?", ifaces) def test_authenticator(self): from certbot.plugins.selection import pick_authenticator self._test(pick_authenticator, (interfaces.IAuthenticator,)) def test_installer(self): from certbot.plugins.selection import pick_installer self._test(pick_installer, (interfaces.IInstaller,)) def test_configurator(self): from certbot.plugins.selection import pick_configurator self._test(pick_configurator, (interfaces.IAuthenticator, interfaces.IInstaller)) class PickPluginTest(unittest.TestCase): """Tests for certbot.plugins.selection.pick_plugin.""" def setUp(self): self.config = mock.Mock(noninteractive_mode=False) self.default = None self.reg = mock.MagicMock() self.question = "Question?" self.ifaces = [] # type: List[interfaces.IPlugin] def _call(self): from certbot.plugins.selection import pick_plugin return pick_plugin(self.config, self.default, self.reg, self.question, self.ifaces) def test_default_provided(self): self.default = "foo" self._call() self.assertEqual(1, self.reg.filter.call_count) def test_no_default(self): self._call() self.assertEqual(1, self.reg.visible().ifaces.call_count) def test_no_candidate(self): self.assertTrue(self._call() is None) def test_single(self): plugin_ep = mock.MagicMock() plugin_ep.init.return_value = "foo" plugin_ep.misconfigured = False self.reg.visible().ifaces().verify().available.return_value = { "bar": plugin_ep} self.assertEqual("foo", self._call()) def test_single_misconfigured(self): plugin_ep = mock.MagicMock() plugin_ep.init.return_value = "foo" plugin_ep.misconfigured = True self.reg.visible().ifaces().verify().available.return_value = { "bar": plugin_ep} self.assertTrue(self._call() is None) def test_multiple(self): plugin_ep = mock.MagicMock() plugin_ep.init.return_value = "foo" self.reg.visible().ifaces().verify().available.return_value = { "bar": plugin_ep, "baz": plugin_ep, } with mock.patch("certbot.plugins.selection.choose_plugin") as mock_choose: mock_choose.return_value = plugin_ep self.assertEqual("foo", self._call()) mock_choose.assert_called_once_with( [plugin_ep, plugin_ep], self.question) def test_choose_plugin_none(self): self.reg.visible().ifaces().verify().available.return_value = { "bar": None, "baz": None, } with mock.patch("certbot.plugins.selection.choose_plugin") as mock_choose: mock_choose.return_value = None self.assertTrue(self._call() is None) class ChoosePluginTest(unittest.TestCase): """Tests for certbot.plugins.selection.choose_plugin.""" def setUp(self): zope.component.provideUtility(display_util.FileDisplay(sys.stdout, False)) self.mock_apache = mock.Mock( description_with_name="a", misconfigured=True) self.mock_apache.name = "apache" self.mock_stand = mock.Mock( description_with_name="s", misconfigured=False) self.mock_stand.init().more_info.return_value = "standalone" self.plugins = [ self.mock_apache, self.mock_stand, ] def _call(self): from certbot.plugins.selection import choose_plugin return choose_plugin(self.plugins, "Question?") @test_util.patch_get_utility("certbot.plugins.selection.z_util") def test_selection(self, mock_util): mock_util().menu.side_effect = [(display_util.OK, 0), (display_util.OK, 1)] self.assertEqual(self.mock_stand, self._call()) self.assertEqual(mock_util().notification.call_count, 1) @test_util.patch_get_utility("certbot.plugins.selection.z_util") def test_more_info(self, mock_util): mock_util().menu.side_effect = [ (display_util.OK, 1), ] self.assertEqual(self.mock_stand, self._call()) @test_util.patch_get_utility("certbot.plugins.selection.z_util") def test_no_choice(self, mock_util): mock_util().menu.return_value = (display_util.CANCEL, 0) self.assertTrue(self._call() is None) @test_util.patch_get_utility("certbot.plugins.selection.z_util") def test_new_interaction_avoidance(self, mock_util): mock_nginx = mock.Mock( description_with_name="n", misconfigured=False) mock_nginx.init().more_info.return_value = "nginx plugin" mock_nginx.name = "nginx" self.plugins[1] = mock_nginx mock_util().menu.return_value = (display_util.CANCEL, 0) unset_cb_auto = os.environ.get("CERTBOT_AUTO") is None if unset_cb_auto: os.environ["CERTBOT_AUTO"] = "foo" try: self._call() finally: if unset_cb_auto: del os.environ["CERTBOT_AUTO"] self.assertTrue("default" in mock_util().menu.call_args[1]) class GetUnpreparedInstallerTest(test_util.ConfigTestCase): """Tests for certbot.plugins.selection.get_unprepared_installer.""" def setUp(self): super(GetUnpreparedInstallerTest, self).setUp() self.mock_apache_fail_ep = mock.Mock( description_with_name="afail") self.mock_apache_fail_ep.name = "afail" self.mock_apache_ep = mock.Mock( description_with_name="apache") self.mock_apache_ep.name = "apache" self.mock_apache_plugin = mock.MagicMock() self.mock_apache_ep.init.return_value = self.mock_apache_plugin self.plugins = PluginsRegistry({ "afail": self.mock_apache_fail_ep, "apache": self.mock_apache_ep, }) def _call(self): from certbot.plugins.selection import get_unprepared_installer return get_unprepared_installer(self.config, self.plugins) def test_no_installer_defined(self): self.config.configurator = None self.assertEquals(self._call(), None) def test_no_available_installers(self): self.config.configurator = "apache" self.plugins = PluginsRegistry({}) self.assertRaises(errors.PluginSelectionError, self._call) def test_get_plugin(self): self.config.configurator = "apache" installer = self._call() self.assertTrue(installer is self.mock_apache_plugin) def test_multiple_installers_returned(self): self.config.configurator = "apache" # Two plugins with the same name self.mock_apache_fail_ep.name = "apache" self.assertRaises(errors.PluginSelectionError, self._call) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/plugins/util_test.py0000644000175000017500000000306213344054434021150 0ustar ericaerica00000000000000"""Tests for certbot.plugins.util.""" import os import unittest import mock class GetPrefixTest(unittest.TestCase): """Tests for certbot.plugins.get_prefixes.""" def test_get_prefix(self): from certbot.plugins.util import get_prefixes self.assertEqual(get_prefixes("/a/b/c/"), ['/a/b/c/', '/a/b/c', '/a/b', '/a', '/']) self.assertEqual(get_prefixes("/"), ["/"]) self.assertEqual(get_prefixes("a"), ["a"]) class PathSurgeryTest(unittest.TestCase): """Tests for certbot.plugins.path_surgery.""" @mock.patch("certbot.plugins.util.logger.debug") def test_path_surgery(self, mock_debug): from certbot.plugins.util import path_surgery all_path = {"PATH": "/usr/local/bin:/bin/:/usr/sbin/:/usr/local/sbin/"} with mock.patch.dict('os.environ', all_path): with mock.patch('certbot.util.exe_exists') as mock_exists: mock_exists.return_value = True self.assertEqual(path_surgery("eg"), True) self.assertEqual(mock_debug.call_count, 0) self.assertEqual(os.environ["PATH"], all_path["PATH"]) no_path = {"PATH": "/tmp/"} with mock.patch.dict('os.environ', no_path): path_surgery("thingy") self.assertEqual(mock_debug.call_count, 2) self.assertTrue("Failed to find" in mock_debug.call_args[0][0]) self.assertTrue("/usr/local/bin" in os.environ["PATH"]) self.assertTrue("/tmp" in os.environ["PATH"]) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/display/0002755000175000017500000000000013344054435016550 5ustar ericaerica00000000000000certbot-0.27.0/certbot/display/dummy_readline.py0000644000175000017500000000107213344054434022115 0ustar ericaerica00000000000000"""A dummy module with no effect for use on systems without readline.""" def get_completer(): """An empty implementation of readline.get_completer.""" def get_completer_delims(): """An empty implementation of readline.get_completer_delims.""" def parse_and_bind(unused_command): """An empty implementation of readline.parse_and_bind.""" def set_completer(unused_function=None): """An empty implementation of readline.set_completer.""" def set_completer_delims(unused_delims): """An empty implementation of readline.set_completer_delims.""" certbot-0.27.0/certbot/display/util.py0000644000175000017500000005310713344054434020102 0ustar ericaerica00000000000000"""Certbot display.""" import logging import os import select import sys import textwrap import zope.interface from certbot import constants from certbot import interfaces from certbot import errors from certbot.display import completer logger = logging.getLogger(__name__) WIDTH = 72 # Display exit codes OK = "ok" """Display exit code indicating user acceptance.""" CANCEL = "cancel" """Display exit code for a user canceling the display.""" HELP = "help" """Display exit code when for when the user requests more help. (UNUSED)""" ESC = "esc" """Display exit code when the user hits Escape (UNUSED)""" # Display constants SIDE_FRAME = ("- " * 39) + "-" """Display boundary (alternates spaces, so when copy-pasted, markdown doesn't interpret it as a heading)""" def _wrap_lines(msg): """Format lines nicely to 80 chars. :param str msg: Original message :returns: Formatted message respecting newlines in message :rtype: str """ lines = msg.splitlines() fixed_l = [] for line in lines: fixed_l.append(textwrap.fill( line, 80, break_long_words=False, break_on_hyphens=False)) return os.linesep.join(fixed_l) def input_with_timeout(prompt=None, timeout=36000.0): """Get user input with a timeout. Behaves the same as six.moves.input, however, an error is raised if a user doesn't answer after timeout seconds. The default timeout value was chosen to place it just under 12 hours for users following our advice and running Certbot twice a day. :param str prompt: prompt to provide for input :param float timeout: maximum number of seconds to wait for input :returns: user response :rtype: str :raises errors.Error if no answer is given before the timeout """ # use of sys.stdin and sys.stdout to mimic six.moves.input based on # https://github.com/python/cpython/blob/baf7bb30a02aabde260143136bdf5b3738a1d409/Lib/getpass.py#L129 if prompt: sys.stdout.write(prompt) sys.stdout.flush() # select can only be used like this on UNIX rlist, _, _ = select.select([sys.stdin], [], [], timeout) if not rlist: raise errors.Error( "Timed out waiting for answer to prompt '{0}'".format(prompt)) line = rlist[0].readline() if not line: raise EOFError return line.rstrip('\n') @zope.interface.implementer(interfaces.IDisplay) class FileDisplay(object): """File-based display.""" # pylint: disable=too-many-arguments # see https://github.com/certbot/certbot/issues/3915 def __init__(self, outfile, force_interactive): super(FileDisplay, self).__init__() self.outfile = outfile self.force_interactive = force_interactive self.skipped_interaction = False def notification(self, message, pause=True, wrap=True, force_interactive=False): """Displays a notification and waits for user acceptance. :param str message: Message to display :param bool pause: Whether or not the program should pause for the user's confirmation :param bool wrap: Whether or not the application should wrap text :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions """ if wrap: message = _wrap_lines(message) self.outfile.write( "{line}{frame}{line}{msg}{line}{frame}{line}".format( line=os.linesep, frame=SIDE_FRAME, msg=message)) self.outfile.flush() if pause: if self._can_interact(force_interactive): input_with_timeout("Press Enter to Continue") else: logger.debug("Not pausing for user confirmation") def menu(self, message, choices, ok_label=None, cancel_label=None, help_label=None, default=None, cli_flag=None, force_interactive=False, **unused_kwargs): # pylint: disable=unused-argument """Display a menu. .. todo:: This doesn't enable the help label/button (I wasn't sold on any interface I came up with for this). It would be a nice feature :param str message: title of menu :param choices: Menu lines, len must be > 0 :type choices: list of tuples (tag, item) or list of descriptions (tags will be enumerated) :param default: default value to return (if one exists) :param str cli_flag: option used to set this value with the CLI :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions :returns: tuple of (`code`, `index`) where `code` - str display exit code `index` - int index of the user's selection :rtype: tuple """ if self._return_default(message, default, cli_flag, force_interactive): return OK, default self._print_menu(message, choices) code, selection = self._get_valid_int_ans(len(choices)) return code, selection - 1 def input(self, message, default=None, cli_flag=None, force_interactive=False, **unused_kwargs): """Accept input from the user. :param str message: message to display to the user :param default: default value to return (if one exists) :param str cli_flag: option used to set this value with the CLI :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions :returns: tuple of (`code`, `input`) where `code` - str display exit code `input` - str of the user's input :rtype: tuple """ if self._return_default(message, default, cli_flag, force_interactive): return OK, default # Trailing space must be added outside of _wrap_lines to be preserved message = _wrap_lines("%s (Enter 'c' to cancel):" % message) + " " ans = input_with_timeout(message) if ans == "c" or ans == "C": return CANCEL, "-1" else: return OK, ans def yesno(self, message, yes_label="Yes", no_label="No", default=None, cli_flag=None, force_interactive=False, **unused_kwargs): """Query the user with a yes/no question. Yes and No label must begin with different letters, and must contain at least one letter each. :param str message: question for the user :param str yes_label: Label of the "Yes" parameter :param str no_label: Label of the "No" parameter :param default: default value to return (if one exists) :param str cli_flag: option used to set this value with the CLI :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions :returns: True for "Yes", False for "No" :rtype: bool """ if self._return_default(message, default, cli_flag, force_interactive): return default message = _wrap_lines(message) self.outfile.write("{0}{frame}{msg}{0}{frame}".format( os.linesep, frame=SIDE_FRAME + os.linesep, msg=message)) self.outfile.flush() while True: ans = input_with_timeout("{yes}/{no}: ".format( yes=_parens_around_char(yes_label), no=_parens_around_char(no_label))) # Couldn't get pylint indentation right with elif # elif doesn't matter in this situation if (ans.startswith(yes_label[0].lower()) or ans.startswith(yes_label[0].upper())): return True if (ans.startswith(no_label[0].lower()) or ans.startswith(no_label[0].upper())): return False def checklist(self, message, tags, default=None, cli_flag=None, force_interactive=False, **unused_kwargs): # pylint: disable=unused-argument """Display a checklist. :param str message: Message to display to user :param list tags: `str` tags to select, len(tags) > 0 :param default: default value to return (if one exists) :param str cli_flag: option used to set this value with the CLI :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions :returns: tuple of (`code`, `tags`) where `code` - str display exit code `tags` - list of selected tags :rtype: tuple """ if self._return_default(message, default, cli_flag, force_interactive): return OK, default while True: self._print_menu(message, tags) code, ans = self.input("Select the appropriate numbers separated " "by commas and/or spaces, or leave input " "blank to select all options shown", force_interactive=True) if code == OK: if len(ans.strip()) == 0: ans = " ".join(str(x) for x in range(1, len(tags)+1)) indices = separate_list_input(ans) selected_tags = self._scrub_checklist_input(indices, tags) if selected_tags: return code, selected_tags else: self.outfile.write( "** Error - Invalid selection **%s" % os.linesep) self.outfile.flush() else: return code, [] def _return_default(self, prompt, default, cli_flag, force_interactive): """Should we return the default instead of prompting the user? :param str prompt: prompt for the user :param default: default answer to prompt :param str cli_flag: command line option for setting an answer to this question :param bool force_interactive: if interactivity is forced by the IDisplay call :returns: True if we should return the default without prompting :rtype: bool """ # assert_valid_call(prompt, default, cli_flag, force_interactive) if self._can_interact(force_interactive): return False elif default is None: msg = "Unable to get an answer for the question:\n{0}".format(prompt) if cli_flag: msg += ( "\nYou can provide an answer on the " "command line with the {0} flag.".format(cli_flag)) raise errors.Error(msg) else: logger.debug( "Falling back to default %s for the prompt:\n%s", default, prompt) return True def _can_interact(self, force_interactive): """Can we safely interact with the user? :param bool force_interactive: if interactivity is forced by the IDisplay call :returns: True if the display can interact with the user :rtype: bool """ if (self.force_interactive or force_interactive or sys.stdin.isatty() and self.outfile.isatty()): return True elif not self.skipped_interaction: logger.warning( "Skipped user interaction because Certbot doesn't appear to " "be running in a terminal. You should probably include " "--non-interactive or %s on the command line.", constants.FORCE_INTERACTIVE_FLAG) self.skipped_interaction = True return False def directory_select(self, message, default=None, cli_flag=None, force_interactive=False, **unused_kwargs): """Display a directory selection screen. :param str message: prompt to give the user :param default: default value to return (if one exists) :param str cli_flag: option used to set this value with the CLI :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions :returns: tuple of the form (`code`, `string`) where `code` - display exit code `string` - input entered by the user """ with completer.Completer(): return self.input(message, default, cli_flag, force_interactive) def _scrub_checklist_input(self, indices, tags): # pylint: disable=no-self-use """Validate input and transform indices to appropriate tags. :param list indices: input :param list tags: Original tags of the checklist :returns: valid tags the user selected :rtype: :class:`list` of :class:`str` """ # They should all be of type int try: indices = [int(index) for index in indices] except ValueError: return [] # Remove duplicates indices = list(set(indices)) # Check all input is within range for index in indices: if index < 1 or index > len(tags): return [] # Transform indices to appropriate tags return [tags[index - 1] for index in indices] def _print_menu(self, message, choices): """Print a menu on the screen. :param str message: title of menu :param choices: Menu lines :type choices: list of tuples (tag, item) or list of descriptions (tags will be enumerated) """ # Can take either tuples or single items in choices list if choices and isinstance(choices[0], tuple): choices = ["%s - %s" % (c[0], c[1]) for c in choices] # Write out the message to the user self.outfile.write( "{new}{msg}{new}".format(new=os.linesep, msg=message)) self.outfile.write(SIDE_FRAME + os.linesep) # Write out the menu choices for i, desc in enumerate(choices, 1): msg = "{num}: {desc}".format(num=i, desc=desc) self.outfile.write(_wrap_lines(msg)) # Keep this outside of the textwrap self.outfile.write(os.linesep) self.outfile.write(SIDE_FRAME + os.linesep) self.outfile.flush() def _get_valid_int_ans(self, max_): """Get a numerical selection. :param int max: The maximum entry (len of choices), must be positive :returns: tuple of the form (`code`, `selection`) where `code` - str display exit code ('ok' or cancel') `selection` - int user's selection :rtype: tuple """ selection = -1 if max_ > 1: input_msg = ("Select the appropriate number " "[1-{max_}] then [enter] (press 'c' to " "cancel): ".format(max_=max_)) else: input_msg = ("Press 1 [enter] to confirm the selection " "(press 'c' to cancel): ") while selection < 1: ans = input_with_timeout(input_msg) if ans.startswith("c") or ans.startswith("C"): return CANCEL, -1 try: selection = int(ans) if selection < 1 or selection > max_: selection = -1 raise ValueError except ValueError: self.outfile.write( "{0}** Invalid input **{0}".format(os.linesep)) self.outfile.flush() return OK, selection def assert_valid_call(prompt, default, cli_flag, force_interactive): """Verify that provided arguments is a valid IDisplay call. :param str prompt: prompt for the user :param default: default answer to prompt :param str cli_flag: command line option for setting an answer to this question :param bool force_interactive: if interactivity is forced by the IDisplay call """ msg = "Invalid IDisplay call for this prompt:\n{0}".format(prompt) if cli_flag: msg += ("\nYou can set an answer to " "this prompt with the {0} flag".format(cli_flag)) assert default is not None or force_interactive, msg @zope.interface.implementer(interfaces.IDisplay) class NoninteractiveDisplay(object): """An iDisplay implementation that never asks for interactive user input""" def __init__(self, outfile, *unused_args, **unused_kwargs): super(NoninteractiveDisplay, self).__init__() self.outfile = outfile def _interaction_fail(self, message, cli_flag, extra=""): "Error out in case of an attempt to interact in noninteractive mode" msg = "Missing command line flag or config entry for this setting:\n" msg += message if extra: msg += "\n" + extra if cli_flag: msg += "\n\n(You can set this with the {0} flag)".format(cli_flag) raise errors.MissingCommandlineFlag(msg) def notification(self, message, pause=False, wrap=True, **unused_kwargs): # pylint: disable=unused-argument """Displays a notification without waiting for user acceptance. :param str message: Message to display to stdout :param bool pause: The NoninteractiveDisplay waits for no keyboard :param bool wrap: Whether or not the application should wrap text """ if wrap: message = _wrap_lines(message) self.outfile.write( "{line}{frame}{line}{msg}{line}{frame}{line}".format( line=os.linesep, frame=SIDE_FRAME, msg=message)) self.outfile.flush() def menu(self, message, choices, ok_label=None, cancel_label=None, help_label=None, default=None, cli_flag=None, **unused_kwargs): # pylint: disable=unused-argument,too-many-arguments """Avoid displaying a menu. :param str message: title of menu :param choices: Menu lines, len must be > 0 :type choices: list of tuples (tag, item) or list of descriptions (tags will be enumerated) :param int default: the default choice :param dict kwargs: absorbs various irrelevant labelling arguments :returns: tuple of (`code`, `index`) where `code` - str display exit code `index` - int index of the user's selection :rtype: tuple :raises errors.MissingCommandlineFlag: if there was no default """ if default is None: self._interaction_fail(message, cli_flag, "Choices: " + repr(choices)) return OK, default def input(self, message, default=None, cli_flag=None, **unused_kwargs): """Accept input from the user. :param str message: message to display to the user :returns: tuple of (`code`, `input`) where `code` - str display exit code `input` - str of the user's input :rtype: tuple :raises errors.MissingCommandlineFlag: if there was no default """ if default is None: self._interaction_fail(message, cli_flag) else: return OK, default def yesno(self, message, yes_label=None, no_label=None, default=None, cli_flag=None, **unused_kwargs): # pylint: disable=unused-argument """Decide Yes or No, without asking anybody :param str message: question for the user :param dict kwargs: absorbs yes_label, no_label :raises errors.MissingCommandlineFlag: if there was no default :returns: True for "Yes", False for "No" :rtype: bool """ if default is None: self._interaction_fail(message, cli_flag) else: return default def checklist(self, message, tags, default=None, cli_flag=None, **unused_kwargs): """Display a checklist. :param str message: Message to display to user :param list tags: `str` tags to select, len(tags) > 0 :param dict kwargs: absorbs default_status arg :returns: tuple of (`code`, `tags`) where `code` - str display exit code `tags` - list of selected tags :rtype: tuple """ if default is None: self._interaction_fail(message, cli_flag, "? ".join(tags)) else: return OK, default def directory_select(self, message, default=None, cli_flag=None, **unused_kwargs): """Simulate prompting the user for a directory. This function returns default if it is not ``None``, otherwise, an exception is raised explaining the problem. If cli_flag is not ``None``, the error message will include the flag that can be used to set this value with the CLI. :param str message: prompt to give the user :param default: default value to return (if one exists) :param str cli_flag: option used to set this value with the CLI :returns: tuple of the form (`code`, `string`) where `code` - int display exit code `string` - input entered by the user """ return self.input(message, default, cli_flag) def separate_list_input(input_): """Separate a comma or space separated list. :param str input_: input from the user :returns: strings :rtype: list """ no_commas = input_.replace(",", " ") # Each string is naturally unicode, this causes problems with M2Crypto SANs # TODO: check if above is still true when M2Crypto is gone ^ return [str(string) for string in no_commas.split()] def _parens_around_char(label): """Place parens around first character of label. :param str label: Must contain at least one character """ return "({first}){rest}".format(first=label[0], rest=label[1:]) certbot-0.27.0/certbot/display/ops.py0000644000175000017500000003027313344054434017725 0ustar ericaerica00000000000000"""Contains UI methods for LE user operations.""" import logging import os import zope.component from certbot import errors from certbot import interfaces from certbot import util from certbot.display import util as display_util logger = logging.getLogger(__name__) # Define a helper function to avoid verbose code z_util = zope.component.getUtility def get_email(invalid=False, optional=True): """Prompt for valid email address. :param bool invalid: True if an invalid address was provided by the user :param bool optional: True if the user can use --register-unsafely-without-email to avoid providing an e-mail :returns: e-mail address :rtype: str :raises errors.Error: if the user cancels """ invalid_prefix = "There seem to be problems with that address. " msg = "Enter email address (used for urgent renewal and security notices)" unsafe_suggestion = ("\n\nIf you really want to skip this, you can run " "the client with --register-unsafely-without-email " "but make sure you then backup your account key from " "/etc/letsencrypt/accounts\n\n") if optional: if invalid: msg += unsafe_suggestion suggest_unsafe = False else: suggest_unsafe = True else: suggest_unsafe = False while True: try: code, email = z_util(interfaces.IDisplay).input( invalid_prefix + msg if invalid else msg, force_interactive=True) except errors.MissingCommandlineFlag: msg = ("You should register before running non-interactively, " "or provide --agree-tos and --email flags.") raise errors.MissingCommandlineFlag(msg) if code != display_util.OK: if optional: raise errors.Error( "An e-mail address or " "--register-unsafely-without-email must be provided.") else: raise errors.Error("An e-mail address must be provided.") elif util.safe_email(email): return email elif suggest_unsafe: msg += unsafe_suggestion suggest_unsafe = False # add this message at most once invalid = bool(email) def choose_account(accounts): """Choose an account. :param list accounts: Containing at least one :class:`~certbot.account.Account` """ # Note this will get more complicated once we start recording authorizations labels = [acc.slug for acc in accounts] code, index = z_util(interfaces.IDisplay).menu( "Please choose an account", labels, force_interactive=True) if code == display_util.OK: return accounts[index] else: return None def choose_values(values, question=None): """Display screen to let user pick one or multiple values from the provided list. :param list values: Values to select from :returns: List of selected values :rtype: list """ code, items = z_util(interfaces.IDisplay).checklist( question, tags=values, force_interactive=True) if code == display_util.OK and items: return items else: return [] def choose_names(installer, question=None): """Display screen to select domains to validate. :param installer: An installer object :type installer: :class:`certbot.interfaces.IInstaller` :param `str` question: Overriding dialog question to ask the user if asked to choose from domain names. :returns: List of selected names :rtype: `list` of `str` """ if installer is None: logger.debug("No installer, picking names manually") return _choose_names_manually() domains = list(installer.get_all_names()) names = get_valid_domains(domains) if not names: return _choose_names_manually( "No names were found in your configuration files. ") code, names = _filter_names(names, question) if code == display_util.OK and names: return names else: return [] def get_valid_domains(domains): """Helper method for choose_names that implements basic checks on domain names :param list domains: Domain names to validate :return: List of valid domains :rtype: list """ valid_domains = [] for domain in domains: try: valid_domains.append(util.enforce_domain_sanity(domain)) except errors.ConfigurationError: continue return valid_domains def _sort_names(FQDNs): """Sort FQDNs by SLD (and if many, by their subdomains) :param list FQDNs: list of domain names :returns: Sorted list of domain names :rtype: list """ return sorted(FQDNs, key=lambda fqdn: fqdn.split('.')[::-1][1:]) def _filter_names(names, override_question=None): """Determine which names the user would like to select from a list. :param list names: domain names :returns: tuple of the form (`code`, `names`) where `code` - str display exit code `names` - list of names selected :rtype: tuple """ #Sort by domain first, and then by subdomain sorted_names = _sort_names(names) if override_question: question = override_question else: question = "Which names would you like to activate HTTPS for?" code, names = z_util(interfaces.IDisplay).checklist( question, tags=sorted_names, cli_flag="--domains", force_interactive=True) return code, [str(s) for s in names] def _choose_names_manually(prompt_prefix=""): """Manually input names for those without an installer. :param str prompt_prefix: string to prepend to prompt for domains :returns: list of provided names :rtype: `list` of `str` """ code, input_ = z_util(interfaces.IDisplay).input( prompt_prefix + "Please enter in your domain name(s) (comma and/or space separated) ", cli_flag="--domains", force_interactive=True) if code == display_util.OK: invalid_domains = dict() retry_message = "" try: domain_list = display_util.separate_list_input(input_) except UnicodeEncodeError: domain_list = [] retry_message = ( "Internationalized domain names are not presently " "supported.{0}{0}Would you like to re-enter the " "names?{0}").format(os.linesep) for i, domain in enumerate(domain_list): try: domain_list[i] = util.enforce_domain_sanity(domain) except errors.ConfigurationError as e: invalid_domains[domain] = str(e) if len(invalid_domains): retry_message = ( "One or more of the entered domain names was not valid:" "{0}{0}").format(os.linesep) for domain in invalid_domains: retry_message = retry_message + "{1}: {2}{0}".format( os.linesep, domain, invalid_domains[domain]) retry_message = retry_message + ( "{0}Would you like to re-enter the names?{0}").format( os.linesep) if retry_message: # We had error in input retry = z_util(interfaces.IDisplay).yesno(retry_message, force_interactive=True) if retry: return _choose_names_manually() else: return domain_list return [] def success_installation(domains): """Display a box confirming the installation of HTTPS. :param list domains: domain names which were enabled """ z_util(interfaces.IDisplay).notification( "Congratulations! You have successfully enabled {0}{1}{1}" "You should test your configuration at:{1}{2}".format( _gen_https_names(domains), os.linesep, os.linesep.join(_gen_ssl_lab_urls(domains))), pause=False) def success_renewal(domains): """Display a box confirming the renewal of an existing certificate. :param list domains: domain names which were renewed """ z_util(interfaces.IDisplay).notification( "Your existing certificate has been successfully renewed, and the " "new certificate has been installed.{1}{1}" "The new certificate covers the following domains: {0}{1}{1}" "You should test your configuration at:{1}{2}".format( _gen_https_names(domains), os.linesep, os.linesep.join(_gen_ssl_lab_urls(domains))), pause=False) def success_revocation(cert_path): """Display a box confirming a certificate has been revoked. :param list cert_path: path to certificate which was revoked. """ z_util(interfaces.IDisplay).notification( "Congratulations! You have successfully revoked the certificate " "that was located at {0}{1}{1}".format( cert_path, os.linesep), pause=False) def _gen_ssl_lab_urls(domains): """Returns a list of urls. :param list domains: Each domain is a 'str' """ return ["https://www.ssllabs.com/ssltest/analyze.html?d=%s" % dom for dom in domains] def _gen_https_names(domains): """Returns a string of the https domains. Domains are formatted nicely with https:// prepended to each. :param list domains: Each domain is a 'str' """ if len(domains) == 1: return "https://{0}".format(domains[0]) elif len(domains) == 2: return "https://{dom[0]} and https://{dom[1]}".format(dom=domains) elif len(domains) > 2: return "{0}{1}{2}".format( ", ".join("https://%s" % dom for dom in domains[:-1]), ", and https://", domains[-1]) return "" def _get_validated(method, validator, message, default=None, **kwargs): if default is not None: try: validator(default) except errors.Error as error: logger.debug('Encountered invalid default value "%s" when prompting for "%s"', default, message, exc_info=True) raise AssertionError('Invalid default "{0}"'.format(default)) while True: code, raw = method(message, default=default, **kwargs) if code == display_util.OK: try: validator(raw) return code, raw except errors.Error as error: logger.debug('Validator rejected "%s" when prompting for "%s"', raw, message, exc_info=True) zope.component.getUtility(interfaces.IDisplay).notification(str(error), pause=False) else: return code, raw def validated_input(validator, *args, **kwargs): """Like `~certbot.interfaces.IDisplay.input`, but with validation. :param callable validator: A method which will be called on the supplied input. If the method raises a `errors.Error`, its text will be displayed and the user will be re-prompted. :param list `*args`: Arguments to be passed to `~certbot.interfaces.IDisplay.input`. :param dict `**kwargs`: Arguments to be passed to `~certbot.interfaces.IDisplay.input`. :return: as `~certbot.interfaces.IDisplay.input` :rtype: tuple """ return _get_validated(zope.component.getUtility(interfaces.IDisplay).input, validator, *args, **kwargs) def validated_directory(validator, *args, **kwargs): """Like `~certbot.interfaces.IDisplay.directory_select`, but with validation. :param callable validator: A method which will be called on the supplied input. If the method raises a `errors.Error`, its text will be displayed and the user will be re-prompted. :param list `*args`: Arguments to be passed to `~certbot.interfaces.IDisplay.directory_select`. :param dict `**kwargs`: Arguments to be passed to `~certbot.interfaces.IDisplay.directory_select`. :return: as `~certbot.interfaces.IDisplay.directory_select` :rtype: tuple """ return _get_validated(zope.component.getUtility(interfaces.IDisplay).directory_select, validator, *args, **kwargs) certbot-0.27.0/certbot/display/__init__.py0000644000175000017500000000004113344054434020651 0ustar ericaerica00000000000000"""Certbot display utilities.""" certbot-0.27.0/certbot/display/completer.py0000644000175000017500000000410713344054434021113 0ustar ericaerica00000000000000"""Provides Tab completion when prompting users for a path.""" import glob # readline module is not available on all systems try: import readline except ImportError: import certbot.display.dummy_readline as readline # type: ignore class Completer(object): """Provides Tab completion when prompting users for a path. This class is meant to be used with readline to provide Tab completion for users entering paths. The complete method can be passed to readline.set_completer directly, however, this function works best as a context manager. For example: with Completer(): raw_input() In this example, Tab completion will be available during the call to raw_input above, however, readline will be restored to its previous state when exiting the body of the with statement. """ def __init__(self): self._iter = self._original_completer = self._original_delims = None def complete(self, text, state): """Provides path completion for use with readline. :param str text: text to offer completions for :param int state: which completion to return :returns: possible completion for text or ``None`` if all completions have been returned :rtype: str """ if state == 0: self._iter = glob.iglob(text + '*') return next(self._iter, None) def __enter__(self): self._original_completer = readline.get_completer() self._original_delims = readline.get_completer_delims() readline.set_completer(self.complete) readline.set_completer_delims(' \t\n;') # readline can be implemented using GNU readline or libedit # which have different configuration syntax if 'libedit' in readline.__doc__: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') def __exit__(self, unused_type, unused_value, unused_traceback): readline.set_completer_delims(self._original_delims) readline.set_completer(self._original_completer) certbot-0.27.0/certbot/display/enhancements.py0000644000175000017500000000343313344054434021572 0ustar ericaerica00000000000000"""Certbot Enhancement Display""" import logging import zope.component from certbot import errors from certbot import interfaces from certbot.display import util as display_util logger = logging.getLogger(__name__) # Define a helper function to avoid verbose code util = zope.component.getUtility def ask(enhancement): """Display the enhancement to the user. :param str enhancement: One of the :class:`certbot.CONFIG.ENHANCEMENTS` enhancements :returns: True if feature is desired, False otherwise :rtype: bool :raises .errors.Error: if the enhancement provided is not supported """ try: # Call the appropriate function based on the enhancement return DISPATCH[enhancement]() except KeyError: logger.error("Unsupported enhancement given to ask(): %s", enhancement) raise errors.Error("Unsupported Enhancement") def redirect_by_default(): """Determines whether the user would like to redirect to HTTPS. :returns: True if redirect is desired, False otherwise :rtype: bool """ choices = [ ("No redirect", "Make no further changes to the webserver configuration."), ("Redirect", "Make all requests redirect to secure HTTPS access. " "Choose this for new sites, or if you're confident your site works on HTTPS. " "You can undo this change by editing your web server's configuration."), ] code, selection = util(interfaces.IDisplay).menu( "Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.", choices, default=0, cli_flag="--redirect / --no-redirect", force_interactive=True) if code != display_util.OK: return False return selection == 1 DISPATCH = { "redirect": redirect_by_default } certbot-0.27.0/certbot/error_handler.py0000644000175000017500000001347513344054434020312 0ustar ericaerica00000000000000"""Registers functions to be called if an exception or signal occurs.""" import functools import logging import os import signal import traceback # pylint: disable=unused-import, no-name-in-module from acme.magic_typing import Any, Callable, Dict, List, Union # pylint: enable=unused-import, no-name-in-module from certbot import errors logger = logging.getLogger(__name__) # _SIGNALS stores the signals that will be handled by the ErrorHandler. These # signals were chosen as their default handler terminates the process and could # potentially occur from inside Python. Signals such as SIGILL were not # included as they could be a sign of something devious and we should terminate # immediately. _SIGNALS = [signal.SIGTERM] if os.name != "nt": for signal_code in [signal.SIGHUP, signal.SIGQUIT, signal.SIGXCPU, signal.SIGXFSZ]: # Adding only those signals that their default action is not Ignore. # This is platform-dependent, so we check it dynamically. if signal.getsignal(signal_code) != signal.SIG_IGN: _SIGNALS.append(signal_code) class ErrorHandler(object): """Context manager for running code that must be cleaned up on failure. The context manager allows you to register functions that will be called when an exception (excluding SystemExit) or signal is encountered. Usage:: handler = ErrorHandler(cleanup1_func, *cleanup1_args, **cleanup1_kwargs) handler.register(cleanup2_func, *cleanup2_args, **cleanup2_kwargs) with handler: do_something() Or for one cleanup function:: with ErrorHandler(func, args, kwargs): do_something() If an exception is raised out of do_something, the cleanup functions will be called in last in first out order. Then the exception is raised. Similarly, if a signal is encountered, the cleanup functions are called followed by the previously received signal handler. Each registered cleanup function is called exactly once. If a registered function raises an exception, it is logged and the next function is called. Signals received while the registered functions are executing are deferred until they finish. """ def __init__(self, func=None, *args, **kwargs): self.call_on_regular_exit = False self.body_executed = False self.funcs = [] # type: List[Callable[[], Any]] self.prev_handlers = {} # type: Dict[int, Union[int, None, Callable]] self.received_signals = [] # type: List[int] if func is not None: self.register(func, *args, **kwargs) def __enter__(self): self.body_executed = False self._set_signal_handlers() def __exit__(self, exec_type, exec_value, trace): self.body_executed = True retval = False # SystemExit is ignored to properly handle forks that don't exec if exec_type is SystemExit: return retval elif exec_type is None: if not self.call_on_regular_exit: return retval elif exec_type is errors.SignalExit: logger.debug("Encountered signals: %s", self.received_signals) retval = True else: logger.debug("Encountered exception:\n%s", "".join( traceback.format_exception(exec_type, exec_value, trace))) self._call_registered() self._reset_signal_handlers() self._call_signals() return retval def register(self, func, *args, **kwargs): # type: (Callable, *Any, **Any) -> None """Sets func to be run with the given arguments during cleanup. :param function func: function to be called in case of an error """ self.funcs.append(functools.partial(func, *args, **kwargs)) def _call_registered(self): """Calls all registered functions""" logger.debug("Calling registered functions") while self.funcs: try: self.funcs[-1]() except Exception: # pylint: disable=broad-except logger.error("Encountered exception during recovery: ", exc_info=True) self.funcs.pop() def _set_signal_handlers(self): """Sets signal handlers for signals in _SIGNALS.""" for signum in _SIGNALS: prev_handler = signal.getsignal(signum) # If prev_handler is None, the handler was set outside of Python if prev_handler is not None: self.prev_handlers[signum] = prev_handler signal.signal(signum, self._signal_handler) def _reset_signal_handlers(self): """Resets signal handlers for signals in _SIGNALS.""" for signum in self.prev_handlers: signal.signal(signum, self.prev_handlers[signum]) self.prev_handlers.clear() def _signal_handler(self, signum, unused_frame): """Replacement function for handling received signals. Store the received signal. If we are executing the code block in the body of the context manager, stop by raising signal exit. :param int signum: number of current signal """ self.received_signals.append(signum) if not self.body_executed: raise errors.SignalExit def _call_signals(self): """Finally call the deferred signals.""" for signum in self.received_signals: logger.debug("Calling signal %s", signum) os.kill(os.getpid(), signum) class ExitHandler(ErrorHandler): """Context manager for running code that must be cleaned up. Subclass of ErrorHandler, with the same usage and parameters. In addition to cleaning up on all signals, also cleans up on regular exit. """ def __init__(self, func=None, *args, **kwargs): ErrorHandler.__init__(self, func, *args, **kwargs) self.call_on_regular_exit = True certbot-0.27.0/certbot/cert_manager.py0000644000175000017500000003607713344054434020116 0ustar ericaerica00000000000000"""Tools for managing certificates.""" import datetime import logging import os import pytz import re import traceback import zope.component from acme.magic_typing import List # pylint: disable=unused-import, no-name-in-module from certbot import crypto_util from certbot import errors from certbot import interfaces from certbot import ocsp from certbot import storage from certbot import util from certbot.display import util as display_util logger = logging.getLogger(__name__) ################### # Commands ################### def update_live_symlinks(config): """Update the certificate file family symlinks to use archive_dir. Use the information in the config file to make symlinks point to the correct archive directory. .. note:: This assumes that the installation is using a Reverter object. :param config: Configuration. :type config: :class:`certbot.configuration.NamespaceConfig` """ for renewal_file in storage.renewal_conf_files(config): storage.RenewableCert(renewal_file, config, update_symlinks=True) def rename_lineage(config): """Rename the specified lineage to the new name. :param config: Configuration. :type config: :class:`certbot.configuration.NamespaceConfig` """ disp = zope.component.getUtility(interfaces.IDisplay) certname = get_certnames(config, "rename")[0] new_certname = config.new_certname if not new_certname: code, new_certname = disp.input( "Enter the new name for certificate {0}".format(certname), flag="--updated-cert-name", force_interactive=True) if code != display_util.OK or not new_certname: raise errors.Error("User ended interaction.") lineage = lineage_for_certname(config, certname) if not lineage: raise errors.ConfigurationError("No existing certificate with name " "{0} found.".format(certname)) storage.rename_renewal_config(certname, new_certname, config) disp.notification("Successfully renamed {0} to {1}." .format(certname, new_certname), pause=False) def certificates(config): """Display information about certs configured with Certbot :param config: Configuration. :type config: :class:`certbot.configuration.NamespaceConfig` """ parsed_certs = [] parse_failures = [] for renewal_file in storage.renewal_conf_files(config): try: renewal_candidate = storage.RenewableCert(renewal_file, config) crypto_util.verify_renewable_cert(renewal_candidate) parsed_certs.append(renewal_candidate) except Exception as e: # pylint: disable=broad-except logger.warning("Renewal configuration file %s produced an " "unexpected error: %s. Skipping.", renewal_file, e) logger.debug("Traceback was:\n%s", traceback.format_exc()) parse_failures.append(renewal_file) # Describe all the certs _describe_certs(config, parsed_certs, parse_failures) def delete(config): """Delete Certbot files associated with a certificate lineage.""" certnames = get_certnames(config, "delete", allow_multiple=True) for certname in certnames: storage.delete_files(config, certname) disp = zope.component.getUtility(interfaces.IDisplay) disp.notification("Deleted all files relating to certificate {0}." .format(certname), pause=False) ################### # Public Helpers ################### def lineage_for_certname(cli_config, certname): """Find a lineage object with name certname.""" configs_dir = cli_config.renewal_configs_dir # Verify the directory is there util.make_or_verify_dir(configs_dir, mode=0o755, uid=os.geteuid()) try: renewal_file = storage.renewal_file_for_certname(cli_config, certname) except errors.CertStorageError: return None try: return storage.RenewableCert(renewal_file, cli_config) except (errors.CertStorageError, IOError): logger.debug("Renewal conf file %s is broken.", renewal_file) logger.debug("Traceback was:\n%s", traceback.format_exc()) return None def domains_for_certname(config, certname): """Find the domains in the cert with name certname.""" lineage = lineage_for_certname(config, certname) return lineage.names() if lineage else None def find_duplicative_certs(config, domains): """Find existing certs that match the given domain names. This function searches for certificates whose domains are equal to the `domains` parameter and certificates whose domains are a subset of the domains in the `domains` parameter. If multiple certificates are found whose names are a subset of `domains`, the one whose names are the largest subset of `domains` is returned. If multiple certificates' domains are an exact match or equally sized subsets, which matching certificates are returned is undefined. :param config: Configuration. :type config: :class:`certbot.configuration.NamespaceConfig` :param domains: List of domain names :type domains: `list` of `str` :returns: lineages representing the identically matching cert and the largest subset if they exist :rtype: `tuple` of `storage.RenewableCert` or `None` """ def update_certs_for_domain_matches(candidate_lineage, rv): """Return cert as identical_names_cert if it matches, or subset_names_cert if it matches as subset """ # TODO: Handle these differently depending on whether they are # expired or still valid? identical_names_cert, subset_names_cert = rv candidate_names = set(candidate_lineage.names()) if candidate_names == set(domains): identical_names_cert = candidate_lineage elif candidate_names.issubset(set(domains)): # This logic finds and returns the largest subset-names cert # in the case where there are several available. if subset_names_cert is None: subset_names_cert = candidate_lineage elif len(candidate_names) > len(subset_names_cert.names()): subset_names_cert = candidate_lineage return (identical_names_cert, subset_names_cert) return _search_lineages(config, update_certs_for_domain_matches, (None, None)) def _archive_files(candidate_lineage, filetype): """ In order to match things like: /etc/letsencrypt/archive/example.com/chain1.pem. Anonymous functions which call this function are eventually passed (in a list) to `match_and_check_overlaps` to help specify the acceptable_matches. :param `.storage.RenewableCert` candidate_lineage: Lineage whose archive dir is to be searched. :param str filetype: main file name prefix e.g. "fullchain" or "chain". :returns: Files in candidate_lineage's archive dir that match the provided filetype. :rtype: list of str or None """ archive_dir = candidate_lineage.archive_dir pattern = [os.path.join(archive_dir, f) for f in os.listdir(archive_dir) if re.match("{0}[0-9]*.pem".format(filetype), f)] if len(pattern) > 0: return pattern else: return None def _acceptable_matches(): """ Generates the list that's passed to match_and_check_overlaps. Is its own function to make unit testing easier. :returns: list of functions :rtype: list """ return [lambda x: x.fullchain_path, lambda x: x.cert_path, lambda x: _archive_files(x, "cert"), lambda x: _archive_files(x, "fullchain")] def cert_path_to_lineage(cli_config): """ If config.cert_path is defined, try to find an appropriate value for config.certname. :param `configuration.NamespaceConfig` cli_config: parsed command line arguments :returns: a lineage name :rtype: str :raises `errors.Error`: If the specified cert path can't be matched to a lineage name. :raises `errors.OverlappingMatchFound`: If the matched lineage's archive is shared. """ acceptable_matches = _acceptable_matches() match = match_and_check_overlaps(cli_config, acceptable_matches, lambda x: cli_config.cert_path[0], lambda x: x.lineagename) return match[0] def match_and_check_overlaps(cli_config, acceptable_matches, match_func, rv_func): """ Searches through all lineages for a match, and checks for duplicates. If a duplicate is found, an error is raised, as performing operations on lineages that have their properties incorrectly duplicated elsewhere is probably a bad idea. :param `configuration.NamespaceConfig` cli_config: parsed command line arguments :param list acceptable_matches: a list of functions that specify acceptable matches :param function match_func: specifies what to match :param function rv_func: specifies what to return """ def find_matches(candidate_lineage, return_value, acceptable_matches): """Returns a list of matches using _search_lineages.""" acceptable_matches = [func(candidate_lineage) for func in acceptable_matches] acceptable_matches_rv = [] # type: List[str] for item in acceptable_matches: if isinstance(item, list): acceptable_matches_rv += item else: acceptable_matches_rv.append(item) match = match_func(candidate_lineage) if match in acceptable_matches_rv: return_value.append(rv_func(candidate_lineage)) return return_value matched = _search_lineages(cli_config, find_matches, [], acceptable_matches) if not matched: raise errors.Error("No match found for cert-path {0}!".format(cli_config.cert_path[0])) elif len(matched) > 1: raise errors.OverlappingMatchFound() else: return matched def human_readable_cert_info(config, cert, skip_filter_checks=False): """ Returns a human readable description of info about a RenewableCert object""" certinfo = [] checker = ocsp.RevocationChecker() if config.certname and cert.lineagename != config.certname and not skip_filter_checks: return "" if config.domains and not set(config.domains).issubset(cert.names()): return "" now = pytz.UTC.fromutc(datetime.datetime.utcnow()) reasons = [] if cert.is_test_cert: reasons.append('TEST_CERT') if cert.target_expiry <= now: reasons.append('EXPIRED') if checker.ocsp_revoked(cert.cert, cert.chain): reasons.append('REVOKED') if reasons: status = "INVALID: " + ", ".join(reasons) else: diff = cert.target_expiry - now if diff.days == 1: status = "VALID: 1 day" elif diff.days < 1: status = "VALID: {0} hour(s)".format(diff.seconds // 3600) else: status = "VALID: {0} days".format(diff.days) valid_string = "{0} ({1})".format(cert.target_expiry, status) certinfo.append(" Certificate Name: {0}\n" " Domains: {1}\n" " Expiry Date: {2}\n" " Certificate Path: {3}\n" " Private Key Path: {4}".format( cert.lineagename, " ".join(cert.names()), valid_string, cert.fullchain, cert.privkey)) return "".join(certinfo) def get_certnames(config, verb, allow_multiple=False, custom_prompt=None): """Get certname from flag, interactively, or error out. """ certname = config.certname if certname: certnames = [certname] else: disp = zope.component.getUtility(interfaces.IDisplay) filenames = storage.renewal_conf_files(config) choices = [storage.lineagename_for_filename(name) for name in filenames] if not choices: raise errors.Error("No existing certificates found.") if allow_multiple: if not custom_prompt: prompt = "Which certificate(s) would you like to {0}?".format(verb) else: prompt = custom_prompt code, certnames = disp.checklist( prompt, choices, cli_flag="--cert-name", force_interactive=True) if code != display_util.OK: raise errors.Error("User ended interaction.") else: if not custom_prompt: prompt = "Which certificate would you like to {0}?".format(verb) else: prompt = custom_prompt code, index = disp.menu( prompt, choices, cli_flag="--cert-name", force_interactive=True) if code != display_util.OK or index not in range(0, len(choices)): raise errors.Error("User ended interaction.") certnames = [choices[index]] return certnames ################### # Private Helpers ################### def _report_lines(msgs): """Format a results report for a category of single-line renewal outcomes""" return " " + "\n ".join(str(msg) for msg in msgs) def _report_human_readable(config, parsed_certs): """Format a results report for a parsed cert""" certinfo = [] for cert in parsed_certs: certinfo.append(human_readable_cert_info(config, cert)) return "\n".join(certinfo) def _describe_certs(config, parsed_certs, parse_failures): """Print information about the certs we know about""" out = [] # type: List[str] notify = out.append if not parsed_certs and not parse_failures: notify("No certs found.") else: if parsed_certs: match = "matching " if config.certname or config.domains else "" notify("Found the following {0}certs:".format(match)) notify(_report_human_readable(config, parsed_certs)) if parse_failures: notify("\nThe following renewal configurations " "were invalid:") notify(_report_lines(parse_failures)) disp = zope.component.getUtility(interfaces.IDisplay) disp.notification("\n".join(out), pause=False, wrap=False) def _search_lineages(cli_config, func, initial_rv, *args): """Iterate func over unbroken lineages, allowing custom return conditions. Allows flexible customization of return values, including multiple return values and complex checks. :param `configuration.NamespaceConfig` cli_config: parsed command line arguments :param function func: function used while searching over lineages :param initial_rv: initial return value of the function (any type) :returns: Whatever was specified by `func` if a match is found. """ configs_dir = cli_config.renewal_configs_dir # Verify the directory is there util.make_or_verify_dir(configs_dir, mode=0o755, uid=os.geteuid()) rv = initial_rv for renewal_file in storage.renewal_conf_files(cli_config): try: candidate_lineage = storage.RenewableCert(renewal_file, cli_config) except (errors.CertStorageError, IOError): logger.debug("Renewal conf file %s is broken. Skipping.", renewal_file) logger.debug("Traceback was:\n%s", traceback.format_exc()) continue rv = func(candidate_lineage, rv, *args) return rv certbot-0.27.0/certbot/tests/0002755000175000017500000000000013344054435016245 5ustar ericaerica00000000000000certbot-0.27.0/certbot/tests/ocsp_test.py0000644000175000017500000001441313344054434020622 0ustar ericaerica00000000000000"""Tests for ocsp.py""" # pylint: disable=protected-access import unittest import mock from certbot import errors out = """Missing = in header key=value ocsp: Use -help for summary. """ class OCSPTest(unittest.TestCase): def setUp(self): from certbot import ocsp with mock.patch('certbot.ocsp.Popen') as mock_popen: with mock.patch('certbot.util.exe_exists') as mock_exists: mock_communicate = mock.MagicMock() mock_communicate.communicate.return_value = (None, out) mock_popen.return_value = mock_communicate mock_exists.return_value = True self.checker = ocsp.RevocationChecker() def tearDown(self): pass @mock.patch('certbot.ocsp.logger.info') @mock.patch('certbot.ocsp.Popen') @mock.patch('certbot.util.exe_exists') def test_init(self, mock_exists, mock_popen, mock_log): mock_communicate = mock.MagicMock() mock_communicate.communicate.return_value = (None, out) mock_popen.return_value = mock_communicate mock_exists.return_value = True from certbot import ocsp checker = ocsp.RevocationChecker() self.assertEqual(mock_popen.call_count, 1) self.assertEqual(checker.host_args("x"), ["Host=x"]) mock_communicate.communicate.return_value = (None, out.partition("\n")[2]) checker = ocsp.RevocationChecker() self.assertEqual(checker.host_args("x"), ["Host", "x"]) self.assertEqual(checker.broken, False) mock_exists.return_value = False mock_popen.call_count = 0 checker = ocsp.RevocationChecker() self.assertEqual(mock_popen.call_count, 0) self.assertEqual(mock_log.call_count, 1) self.assertEqual(checker.broken, True) @mock.patch('certbot.ocsp.RevocationChecker.determine_ocsp_server') @mock.patch('certbot.util.run_script') def test_ocsp_revoked(self, mock_run, mock_determine): self.checker.broken = True mock_determine.return_value = ("", "") self.assertEqual(self.checker.ocsp_revoked("x", "y"), False) self.checker.broken = False mock_run.return_value = tuple(openssl_happy[1:]) self.assertEqual(self.checker.ocsp_revoked("x", "y"), False) self.assertEqual(mock_run.call_count, 0) mock_determine.return_value = ("http://x.co", "x.co") self.assertEqual(self.checker.ocsp_revoked("blah.pem", "chain.pem"), False) mock_run.side_effect = errors.SubprocessError("Unable to load certificate launcher") self.assertEqual(self.checker.ocsp_revoked("x", "y"), False) self.assertEqual(mock_run.call_count, 2) @mock.patch('certbot.ocsp.logger.info') @mock.patch('certbot.util.run_script') def test_determine_ocsp_server(self, mock_run, mock_info): uri = "http://ocsp.stg-int-x1.letsencrypt.org/" host = "ocsp.stg-int-x1.letsencrypt.org" mock_run.return_value = uri, "" self.assertEqual(self.checker.determine_ocsp_server("beep"), (uri, host)) mock_run.return_value = "ftp:/" + host + "/", "" self.assertEqual(self.checker.determine_ocsp_server("beep"), (None, None)) self.assertEqual(mock_info.call_count, 1) c = "confusion" mock_run.side_effect = errors.SubprocessError(c) self.assertEqual(self.checker.determine_ocsp_server("beep"), (None, None)) @mock.patch('certbot.ocsp.logger') @mock.patch('certbot.util.run_script') def test_translate_ocsp(self, mock_run, mock_log): # pylint: disable=protected-access,star-args mock_run.return_value = openssl_confused from certbot import ocsp self.assertEqual(ocsp._translate_ocsp_query(*openssl_happy), False) self.assertEqual(ocsp._translate_ocsp_query(*openssl_confused), False) self.assertEqual(mock_log.debug.call_count, 1) self.assertEqual(mock_log.warn.call_count, 0) mock_log.debug.call_count = 0 self.assertEqual(ocsp._translate_ocsp_query(*openssl_unknown), False) self.assertEqual(mock_log.debug.call_count, 1) self.assertEqual(mock_log.warn.call_count, 0) self.assertEqual(ocsp._translate_ocsp_query(*openssl_expired_ocsp), False) self.assertEqual(mock_log.debug.call_count, 2) self.assertEqual(ocsp._translate_ocsp_query(*openssl_broken), False) self.assertEqual(mock_log.warn.call_count, 1) mock_log.info.call_count = 0 self.assertEqual(ocsp._translate_ocsp_query(*openssl_revoked), True) self.assertEqual(mock_log.info.call_count, 0) self.assertEqual(ocsp._translate_ocsp_query(*openssl_expired_ocsp_revoked), True) self.assertEqual(mock_log.info.call_count, 1) # pylint: disable=line-too-long openssl_confused = ("", """ /etc/letsencrypt/live/example.org/cert.pem: good This Update: Dec 17 00:00:00 2016 GMT Next Update: Dec 24 00:00:00 2016 GMT """, """ Response Verify Failure 139903674214048:error:27069065:OCSP routines:OCSP_basic_verify:certificate verify error:ocsp_vfy.c:138:Verify error:unable to get local issuer certificate """) openssl_happy = ("blah.pem", """ blah.pem: good This Update: Dec 20 18:00:00 2016 GMT Next Update: Dec 27 18:00:00 2016 GMT """, "Response verify OK") openssl_revoked = ("blah.pem", """ blah.pem: revoked This Update: Dec 20 01:00:00 2016 GMT Next Update: Dec 27 01:00:00 2016 GMT Revocation Time: Dec 20 01:46:34 2016 GMT """, """Response verify OK""") openssl_unknown = ("blah.pem", """ blah.pem: unknown This Update: Dec 20 18:00:00 2016 GMT Next Update: Dec 27 18:00:00 2016 GMT """, "Response verify OK") openssl_broken = ("", "tentacles", "Response verify OK") openssl_expired_ocsp = ("blah.pem", """ blah.pem: WARNING: Status times invalid. 140659132298912:error:2707307D:OCSP routines:OCSP_check_validity:status expired:ocsp_cl.c:372: good This Update: Apr 6 00:00:00 2016 GMT Next Update: Apr 13 00:00:00 2016 GMT """, """Response verify OK""") openssl_expired_ocsp_revoked = ("blah.pem", """ blah.pem: WARNING: Status times invalid. 140659132298912:error:2707307D:OCSP routines:OCSP_check_validity:status expired:ocsp_cl.c:372: revoked This Update: Apr 6 00:00:00 2016 GMT Next Update: Apr 13 00:00:00 2016 GMT """, """Response verify OK""") if __name__ == '__main__': unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/notify_test.py0000644000175000017500000000410513344054434021163 0ustar ericaerica00000000000000"""Tests for certbot.notify.""" import socket import unittest import mock class NotifyTests(unittest.TestCase): """Tests for the notifier.""" @mock.patch("certbot.notify.smtplib.LMTP") def test_smtp_success(self, mock_lmtp): from certbot.notify import notify lmtp_obj = mock.MagicMock() mock_lmtp.return_value = lmtp_obj self.assertTrue(notify("Goose", "auntrhody@example.com", "The old grey goose is dead.")) self.assertEqual(lmtp_obj.connect.call_count, 1) self.assertEqual(lmtp_obj.sendmail.call_count, 1) @mock.patch("certbot.notify.smtplib.LMTP") @mock.patch("certbot.notify.subprocess.Popen") def test_smtp_failure(self, mock_popen, mock_lmtp): from certbot.notify import notify lmtp_obj = mock.MagicMock() mock_lmtp.return_value = lmtp_obj lmtp_obj.sendmail.side_effect = socket.error(17) proc = mock.MagicMock() mock_popen.return_value = proc self.assertTrue(notify("Goose", "auntrhody@example.com", "The old grey goose is dead.")) self.assertEqual(lmtp_obj.sendmail.call_count, 1) self.assertEqual(proc.communicate.call_count, 1) @mock.patch("certbot.notify.smtplib.LMTP") @mock.patch("certbot.notify.subprocess.Popen") def test_everything_fails(self, mock_popen, mock_lmtp): from certbot.notify import notify lmtp_obj = mock.MagicMock() mock_lmtp.return_value = lmtp_obj lmtp_obj.sendmail.side_effect = socket.error(17) proc = mock.MagicMock() mock_popen.return_value = proc proc.communicate.side_effect = OSError("What we have here is a " "failure to communicate.") self.assertFalse(notify("Goose", "auntrhody@example.com", "The old grey goose is dead.")) self.assertEqual(lmtp_obj.sendmail.call_count, 1) self.assertEqual(proc.communicate.call_count, 1) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/storage_test.py0000644000175000017500000012263613344054434021331 0ustar ericaerica00000000000000"""Tests for certbot.storage.""" # pylint disable=protected-access import datetime import os import shutil import stat import unittest import configobj import mock import pytz import six import certbot from certbot import cli from certbot import errors from certbot.storage import ALL_FOUR import certbot.tests.util as test_util CERT = test_util.load_cert('cert_512.pem') def unlink_all(rc_object): """Unlink all four items associated with this RenewableCert.""" for kind in ALL_FOUR: os.unlink(getattr(rc_object, kind)) def fill_with_sample_data(rc_object): """Put dummy data into all four files of this RenewableCert.""" for kind in ALL_FOUR: with open(getattr(rc_object, kind), "w") as f: f.write(kind) class BaseRenewableCertTest(test_util.ConfigTestCase): """Base class for setting up Renewable Cert tests. .. note:: It may be required to write out self.config for your test. Check :class:`.cli_test.DuplicateCertTest` for an example. """ def setUp(self): from certbot import storage super(BaseRenewableCertTest, self).setUp() # TODO: maybe provide NamespaceConfig.make_dirs? # TODO: main() should create those dirs, c.f. #902 os.makedirs(os.path.join(self.config.config_dir, "live", "example.org")) archive_path = os.path.join(self.config.config_dir, "archive", "example.org") os.makedirs(archive_path) os.makedirs(os.path.join(self.config.config_dir, "renewal")) config_file = configobj.ConfigObj() for kind in ALL_FOUR: kind_path = os.path.join(self.config.config_dir, "live", "example.org", kind + ".pem") config_file[kind] = kind_path with open(os.path.join(self.config.config_dir, "live", "example.org", "README"), 'a'): pass config_file["archive"] = archive_path config_file.filename = os.path.join(self.config.config_dir, "renewal", "example.org.conf") config_file.write() self.config_file = config_file # We also create a file that isn't a renewal config in the same # location to test that logic that reads in all-and-only renewal # configs will ignore it and NOT attempt to parse it. junk = open(os.path.join(self.config.config_dir, "renewal", "IGNORE.THIS"), "w") junk.write("This file should be ignored!") junk.close() self.defaults = configobj.ConfigObj() with mock.patch("certbot.storage.RenewableCert._check_symlinks") as check: check.return_value = True self.test_rc = storage.RenewableCert(config_file.filename, self.config) def _write_out_kind(self, kind, ver, value=None): link = getattr(self.test_rc, kind) if os.path.lexists(link): os.unlink(link) os.symlink(os.path.join(os.path.pardir, os.path.pardir, "archive", "example.org", "{0}{1}.pem".format(kind, ver)), link) with open(link, "wb") as f: f.write(kind.encode('ascii') if value is None else value) def _write_out_ex_kinds(self): for kind in ALL_FOUR: self._write_out_kind(kind, 12) self._write_out_kind(kind, 11) class RenewableCertTests(BaseRenewableCertTest): # pylint: disable=too-many-public-methods """Tests for certbot.storage.""" def test_initialization(self): self.assertEqual(self.test_rc.lineagename, "example.org") for kind in ALL_FOUR: self.assertEqual( getattr(self.test_rc, kind), os.path.join( self.config.config_dir, "live", "example.org", kind + ".pem")) def test_renewal_bad_config(self): """Test that the RenewableCert constructor will complain if the renewal configuration file doesn't end in ".conf" """ from certbot import storage broken = os.path.join(self.config.config_dir, "broken.conf") with open(broken, "w") as f: f.write("[No closing bracket for you!") self.assertRaises(errors.CertStorageError, storage.RenewableCert, broken, self.config) os.unlink(broken) self.assertRaises(errors.CertStorageError, storage.RenewableCert, "fun", self.config) def test_renewal_incomplete_config(self): """Test that the RenewableCert constructor will complain if the renewal configuration file is missing a required file element.""" from certbot import storage config = configobj.ConfigObj() config["cert"] = "imaginary_cert.pem" # Here the required privkey is missing. config["chain"] = "imaginary_chain.pem" config["fullchain"] = "imaginary_fullchain.pem" config.filename = os.path.join(self.config.config_dir, "imaginary_config.conf") config.write() self.assertRaises(errors.CertStorageError, storage.RenewableCert, config.filename, self.config) def test_no_renewal_version(self): from certbot import storage self._write_out_ex_kinds() self.assertTrue("version" not in self.config_file) with mock.patch("certbot.storage.logger") as mock_logger: storage.RenewableCert(self.config_file.filename, self.config) self.assertFalse(mock_logger.warning.called) def test_renewal_newer_version(self): from certbot import storage self._write_out_ex_kinds() self.config_file["version"] = "99.99.99" self.config_file.write() with mock.patch("certbot.storage.logger") as mock_logger: storage.RenewableCert(self.config_file.filename, self.config) self.assertTrue(mock_logger.info.called) self.assertTrue("version" in mock_logger.info.call_args[0][0]) def test_consistent(self): # pylint: disable=too-many-statements,protected-access oldcert = self.test_rc.cert self.test_rc.cert = "relative/path" # Absolute path for item requirement self.assertFalse(self.test_rc._consistent()) self.test_rc.cert = oldcert # Items must exist requirement self.assertFalse(self.test_rc._consistent()) # Items must be symlinks requirements fill_with_sample_data(self.test_rc) self.assertFalse(self.test_rc._consistent()) unlink_all(self.test_rc) # Items must point to desired place if they are relative for kind in ALL_FOUR: os.symlink(os.path.join("..", kind + "17.pem"), getattr(self.test_rc, kind)) self.assertFalse(self.test_rc._consistent()) unlink_all(self.test_rc) # Items must point to desired place if they are absolute for kind in ALL_FOUR: os.symlink(os.path.join(self.config.config_dir, kind + "17.pem"), getattr(self.test_rc, kind)) self.assertFalse(self.test_rc._consistent()) unlink_all(self.test_rc) # Items must point to things that exist for kind in ALL_FOUR: os.symlink(os.path.join("..", "..", "archive", "example.org", kind + "17.pem"), getattr(self.test_rc, kind)) self.assertFalse(self.test_rc._consistent()) # This version should work fill_with_sample_data(self.test_rc) self.assertTrue(self.test_rc._consistent()) # Items must point to things that follow the naming convention os.unlink(self.test_rc.fullchain) os.symlink(os.path.join("..", "..", "archive", "example.org", "fullchain_17.pem"), self.test_rc.fullchain) with open(self.test_rc.fullchain, "w") as f: f.write("wrongly-named fullchain") self.assertFalse(self.test_rc._consistent()) def test_current_target(self): # Relative path logic self._write_out_kind("cert", 17) self.assertTrue(os.path.samefile(self.test_rc.current_target("cert"), os.path.join(self.config.config_dir, "archive", "example.org", "cert17.pem"))) # Absolute path logic os.unlink(self.test_rc.cert) os.symlink(os.path.join(self.config.config_dir, "archive", "example.org", "cert17.pem"), self.test_rc.cert) with open(self.test_rc.cert, "w") as f: f.write("cert") self.assertTrue(os.path.samefile(self.test_rc.current_target("cert"), os.path.join(self.config.config_dir, "archive", "example.org", "cert17.pem"))) def test_current_version(self): for ver in (1, 5, 10, 20): self._write_out_kind("cert", ver) os.unlink(self.test_rc.cert) os.symlink(os.path.join("..", "..", "archive", "example.org", "cert10.pem"), self.test_rc.cert) self.assertEqual(self.test_rc.current_version("cert"), 10) def test_no_current_version(self): self.assertEqual(self.test_rc.current_version("cert"), None) def test_latest_and_next_versions(self): for ver in six.moves.range(1, 6): for kind in ALL_FOUR: self._write_out_kind(kind, ver) self.assertEqual(self.test_rc.latest_common_version(), 5) self.assertEqual(self.test_rc.next_free_version(), 6) # Having one kind of file of a later version doesn't change the # result self._write_out_kind("privkey", 7) self.assertEqual(self.test_rc.latest_common_version(), 5) # ... although it does change the next free version self.assertEqual(self.test_rc.next_free_version(), 8) # Nor does having three out of four change the result self._write_out_kind("cert", 7) self._write_out_kind("fullchain", 7) self.assertEqual(self.test_rc.latest_common_version(), 5) # If we have everything from a much later version, it does change # the result for kind in ALL_FOUR: self._write_out_kind(kind, 17) self.assertEqual(self.test_rc.latest_common_version(), 17) self.assertEqual(self.test_rc.next_free_version(), 18) @mock.patch("certbot.storage.logger") def test_ensure_deployed(self, mock_logger): mock_update = self.test_rc.update_all_links_to = mock.Mock() mock_has_pending = self.test_rc.has_pending_deployment = mock.Mock() self.test_rc.latest_common_version = mock.Mock() mock_has_pending.return_value = False self.assertEqual(self.test_rc.ensure_deployed(), True) self.assertEqual(mock_update.call_count, 0) self.assertEqual(mock_logger.warn.call_count, 0) mock_has_pending.return_value = True self.assertEqual(self.test_rc.ensure_deployed(), False) self.assertEqual(mock_update.call_count, 1) self.assertEqual(mock_logger.warn.call_count, 1) def test_update_link_to(self): for ver in six.moves.range(1, 6): for kind in ALL_FOUR: self._write_out_kind(kind, ver) self.assertEqual(ver, self.test_rc.current_version(kind)) # pylint: disable=protected-access self.test_rc._update_link_to("cert", 3) self.test_rc._update_link_to("privkey", 2) self.assertEqual(3, self.test_rc.current_version("cert")) self.assertEqual(2, self.test_rc.current_version("privkey")) self.assertEqual(5, self.test_rc.current_version("chain")) self.assertEqual(5, self.test_rc.current_version("fullchain")) # Currently we are allowed to update to a version that doesn't exist self.test_rc._update_link_to("chain", 3000) # However, current_version doesn't allow querying the resulting # version (because it's a broken link). self.assertEqual(os.path.basename(os.readlink(self.test_rc.chain)), "chain3000.pem") def test_version(self): self._write_out_kind("cert", 12) # TODO: We should probably test that the directory is still the # same, but it's tricky because we can get an absolute # path out when we put a relative path in. self.assertEqual("cert8.pem", os.path.basename(self.test_rc.version("cert", 8))) def test_update_all_links_to_success(self): for ver in six.moves.range(1, 6): for kind in ALL_FOUR: self._write_out_kind(kind, ver) self.assertEqual(ver, self.test_rc.current_version(kind)) self.assertEqual(self.test_rc.latest_common_version(), 5) for ver in six.moves.range(1, 6): self.test_rc.update_all_links_to(ver) for kind in ALL_FOUR: self.assertEqual(ver, self.test_rc.current_version(kind)) self.assertEqual(self.test_rc.latest_common_version(), 5) def test_update_all_links_to_partial_failure(self): def unlink_or_raise(path, real_unlink=os.unlink): # pylint: disable=missing-docstring basename = os.path.basename(path) if "fullchain" in basename and basename.startswith("prev"): raise ValueError else: real_unlink(path) self._write_out_ex_kinds() with mock.patch("certbot.storage.os.unlink") as mock_unlink: mock_unlink.side_effect = unlink_or_raise self.assertRaises(ValueError, self.test_rc.update_all_links_to, 12) for kind in ALL_FOUR: self.assertEqual(self.test_rc.current_version(kind), 12) def test_update_all_links_to_full_failure(self): def unlink_or_raise(path, real_unlink=os.unlink): # pylint: disable=missing-docstring if "fullchain" in os.path.basename(path): raise ValueError else: real_unlink(path) self._write_out_ex_kinds() with mock.patch("certbot.storage.os.unlink") as mock_unlink: mock_unlink.side_effect = unlink_or_raise self.assertRaises(ValueError, self.test_rc.update_all_links_to, 12) for kind in ALL_FOUR: self.assertEqual(self.test_rc.current_version(kind), 11) def test_has_pending_deployment(self): for ver in six.moves.range(1, 6): for kind in ALL_FOUR: self._write_out_kind(kind, ver) self.assertEqual(ver, self.test_rc.current_version(kind)) for ver in six.moves.range(1, 6): self.test_rc.update_all_links_to(ver) for kind in ALL_FOUR: self.assertEqual(ver, self.test_rc.current_version(kind)) if ver < 5: self.assertTrue(self.test_rc.has_pending_deployment()) else: self.assertFalse(self.test_rc.has_pending_deployment()) def test_names(self): # Trying the current version self._write_out_kind("cert", 12, test_util.load_vector("cert-san_512.pem")) self.assertEqual(self.test_rc.names(), ["example.com", "www.example.com"]) # Trying a non-current version self._write_out_kind("cert", 15, test_util.load_vector("cert_512.pem")) self.assertEqual(self.test_rc.names(12), ["example.com", "www.example.com"]) # Testing common name is listed first self._write_out_kind( "cert", 12, test_util.load_vector("cert-5sans_512.pem")) self.assertEqual( self.test_rc.names(12), ["example.com"] + ["{0}.example.com".format(c) for c in "abcd"]) # Trying missing cert os.unlink(self.test_rc.cert) self.assertRaises(errors.CertStorageError, self.test_rc.names) @mock.patch("certbot.storage.cli") @mock.patch("certbot.storage.datetime") def test_time_interval_judgments(self, mock_datetime, mock_cli): """Test should_autodeploy() and should_autorenew() on the basis of expiry time windows.""" test_cert = test_util.load_vector("cert_512.pem") self._write_out_ex_kinds() self.test_rc.update_all_links_to(12) with open(self.test_rc.cert, "wb") as f: f.write(test_cert) self.test_rc.update_all_links_to(11) with open(self.test_rc.cert, "wb") as f: f.write(test_cert) mock_datetime.timedelta = datetime.timedelta mock_cli.set_by_cli.return_value = False self.test_rc.configuration["renewalparams"] = {} for (current_time, interval, result) in [ # 2014-12-13 12:00:00+00:00 (about 5 days prior to expiry) # Times that should result in autorenewal/autodeployment (1418472000, "2 months", True), (1418472000, "1 week", True), # Times that should not (1418472000, "4 days", False), (1418472000, "2 days", False), # 2009-05-01 12:00:00+00:00 (about 5 years prior to expiry) # Times that should result in autorenewal/autodeployment (1241179200, "7 years", True), (1241179200, "11 years 2 months", True), # Times that should not (1241179200, "8 hours", False), (1241179200, "2 days", False), (1241179200, "40 days", False), (1241179200, "9 months", False), # 2015-01-01 (after expiry has already happened, so all # intervals should cause autorenewal/autodeployment) (1420070400, "0 seconds", True), (1420070400, "10 seconds", True), (1420070400, "10 minutes", True), (1420070400, "10 weeks", True), (1420070400, "10 months", True), (1420070400, "10 years", True), (1420070400, "99 months", True), ]: sometime = datetime.datetime.utcfromtimestamp(current_time) mock_datetime.datetime.utcnow.return_value = sometime self.test_rc.configuration["deploy_before_expiry"] = interval self.test_rc.configuration["renew_before_expiry"] = interval self.assertEqual(self.test_rc.should_autodeploy(), result) self.assertEqual(self.test_rc.should_autorenew(), result) def test_autodeployment_is_enabled(self): self.assertTrue(self.test_rc.autodeployment_is_enabled()) self.test_rc.configuration["autodeploy"] = "1" self.assertTrue(self.test_rc.autodeployment_is_enabled()) self.test_rc.configuration["autodeploy"] = "0" self.assertFalse(self.test_rc.autodeployment_is_enabled()) def test_should_autodeploy(self): """Test should_autodeploy() on the basis of reasons other than expiry time window.""" # pylint: disable=too-many-statements # Autodeployment turned off self.test_rc.configuration["autodeploy"] = "0" self.assertFalse(self.test_rc.should_autodeploy()) self.test_rc.configuration["autodeploy"] = "1" # No pending deployment for ver in six.moves.range(1, 6): for kind in ALL_FOUR: self._write_out_kind(kind, ver) self.assertFalse(self.test_rc.should_autodeploy()) def test_autorenewal_is_enabled(self): self.test_rc.configuration["renewalparams"] = {} self.assertTrue(self.test_rc.autorenewal_is_enabled()) self.test_rc.configuration["renewalparams"]["autorenew"] = "True" self.assertTrue(self.test_rc.autorenewal_is_enabled()) self.test_rc.configuration["renewalparams"]["autorenew"] = "False" self.assertFalse(self.test_rc.autorenewal_is_enabled()) @mock.patch("certbot.storage.cli") @mock.patch("certbot.storage.RenewableCert.ocsp_revoked") def test_should_autorenew(self, mock_ocsp, mock_cli): """Test should_autorenew on the basis of reasons other than expiry time window.""" # pylint: disable=too-many-statements mock_cli.set_by_cli.return_value = False # Autorenewal turned off self.test_rc.configuration["renewalparams"] = {"autorenew": "False"} self.assertFalse(self.test_rc.should_autorenew()) self.test_rc.configuration["renewalparams"]["autorenew"] = "True" for kind in ALL_FOUR: self._write_out_kind(kind, 12) # Mandatory renewal on the basis of OCSP revocation mock_ocsp.return_value = True self.assertTrue(self.test_rc.should_autorenew()) mock_ocsp.return_value = False @mock.patch("certbot.storage.relevant_values") def test_save_successor(self, mock_rv): # Mock relevant_values() to claim that all values are relevant here # (to avoid instantiating parser) mock_rv.side_effect = lambda x: x for ver in six.moves.range(1, 6): for kind in ALL_FOUR: self._write_out_kind(kind, ver) self.test_rc.update_all_links_to(3) self.assertEqual( 6, self.test_rc.save_successor(3, b'new cert', None, b'new chain', self.config)) with open(self.test_rc.version("cert", 6)) as f: self.assertEqual(f.read(), "new cert") with open(self.test_rc.version("chain", 6)) as f: self.assertEqual(f.read(), "new chain") with open(self.test_rc.version("fullchain", 6)) as f: self.assertEqual(f.read(), "new cert" + "new chain") # version 6 of the key should be a link back to version 3 self.assertFalse(os.path.islink(self.test_rc.version("privkey", 3))) self.assertTrue(os.path.islink(self.test_rc.version("privkey", 6))) # Let's try two more updates self.assertEqual( 7, self.test_rc.save_successor(6, b'again', None, b'newer chain', self.config)) self.assertEqual( 8, self.test_rc.save_successor(7, b'hello', None, b'other chain', self.config)) # All of the subsequent versions should link directly to the original # privkey. for i in (6, 7, 8): self.assertTrue(os.path.islink(self.test_rc.version("privkey", i))) self.assertEqual("privkey3.pem", os.path.basename(os.readlink( self.test_rc.version("privkey", i)))) for kind in ALL_FOUR: self.assertEqual(self.test_rc.available_versions(kind), list(six.moves.range(1, 9))) self.assertEqual(self.test_rc.current_version(kind), 3) # Test updating from latest version rather than old version self.test_rc.update_all_links_to(8) self.assertEqual( 9, self.test_rc.save_successor(8, b'last', None, b'attempt', self.config)) for kind in ALL_FOUR: self.assertEqual(self.test_rc.available_versions(kind), list(six.moves.range(1, 10))) self.assertEqual(self.test_rc.current_version(kind), 8) with open(self.test_rc.version("fullchain", 9)) as f: self.assertEqual(f.read(), "last" + "attempt") temp_config_file = os.path.join(self.config.renewal_configs_dir, self.test_rc.lineagename) + ".conf.new" with open(temp_config_file, "w") as f: f.write("We previously crashed while writing me :(") # Test updating when providing a new privkey. The key should # be saved in a new file rather than creating a new symlink. self.assertEqual( 10, self.test_rc.save_successor(9, b'with', b'a', b'key', self.config)) self.assertTrue(os.path.exists(self.test_rc.version("privkey", 10))) self.assertFalse(os.path.islink(self.test_rc.version("privkey", 10))) self.assertFalse(os.path.exists(temp_config_file)) def _test_relevant_values_common(self, values): defaults = dict((option, cli.flag_default(option)) for option in ("authenticator", "installer", "rsa_key_size", "server",)) mock_parser = mock.Mock(args=[], verb="plugins", defaults=defaults) # make a copy to ensure values isn't modified values = values.copy() values.setdefault("server", defaults["server"]) expected_server = values["server"] from certbot.storage import relevant_values with mock.patch("certbot.cli.helpful_parser", mock_parser): rv = relevant_values(values) self.assertIn("server", rv) self.assertEqual(rv.pop("server"), expected_server) return rv def test_relevant_values(self): """Test that relevant_values() can reject an irrelevant value.""" self.assertEqual( self._test_relevant_values_common({"hello": "there"}), {}) def test_relevant_values_default(self): """Test that relevant_values() can reject a default value.""" option = "rsa_key_size" values = {option: cli.flag_default(option)} self.assertEqual(self._test_relevant_values_common(values), {}) def test_relevant_values_nondefault(self): """Test that relevant_values() can retain a non-default value.""" values = {"rsa_key_size": 12} self.assertEqual( self._test_relevant_values_common(values), values) def test_relevant_values_bool(self): values = {"allow_subset_of_names": True} self.assertEqual( self._test_relevant_values_common(values), values) def test_relevant_values_str(self): values = {"authenticator": "apache"} self.assertEqual( self._test_relevant_values_common(values), values) def test_relevant_values_plugins_none(self): self.assertEqual( self._test_relevant_values_common( {"authenticator": None, "installer": None}), {}) @mock.patch("certbot.cli.set_by_cli") @mock.patch("certbot.plugins.disco.PluginsRegistry.find_all") def test_relevant_values_namespace(self, mock_find_all, mock_set_by_cli): mock_set_by_cli.return_value = True mock_find_all.return_value = ["certbot-foo:bar"] values = {"certbot_foo:bar_baz": 42} self.assertEqual( self._test_relevant_values_common(values), values) def test_relevant_values_server(self): self.assertEqual( # _test_relevant_values_common handles testing the server # value and removes it self._test_relevant_values_common({"server": "example.org"}), {}) @mock.patch("certbot.storage.relevant_values") def test_new_lineage(self, mock_rv): """Test for new_lineage() class method.""" # Mock relevant_values to say everything is relevant here (so we # don't have to mock the parser to help it decide!) mock_rv.side_effect = lambda x: x from certbot import storage result = storage.RenewableCert.new_lineage( "the-lineage.com", b"cert", b"privkey", b"chain", self.config) # This consistency check tests most relevant properties about the # newly created cert lineage. # pylint: disable=protected-access self.assertTrue(result._consistent()) self.assertTrue(os.path.exists(os.path.join( self.config.renewal_configs_dir, "the-lineage.com.conf"))) self.assertTrue(os.path.exists(os.path.join( self.config.live_dir, "the-lineage.com", "README"))) with open(result.fullchain, "rb") as f: self.assertEqual(f.read(), b"cert" + b"chain") # Let's do it again and make sure it makes a different lineage result = storage.RenewableCert.new_lineage( "the-lineage.com", b"cert2", b"privkey2", b"chain2", self.config) self.assertTrue(os.path.exists(os.path.join( self.config.renewal_configs_dir, "the-lineage.com-0001.conf"))) self.assertTrue(os.path.exists(os.path.join( self.config.live_dir, "the-lineage.com-0001", "README"))) # Now trigger the detection of already existing files os.mkdir(os.path.join( self.config.live_dir, "the-lineage.com-0002")) self.assertRaises(errors.CertStorageError, storage.RenewableCert.new_lineage, "the-lineage.com", b"cert3", b"privkey3", b"chain3", self.config) os.mkdir(os.path.join(self.config.default_archive_dir, "other-example.com")) self.assertRaises(errors.CertStorageError, storage.RenewableCert.new_lineage, "other-example.com", b"cert4", b"privkey4", b"chain4", self.config) # Make sure it can accept renewal parameters result = storage.RenewableCert.new_lineage( "the-lineage.com", b"cert2", b"privkey2", b"chain2", self.config) # TODO: Conceivably we could test that the renewal parameters actually # got saved @mock.patch("certbot.storage.relevant_values") def test_new_lineage_nonexistent_dirs(self, mock_rv): """Test that directories can be created if they don't exist.""" # Mock relevant_values to say everything is relevant here (so we # don't have to mock the parser to help it decide!) mock_rv.side_effect = lambda x: x from certbot import storage shutil.rmtree(self.config.renewal_configs_dir) shutil.rmtree(self.config.default_archive_dir) shutil.rmtree(self.config.live_dir) storage.RenewableCert.new_lineage( "the-lineage.com", b"cert2", b"privkey2", b"chain2", self.config) self.assertTrue(os.path.exists( os.path.join( self.config.renewal_configs_dir, "the-lineage.com.conf"))) self.assertTrue(os.path.exists(os.path.join( self.config.live_dir, "the-lineage.com", "privkey.pem"))) self.assertTrue(os.path.exists(os.path.join( self.config.default_archive_dir, "the-lineage.com", "privkey1.pem"))) @mock.patch("certbot.storage.util.unique_lineage_name") def test_invalid_config_filename(self, mock_uln): from certbot import storage mock_uln.return_value = "this_does_not_end_with_dot_conf", "yikes" self.assertRaises(errors.CertStorageError, storage.RenewableCert.new_lineage, "example.com", "cert", "privkey", "chain", self.config) def test_bad_kind(self): self.assertRaises( errors.CertStorageError, self.test_rc.current_target, "elephant") self.assertRaises( errors.CertStorageError, self.test_rc.current_version, "elephant") self.assertRaises( errors.CertStorageError, self.test_rc.version, "elephant", 17) self.assertRaises( errors.CertStorageError, self.test_rc.available_versions, "elephant") self.assertRaises( errors.CertStorageError, self.test_rc.newest_available_version, "elephant") # pylint: disable=protected-access self.assertRaises( errors.CertStorageError, self.test_rc._update_link_to, "elephant", 17) def test_ocsp_revoked(self): # XXX: This is currently hardcoded to False due to a lack of an # OCSP server to test against. self.assertFalse(self.test_rc.ocsp_revoked()) def test_add_time_interval(self): from certbot import storage # this month has 30 days, and the next year is a leap year time_1 = pytz.UTC.fromutc(datetime.datetime(2003, 11, 20, 11, 59, 21)) # this month has 31 days, and the next year is not a leap year time_2 = pytz.UTC.fromutc(datetime.datetime(2012, 10, 18, 21, 31, 16)) # in different time zone (GMT+8) time_3 = pytz.timezone('Asia/Shanghai').fromutc( datetime.datetime(2015, 10, 26, 22, 25, 41)) intended = { (time_1, ""): time_1, (time_2, ""): time_2, (time_3, ""): time_3, (time_1, "17 days"): time_1 + datetime.timedelta(17), (time_2, "17 days"): time_2 + datetime.timedelta(17), (time_1, "30"): time_1 + datetime.timedelta(30), (time_2, "30"): time_2 + datetime.timedelta(30), (time_1, "7 weeks"): time_1 + datetime.timedelta(49), (time_2, "7 weeks"): time_2 + datetime.timedelta(49), # 1 month is always 30 days, no matter which month it is (time_1, "1 month"): time_1 + datetime.timedelta(30), (time_2, "1 month"): time_2 + datetime.timedelta(31), # 1 year could be 365 or 366 days, depends on the year (time_1, "1 year"): time_1 + datetime.timedelta(366), (time_2, "1 year"): time_2 + datetime.timedelta(365), (time_1, "1 year 1 day"): time_1 + datetime.timedelta(367), (time_2, "1 year 1 day"): time_2 + datetime.timedelta(366), (time_1, "1 year-1 day"): time_1 + datetime.timedelta(365), (time_2, "1 year-1 day"): time_2 + datetime.timedelta(364), (time_1, "4 years"): time_1 + datetime.timedelta(1461), (time_2, "4 years"): time_2 + datetime.timedelta(1461), } for parameters, excepted in intended.items(): base_time, interval = parameters self.assertEqual(storage.add_time_interval(base_time, interval), excepted) def test_is_test_cert(self): self.test_rc.configuration["renewalparams"] = {} rp = self.test_rc.configuration["renewalparams"] self.assertEqual(self.test_rc.is_test_cert, False) rp["server"] = "https://acme-staging-v02.api.letsencrypt.org/directory" self.assertEqual(self.test_rc.is_test_cert, True) rp["server"] = "https://staging.someotherca.com/directory" self.assertEqual(self.test_rc.is_test_cert, True) rp["server"] = "https://acme-v01.api.letsencrypt.org/directory" self.assertEqual(self.test_rc.is_test_cert, False) rp["server"] = "https://acme-v02.api.letsencrypt.org/directory" self.assertEqual(self.test_rc.is_test_cert, False) def test_missing_cert(self): from certbot import storage self.assertRaises(errors.CertStorageError, storage.RenewableCert, self.config_file.filename, self.config) os.symlink("missing", self.config_file[ALL_FOUR[0]]) self.assertRaises(errors.CertStorageError, storage.RenewableCert, self.config_file.filename, self.config) def test_write_renewal_config(self): # Mostly tested by the process of creating and updating lineages, # but we can test that this successfully creates files, removes # unneeded items, and preserves comments. temp = os.path.join(self.config.config_dir, "sample-file") temp2 = os.path.join(self.config.config_dir, "sample-file.new") with open(temp, "w") as f: f.write("[renewalparams]\nuseful = value # A useful value\n" "useless = value # Not needed\n") os.chmod(temp, 0o640) target = {} for x in ALL_FOUR: target[x] = "somewhere" archive_dir = "the_archive" relevant_data = {"useful": "new_value"} from certbot import storage storage.write_renewal_config(temp, temp2, archive_dir, target, relevant_data) with open(temp2, "r") as f: content = f.read() # useful value was updated self.assertTrue("useful = new_value" in content) # associated comment was preserved self.assertTrue("A useful value" in content) # useless value was deleted self.assertTrue("useless" not in content) # check version was stored self.assertTrue("version = {0}".format(certbot.__version__) in content) # ensure permissions are copied self.assertEqual(stat.S_IMODE(os.lstat(temp).st_mode), stat.S_IMODE(os.lstat(temp2).st_mode)) def test_update_symlinks(self): from certbot import storage archive_dir_path = os.path.join(self.config.config_dir, "archive", "example.org") for kind in ALL_FOUR: live_path = self.config_file[kind] basename = kind + "1.pem" archive_path = os.path.join(archive_dir_path, basename) open(archive_path, 'a').close() os.symlink(os.path.join(self.config.config_dir, basename), live_path) self.assertRaises(errors.CertStorageError, storage.RenewableCert, self.config_file.filename, self.config) storage.RenewableCert(self.config_file.filename, self.config, update_symlinks=True) class DeleteFilesTest(BaseRenewableCertTest): """Tests for certbot.storage.delete_files""" def setUp(self): super(DeleteFilesTest, self).setUp() for kind in ALL_FOUR: kind_path = os.path.join(self.config.config_dir, "live", "example.org", kind + ".pem") with open(kind_path, 'a'): pass self.config_file.write() self.assertTrue(os.path.exists(os.path.join( self.config.renewal_configs_dir, "example.org.conf"))) self.assertTrue(os.path.exists(os.path.join( self.config.live_dir, "example.org"))) self.assertTrue(os.path.exists(os.path.join( self.config.config_dir, "archive", "example.org"))) def _call(self): from certbot import storage with mock.patch("certbot.storage.logger"): storage.delete_files(self.config, "example.org") def test_delete_all_files(self): self._call() self.assertFalse(os.path.exists(os.path.join( self.config.renewal_configs_dir, "example.org.conf"))) self.assertFalse(os.path.exists(os.path.join( self.config.live_dir, "example.org"))) self.assertFalse(os.path.exists(os.path.join( self.config.config_dir, "archive", "example.org"))) def test_bad_renewal_config(self): with open(self.config_file.filename, 'a') as config_file: config_file.write("asdfasfasdfasdf") self.assertRaises(errors.CertStorageError, self._call) self.assertTrue(os.path.exists(os.path.join( self.config.live_dir, "example.org"))) self.assertFalse(os.path.exists(os.path.join( self.config.renewal_configs_dir, "example.org.conf"))) def test_no_renewal_config(self): os.remove(self.config_file.filename) self.assertRaises(errors.CertStorageError, self._call) self.assertTrue(os.path.exists(os.path.join( self.config.live_dir, "example.org"))) self.assertFalse(os.path.exists(self.config_file.filename)) def test_no_cert_file(self): os.remove(os.path.join( self.config.live_dir, "example.org", "cert.pem")) self._call() self.assertFalse(os.path.exists(self.config_file.filename)) self.assertFalse(os.path.exists(os.path.join( self.config.live_dir, "example.org"))) self.assertFalse(os.path.exists(os.path.join( self.config.config_dir, "archive", "example.org"))) def test_no_readme_file(self): os.remove(os.path.join( self.config.live_dir, "example.org", "README")) self._call() self.assertFalse(os.path.exists(self.config_file.filename)) self.assertFalse(os.path.exists(os.path.join( self.config.live_dir, "example.org"))) self.assertFalse(os.path.exists(os.path.join( self.config.config_dir, "archive", "example.org"))) def test_livedir_not_empty(self): with open(os.path.join( self.config.live_dir, "example.org", "other_file"), 'a'): pass self._call() self.assertFalse(os.path.exists(self.config_file.filename)) self.assertTrue(os.path.exists(os.path.join( self.config.live_dir, "example.org"))) self.assertFalse(os.path.exists(os.path.join( self.config.config_dir, "archive", "example.org"))) def test_no_archive(self): archive_dir = os.path.join(self.config.config_dir, "archive", "example.org") os.rmdir(archive_dir) self._call() self.assertFalse(os.path.exists(self.config_file.filename)) self.assertFalse(os.path.exists(os.path.join( self.config.live_dir, "example.org"))) self.assertFalse(os.path.exists(archive_dir)) class CertPathForCertNameTest(BaseRenewableCertTest): """Test for certbot.storage.cert_path_for_cert_name""" def setUp(self): super(CertPathForCertNameTest, self).setUp() self.config_file.write() self._write_out_ex_kinds() self.fullchain = os.path.join(self.config.config_dir, 'live', 'example.org', 'fullchain.pem') self.config.cert_path = (self.fullchain, '') def _call(self, cli_config, certname): from certbot.storage import cert_path_for_cert_name return cert_path_for_cert_name(cli_config, certname) def test_simple_cert_name(self): self.assertEqual(self._call(self.config, 'example.org'), (self.fullchain, 'fullchain')) def test_no_such_cert_name(self): self.assertRaises(errors.CertStorageError, self._call, self.config, 'fake-example.org') if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/cli_test.py0000644000175000017500000004643513344054434020436 0ustar ericaerica00000000000000"""Tests for certbot.cli.""" import argparse import unittest import os import tempfile import copy import mock import six from six.moves import reload_module # pylint: disable=import-error from acme import challenges from certbot import cli from certbot import constants from certbot import errors from certbot.plugins import disco import certbot.tests.util as test_util from certbot.tests.util import TempDirTestCase PLUGINS = disco.PluginsRegistry.find_all() class TestReadFile(TempDirTestCase): '''Test cli.read_file''' def test_read_file(self): rel_test_path = os.path.relpath(os.path.join(self.tempdir, 'foo')) self.assertRaises( argparse.ArgumentTypeError, cli.read_file, rel_test_path) test_contents = b'bar\n' with open(rel_test_path, 'wb') as f: f.write(test_contents) path, contents = cli.read_file(rel_test_path) self.assertEqual(path, os.path.abspath(path)) self.assertEqual(contents, test_contents) class ParseTest(unittest.TestCase): # pylint: disable=too-many-public-methods '''Test the cli args entrypoint''' def setUp(self): reload_module(cli) @staticmethod def _unmocked_parse(*args, **kwargs): """Get result of cli.prepare_and_parse_args.""" return cli.prepare_and_parse_args(PLUGINS, *args, **kwargs) @staticmethod def parse(*args, **kwargs): """Mocks zope.component.getUtility and calls _unmocked_parse.""" with test_util.patch_get_utility(): return ParseTest._unmocked_parse(*args, **kwargs) def _help_output(self, args): "Run a command, and return the output string for scrutiny" output = six.StringIO() def write_msg(message, *args, **kwargs): # pylint: disable=missing-docstring,unused-argument output.write(message) with mock.patch('certbot.main.sys.stdout', new=output): with test_util.patch_get_utility() as mock_get_utility: mock_get_utility().notification.side_effect = write_msg with mock.patch('certbot.main.sys.stderr'): self.assertRaises(SystemExit, self._unmocked_parse, args, output) return output.getvalue() @mock.patch("certbot.cli.flag_default") def test_cli_ini_domains(self, mock_flag_default): tmp_config = tempfile.NamedTemporaryFile() # use a shim to get ConfigArgParse to pick up tmp_config shim = ( lambda v: copy.deepcopy(constants.CLI_DEFAULTS[v]) if v != "config_files" else [tmp_config.name] ) mock_flag_default.side_effect = shim namespace = self.parse(["certonly"]) self.assertEqual(namespace.domains, []) tmp_config.write(b"domains = example.com") tmp_config.flush() namespace = self.parse(["certonly"]) self.assertEqual(namespace.domains, ["example.com"]) namespace = self.parse(["renew"]) self.assertEqual(namespace.domains, []) def test_no_args(self): namespace = self.parse([]) for d in ('config_dir', 'logs_dir', 'work_dir'): self.assertEqual(getattr(namespace, d), cli.flag_default(d)) def test_install_abspath(self): cert = 'cert' key = 'key' chain = 'chain' fullchain = 'fullchain' with mock.patch('certbot.main.install'): namespace = self.parse(['install', '--cert-path', cert, '--key-path', 'key', '--chain-path', 'chain', '--fullchain-path', 'fullchain']) self.assertEqual(namespace.cert_path, os.path.abspath(cert)) self.assertEqual(namespace.key_path, os.path.abspath(key)) self.assertEqual(namespace.chain_path, os.path.abspath(chain)) self.assertEqual(namespace.fullchain_path, os.path.abspath(fullchain)) def test_help(self): self._help_output(['--help']) # assert SystemExit is raised here out = self._help_output(['--help', 'all']) self.assertTrue("--configurator" in out) self.assertTrue("how a certificate is deployed" in out) self.assertTrue("--webroot-path" in out) self.assertTrue("--text" not in out) self.assertTrue("--dialog" not in out) self.assertTrue("%s" not in out) self.assertTrue("{0}" not in out) self.assertTrue("--renew-hook" not in out) out = self._help_output(['-h', 'nginx']) if "nginx" in PLUGINS: # may be false while building distributions without plugins self.assertTrue("--nginx-ctl" in out) self.assertTrue("--webroot-path" not in out) self.assertTrue("--checkpoints" not in out) out = self._help_output(['-h']) self.assertTrue("letsencrypt-auto" not in out) # test cli.cli_command if "nginx" in PLUGINS: self.assertTrue("Use the Nginx plugin" in out) else: self.assertTrue("(the certbot nginx plugin is not" in out) out = self._help_output(['--help', 'plugins']) self.assertTrue("--webroot-path" not in out) self.assertTrue("--prepare" in out) self.assertTrue('"plugins" subcommand' in out) # test multiple topics out = self._help_output(['-h', 'renew']) self.assertTrue("--keep" in out) out = self._help_output(['-h', 'automation']) self.assertTrue("--keep" in out) out = self._help_output(['-h', 'revoke']) self.assertTrue("--keep" not in out) out = self._help_output(['--help', 'install']) self.assertTrue("--cert-path" in out) self.assertTrue("--key-path" in out) out = self._help_output(['--help', 'revoke']) self.assertTrue("--cert-path" in out) self.assertTrue("--key-path" in out) self.assertTrue("--reason" in out) self.assertTrue("--delete-after-revoke" in out) self.assertTrue("--no-delete-after-revoke" in out) out = self._help_output(['-h', 'config_changes']) self.assertTrue("--cert-path" not in out) self.assertTrue("--key-path" not in out) out = self._help_output(['-h']) self.assertTrue(cli.SHORT_USAGE in out) self.assertTrue(cli.COMMAND_OVERVIEW[:100] in out) self.assertTrue("%s" not in out) self.assertTrue("{0}" not in out) def test_help_no_dashes(self): self._help_output(['help']) # assert SystemExit is raised here out = self._help_output(['help', 'all']) self.assertTrue("--configurator" in out) self.assertTrue("how a certificate is deployed" in out) self.assertTrue("--webroot-path" in out) self.assertTrue("--text" not in out) self.assertTrue("--dialog" not in out) self.assertTrue("%s" not in out) self.assertTrue("{0}" not in out) out = self._help_output(['help', 'install']) self.assertTrue("--cert-path" in out) self.assertTrue("--key-path" in out) out = self._help_output(['help', 'revoke']) self.assertTrue("--cert-path" in out) self.assertTrue("--key-path" in out) def test_parse_domains(self): short_args = ['-d', 'example.com'] namespace = self.parse(short_args) self.assertEqual(namespace.domains, ['example.com']) short_args = ['-d', 'trailing.period.com.'] namespace = self.parse(short_args) self.assertEqual(namespace.domains, ['trailing.period.com']) short_args = ['-d', 'example.com,another.net,third.org,example.com'] namespace = self.parse(short_args) self.assertEqual(namespace.domains, ['example.com', 'another.net', 'third.org']) long_args = ['--domains', 'example.com'] namespace = self.parse(long_args) self.assertEqual(namespace.domains, ['example.com']) long_args = ['--domains', 'trailing.period.com.'] namespace = self.parse(long_args) self.assertEqual(namespace.domains, ['trailing.period.com']) long_args = ['--domains', 'example.com,another.net,example.com'] namespace = self.parse(long_args) self.assertEqual(namespace.domains, ['example.com', 'another.net']) def test_preferred_challenges(self): short_args = ['--preferred-challenges', 'http, tls-sni-01, dns'] namespace = self.parse(short_args) expected = [challenges.HTTP01.typ, challenges.TLSSNI01.typ, challenges.DNS01.typ] self.assertEqual(namespace.pref_challs, expected) short_args = ['--preferred-challenges', 'jumping-over-the-moon'] # argparse.ArgumentError makes argparse print more information # to stderr and call sys.exit() with mock.patch('sys.stderr'): self.assertRaises(SystemExit, self.parse, short_args) def test_server_flag(self): namespace = self.parse('--server example.com'.split()) self.assertEqual(namespace.server, 'example.com') def test_must_staple_flag(self): short_args = ['--must-staple'] namespace = self.parse(short_args) self.assertTrue(namespace.must_staple) self.assertTrue(namespace.staple) def test_no_gui(self): args = ['renew', '--dialog'] stderr = six.StringIO() with mock.patch('certbot.main.sys.stderr', new=stderr): namespace = self.parse(args) self.assertTrue(namespace.noninteractive_mode) self.assertTrue("--dialog is deprecated" in stderr.getvalue()) def _check_server_conflict_message(self, parser_args, conflicting_args): try: self.parse(parser_args) self.fail( # pragma: no cover "The following flags didn't conflict with " '--server: {0}'.format(', '.join(conflicting_args))) except errors.Error as error: self.assertTrue('--server' in str(error)) for arg in conflicting_args: self.assertTrue(arg in str(error)) def test_staging_flag(self): short_args = ['--staging'] namespace = self.parse(short_args) self.assertTrue(namespace.staging) self.assertEqual(namespace.server, constants.STAGING_URI) short_args += '--server example.com'.split() self._check_server_conflict_message(short_args, '--staging') def _assert_dry_run_flag_worked(self, namespace, existing_account): self.assertTrue(namespace.dry_run) self.assertTrue(namespace.break_my_certs) self.assertTrue(namespace.staging) self.assertEqual(namespace.server, constants.STAGING_URI) if existing_account: self.assertTrue(namespace.tos) self.assertTrue(namespace.register_unsafely_without_email) else: self.assertFalse(namespace.tos) self.assertFalse(namespace.register_unsafely_without_email) def test_dry_run_flag(self): config_dir = tempfile.mkdtemp() short_args = '--dry-run --config-dir {0}'.format(config_dir).split() self.assertRaises(errors.Error, self.parse, short_args) self._assert_dry_run_flag_worked( self.parse(short_args + ['auth']), False) self._assert_dry_run_flag_worked( self.parse(short_args + ['certonly']), False) self._assert_dry_run_flag_worked( self.parse(short_args + ['renew']), False) account_dir = os.path.join(config_dir, constants.ACCOUNTS_DIR) os.mkdir(account_dir) os.mkdir(os.path.join(account_dir, 'fake_account_dir')) self._assert_dry_run_flag_worked(self.parse(short_args + ['auth']), True) self._assert_dry_run_flag_worked(self.parse(short_args + ['renew']), True) short_args += ['certonly'] self._assert_dry_run_flag_worked(self.parse(short_args), True) short_args += '--server example.com'.split() conflicts = ['--dry-run'] self._check_server_conflict_message(short_args, '--dry-run') short_args += ['--staging'] conflicts += ['--staging'] self._check_server_conflict_message(short_args, conflicts) def test_option_was_set(self): key_size_option = 'rsa_key_size' key_size_value = cli.flag_default(key_size_option) self.parse('--rsa-key-size {0}'.format(key_size_value).split()) self.assertTrue(cli.option_was_set(key_size_option, key_size_value)) self.assertTrue(cli.option_was_set('no_verify_ssl', True)) config_dir_option = 'config_dir' self.assertFalse(cli.option_was_set( config_dir_option, cli.flag_default(config_dir_option))) def test_encode_revocation_reason(self): for reason, code in constants.REVOCATION_REASONS.items(): namespace = self.parse(['--reason', reason]) self.assertEqual(namespace.reason, code) for reason, code in constants.REVOCATION_REASONS.items(): namespace = self.parse(['--reason', reason.upper()]) self.assertEqual(namespace.reason, code) def test_force_interactive(self): self.assertRaises( errors.Error, self.parse, "renew --force-interactive".split()) self.assertRaises( errors.Error, self.parse, "-n --force-interactive".split()) def test_deploy_hook_conflict(self): with mock.patch("certbot.cli.sys.stderr"): self.assertRaises(SystemExit, self.parse, "--renew-hook foo --deploy-hook bar".split()) def test_deploy_hook_matches_renew_hook(self): value = "foo" namespace = self.parse(["--renew-hook", value, "--deploy-hook", value, "--disable-hook-validation"]) self.assertEqual(namespace.deploy_hook, value) self.assertEqual(namespace.renew_hook, value) def test_deploy_hook_sets_renew_hook(self): value = "foo" namespace = self.parse( ["--deploy-hook", value, "--disable-hook-validation"]) self.assertEqual(namespace.deploy_hook, value) self.assertEqual(namespace.renew_hook, value) def test_renew_hook_conflict(self): with mock.patch("certbot.cli.sys.stderr"): self.assertRaises(SystemExit, self.parse, "--deploy-hook foo --renew-hook bar".split()) def test_renew_hook_matches_deploy_hook(self): value = "foo" namespace = self.parse(["--deploy-hook", value, "--renew-hook", value, "--disable-hook-validation"]) self.assertEqual(namespace.deploy_hook, value) self.assertEqual(namespace.renew_hook, value) def test_renew_hook_does_not_set_renew_hook(self): value = "foo" namespace = self.parse( ["--renew-hook", value, "--disable-hook-validation"]) self.assertEqual(namespace.deploy_hook, None) self.assertEqual(namespace.renew_hook, value) def test_max_log_backups_error(self): with mock.patch('certbot.cli.sys.stderr'): self.assertRaises( SystemExit, self.parse, "--max-log-backups foo".split()) self.assertRaises( SystemExit, self.parse, "--max-log-backups -42".split()) def test_max_log_backups_success(self): value = "42" namespace = self.parse(["--max-log-backups", value]) self.assertEqual(namespace.max_log_backups, int(value)) def test_unchanging_defaults(self): namespace = self.parse([]) self.assertEqual(namespace.domains, []) self.assertEqual(namespace.pref_challs, []) namespace.pref_challs = [challenges.HTTP01.typ] namespace.domains = ['example.com'] namespace = self.parse([]) self.assertEqual(namespace.domains, []) self.assertEqual(namespace.pref_challs, []) def test_no_directory_hooks_set(self): self.assertFalse(self.parse(["--no-directory-hooks"]).directory_hooks) def test_no_directory_hooks_unset(self): self.assertTrue(self.parse([]).directory_hooks) def test_delete_after_revoke(self): namespace = self.parse(["--delete-after-revoke"]) self.assertTrue(namespace.delete_after_revoke) def test_delete_after_revoke_default(self): namespace = self.parse([]) self.assertEqual(namespace.delete_after_revoke, None) def test_no_delete_after_revoke(self): namespace = self.parse(["--no-delete-after-revoke"]) self.assertFalse(namespace.delete_after_revoke) def test_allow_subset_with_wildcard(self): self.assertRaises(errors.Error, self.parse, "--allow-subset-of-names -d *.example.org".split()) class DefaultTest(unittest.TestCase): """Tests for certbot.cli._Default.""" def setUp(self): # pylint: disable=protected-access self.default1 = cli._Default() self.default2 = cli._Default() def test_boolean(self): self.assertFalse(self.default1) self.assertFalse(self.default2) def test_equality(self): self.assertEqual(self.default1, self.default2) def test_hash(self): self.assertEqual(hash(self.default1), hash(self.default2)) class SetByCliTest(unittest.TestCase): """Tests for certbot.set_by_cli and related functions.""" def setUp(self): reload_module(cli) def test_deploy_hook(self): self.assertTrue(_call_set_by_cli( 'renew_hook', '--deploy-hook foo'.split(), 'renew')) def test_webroot_map(self): args = '-w /var/www/html -d example.com'.split() verb = 'renew' self.assertTrue(_call_set_by_cli('webroot_map', args, verb)) def test_report_config_interaction_str(self): cli.report_config_interaction('manual_public_ip_logging_ok', 'manual_auth_hook') cli.report_config_interaction('manual_auth_hook', 'manual') self._test_report_config_interaction_common() def test_report_config_interaction_iterable(self): cli.report_config_interaction(('manual_public_ip_logging_ok',), ('manual_auth_hook',)) cli.report_config_interaction(('manual_auth_hook',), ('manual',)) self._test_report_config_interaction_common() def _test_report_config_interaction_common(self): """Tests implied interaction between manual flags. --manual implies --manual-auth-hook which implies --manual-public-ip-logging-ok. These interactions don't actually exist in the client, but are used here for testing purposes. """ args = ['--manual'] verb = 'renew' for v in ('manual', 'manual_auth_hook', 'manual_public_ip_logging_ok'): self.assertTrue(_call_set_by_cli(v, args, verb)) # https://github.com/python/mypy/issues/2087 cli.set_by_cli.detector = None # type: ignore args = ['--manual-auth-hook', 'command'] for v in ('manual_auth_hook', 'manual_public_ip_logging_ok'): self.assertTrue(_call_set_by_cli(v, args, verb)) self.assertFalse(_call_set_by_cli('manual', args, verb)) def _call_set_by_cli(var, args, verb): with mock.patch('certbot.cli.helpful_parser') as mock_parser: with test_util.patch_get_utility(): mock_parser.args = args mock_parser.verb = verb return cli.set_by_cli(var) if __name__ == '__main__': unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/client_test.py0000644000175000017500000006310113344054434021132 0ustar ericaerica00000000000000"""Tests for certbot.client.""" import os import platform import shutil import tempfile import unittest import mock from certbot import account from certbot import errors from certbot import util import certbot.tests.util as test_util KEY = test_util.load_vector("rsa512_key.pem") CSR_SAN = test_util.load_vector("csr-san_512.pem") class DetermineUserAgentTest(test_util.ConfigTestCase): """Tests for certbot.client.determine_user_agent.""" def _call(self): from certbot.client import determine_user_agent return determine_user_agent(self.config) @mock.patch.dict(os.environ, {"CERTBOT_DOCS": "1"}) def test_docs_value(self): self._test(expect_doc_values=True) @mock.patch.dict(os.environ, {}) def test_real_values(self): self._test(expect_doc_values=False) def _test(self, expect_doc_values): ua = self._call() if expect_doc_values: doc_value_check = self.assertIn real_value_check = self.assertNotIn else: doc_value_check = self.assertNotIn real_value_check = self.assertIn doc_value_check("certbot(-auto)", ua) doc_value_check("OS_NAME OS_VERSION", ua) doc_value_check("major.minor.patchlevel", ua) real_value_check(util.get_os_info_ua(), ua) real_value_check(platform.python_version(), ua) class RegisterTest(test_util.ConfigTestCase): """Tests for certbot.client.register.""" def setUp(self): super(RegisterTest, self).setUp() self.config.rsa_key_size = 1024 self.config.register_unsafely_without_email = False self.config.email = "alias@example.com" self.account_storage = account.AccountMemoryStorage() def _call(self): from certbot.client import register tos_cb = mock.MagicMock() return register(self.config, self.account_storage, tos_cb) def test_no_tos(self): with mock.patch("certbot.client.acme_client.BackwardsCompatibleClientV2") as mock_client: mock_client.new_account_and_tos().terms_of_service = "http://tos" with mock.patch("certbot.eff.handle_subscription") as mock_handle: with mock.patch("certbot.account.report_new_account"): mock_client().new_account_and_tos.side_effect = errors.Error self.assertRaises(errors.Error, self._call) self.assertFalse(mock_handle.called) mock_client().new_account_and_tos.side_effect = None self._call() self.assertTrue(mock_handle.called) def test_it(self): with mock.patch("certbot.client.acme_client.BackwardsCompatibleClientV2"): with mock.patch("certbot.account.report_new_account"): with mock.patch("certbot.eff.handle_subscription"): self._call() @mock.patch("certbot.account.report_new_account") @mock.patch("certbot.client.display_ops.get_email") def test_email_retry(self, _rep, mock_get_email): from acme import messages self.config.noninteractive_mode = False msg = "DNS problem: NXDOMAIN looking up MX for example.com" mx_err = messages.Error.with_code('invalidContact', detail=msg) with mock.patch("certbot.client.acme_client.BackwardsCompatibleClientV2") as mock_client: with mock.patch("certbot.eff.handle_subscription") as mock_handle: mock_client().new_account_and_tos.side_effect = [mx_err, mock.MagicMock()] self._call() self.assertEqual(mock_get_email.call_count, 1) self.assertTrue(mock_handle.called) @mock.patch("certbot.account.report_new_account") def test_email_invalid_noninteractive(self, _rep): from acme import messages self.config.noninteractive_mode = True msg = "DNS problem: NXDOMAIN looking up MX for example.com" mx_err = messages.Error.with_code('invalidContact', detail=msg) with mock.patch("certbot.client.acme_client.BackwardsCompatibleClientV2") as mock_client: with mock.patch("certbot.eff.handle_subscription"): mock_client().new_account_and_tos.side_effect = [mx_err, mock.MagicMock()] self.assertRaises(errors.Error, self._call) def test_needs_email(self): self.config.email = None self.assertRaises(errors.Error, self._call) @mock.patch("certbot.client.logger") def test_without_email(self, mock_logger): with mock.patch("certbot.eff.handle_subscription") as mock_handle: with mock.patch("certbot.client.acme_client.BackwardsCompatibleClientV2"): with mock.patch("certbot.account.report_new_account"): self.config.email = None self.config.register_unsafely_without_email = True self.config.dry_run = False self._call() mock_logger.info.assert_called_once_with(mock.ANY) self.assertTrue(mock_handle.called) @mock.patch("certbot.account.report_new_account") @mock.patch("certbot.client.display_ops.get_email") def test_dry_run_no_staging_account(self, _rep, mock_get_email): """Tests dry-run for no staging account, expect account created with no email""" with mock.patch("certbot.client.acme_client.BackwardsCompatibleClientV2") as mock_client: with mock.patch("certbot.eff.handle_subscription"): with mock.patch("certbot.account.report_new_account"): self.config.dry_run = True self._call() # check Certbot did not ask the user to provide an email self.assertFalse(mock_get_email.called) # check Certbot created an account with no email. Contact should return empty self.assertFalse(mock_client().new_account_and_tos.call_args[0][0].contact) def test_unsupported_error(self): from acme import messages msg = "Test" mx_err = messages.Error(detail=msg, typ="malformed", title="title") with mock.patch("certbot.client.acme_client.BackwardsCompatibleClientV2") as mock_client: with mock.patch("certbot.eff.handle_subscription") as mock_handle: mock_client().new_account_and_tos.side_effect = [mx_err, mock.MagicMock()] self.assertRaises(messages.Error, self._call) self.assertFalse(mock_handle.called) class ClientTestCommon(test_util.ConfigTestCase): """Common base class for certbot.client.Client tests.""" def setUp(self): super(ClientTestCommon, self).setUp() self.config.no_verify_ssl = False self.config.allow_subset_of_names = False # pylint: disable=star-args self.account = mock.MagicMock(**{"key.pem": KEY}) from certbot.client import Client with mock.patch("certbot.client.acme_client.BackwardsCompatibleClientV2") as acme: self.acme_client = acme self.acme = acme.return_value = mock.MagicMock() self.client = Client( config=self.config, account_=self.account, auth=None, installer=None) class ClientTest(ClientTestCommon): """Tests for certbot.client.Client.""" def setUp(self): super(ClientTest, self).setUp() self.config.allow_subset_of_names = False self.config.dry_run = False self.eg_domains = ["example.com", "www.example.com"] self.eg_order = mock.MagicMock( authorizations=[None], csr_pem=mock.sentinel.csr_pem) def test_init_acme_verify_ssl(self): net = self.acme_client.call_args[0][0] self.assertTrue(net.verify_ssl) def _mock_obtain_certificate(self): self.client.auth_handler = mock.MagicMock() self.client.auth_handler.handle_authorizations.return_value = [None] self.acme.finalize_order.return_value = self.eg_order self.acme.new_order.return_value = self.eg_order self.eg_order.update.return_value = self.eg_order def _check_obtain_certificate(self, auth_count=1): if auth_count == 1: self.client.auth_handler.handle_authorizations.assert_called_once_with( self.eg_order, self.config.allow_subset_of_names) else: self.assertEqual(self.client.auth_handler.handle_authorizations.call_count, auth_count) self.acme.finalize_order.assert_called_once_with( self.eg_order, mock.ANY) @mock.patch("certbot.client.crypto_util") @mock.patch("certbot.client.logger") @test_util.patch_get_utility() def test_obtain_certificate_from_csr(self, unused_mock_get_utility, mock_logger, mock_crypto_util): self._mock_obtain_certificate() test_csr = util.CSR(form="pem", file=None, data=CSR_SAN) auth_handler = self.client.auth_handler self._set_mock_from_fullchain(mock_crypto_util.cert_and_chain_from_fullchain) orderr = self.acme.new_order(test_csr.data) auth_handler.handle_authorizations(orderr, False) self.assertEqual( (mock.sentinel.cert, mock.sentinel.chain), self.client.obtain_certificate_from_csr( test_csr, orderr=orderr)) # and that the cert was obtained correctly self._check_obtain_certificate() # Test for orderr=None self.assertEqual( (mock.sentinel.cert, mock.sentinel.chain), self.client.obtain_certificate_from_csr( test_csr, orderr=None)) auth_handler.handle_authorizations.assert_called_with(self.eg_order, False) # Test for no auth_handler self.client.auth_handler = None self.assertRaises( errors.Error, self.client.obtain_certificate_from_csr, test_csr) mock_logger.warning.assert_called_once_with(mock.ANY) @mock.patch("certbot.client.crypto_util") def test_obtain_certificate(self, mock_crypto_util): csr = util.CSR(form="pem", file=None, data=CSR_SAN) mock_crypto_util.init_save_csr.return_value = csr mock_crypto_util.init_save_key.return_value = mock.sentinel.key self._set_mock_from_fullchain(mock_crypto_util.cert_and_chain_from_fullchain) self._test_obtain_certificate_common(mock.sentinel.key, csr) mock_crypto_util.init_save_key.assert_called_once_with( self.config.rsa_key_size, self.config.key_dir) mock_crypto_util.init_save_csr.assert_called_once_with( mock.sentinel.key, self.eg_domains, self.config.csr_dir) mock_crypto_util.cert_and_chain_from_fullchain.assert_called_once_with( self.eg_order.fullchain_pem) @mock.patch("certbot.client.crypto_util") @mock.patch("os.remove") def test_obtain_certificate_partial_success(self, mock_remove, mock_crypto_util): csr = util.CSR(form="pem", file=mock.sentinel.csr_file, data=CSR_SAN) key = util.CSR(form="pem", file=mock.sentinel.key_file, data=CSR_SAN) mock_crypto_util.init_save_csr.return_value = csr mock_crypto_util.init_save_key.return_value = key self._set_mock_from_fullchain(mock_crypto_util.cert_and_chain_from_fullchain) authzr = self._authzr_from_domains(["example.com"]) self.config.allow_subset_of_names = True self._test_obtain_certificate_common(key, csr, authzr_ret=authzr, auth_count=2) self.assertEqual(mock_crypto_util.init_save_key.call_count, 2) self.assertEqual(mock_crypto_util.init_save_csr.call_count, 2) self.assertEqual(mock_remove.call_count, 2) self.assertEqual(mock_crypto_util.cert_and_chain_from_fullchain.call_count, 1) @mock.patch("certbot.client.crypto_util") @mock.patch("certbot.client.acme_crypto_util") def test_obtain_certificate_dry_run(self, mock_acme_crypto, mock_crypto): csr = util.CSR(form="pem", file=None, data=CSR_SAN) mock_acme_crypto.make_csr.return_value = CSR_SAN mock_crypto.make_key.return_value = mock.sentinel.key_pem key = util.Key(file=None, pem=mock.sentinel.key_pem) self._set_mock_from_fullchain(mock_crypto.cert_and_chain_from_fullchain) self.client.config.dry_run = True self._test_obtain_certificate_common(key, csr) mock_crypto.make_key.assert_called_once_with(self.config.rsa_key_size) mock_acme_crypto.make_csr.assert_called_once_with( mock.sentinel.key_pem, self.eg_domains, self.config.must_staple) mock_crypto.init_save_key.assert_not_called() mock_crypto.init_save_csr.assert_not_called() self.assertEqual(mock_crypto.cert_and_chain_from_fullchain.call_count, 1) def _set_mock_from_fullchain(self, mock_from_fullchain): mock_cert = mock.Mock() mock_cert.encode.return_value = mock.sentinel.cert mock_chain = mock.Mock() mock_chain.encode.return_value = mock.sentinel.chain mock_from_fullchain.return_value = (mock_cert, mock_chain) def _authzr_from_domains(self, domains): authzr = [] # domain ordering should not be affected by authorization order for domain in reversed(domains): authzr.append( mock.MagicMock( body=mock.MagicMock( identifier=mock.MagicMock( value=domain)))) return authzr def _test_obtain_certificate_common(self, key, csr, authzr_ret=None, auth_count=1): self._mock_obtain_certificate() # return_value is essentially set to (None, None) in # _mock_obtain_certificate(), which breaks this test. # Thus fixed by the next line. authzr = authzr_ret or self._authzr_from_domains(self.eg_domains) self.eg_order.authorizations = authzr self.client.auth_handler.handle_authorizations.return_value = authzr with test_util.patch_get_utility(): result = self.client.obtain_certificate(self.eg_domains) self.assertEqual( result, (mock.sentinel.cert, mock.sentinel.chain, key, csr)) self._check_obtain_certificate(auth_count) @mock.patch('certbot.client.Client.obtain_certificate') @mock.patch('certbot.storage.RenewableCert.new_lineage') def test_obtain_and_enroll_certificate(self, mock_storage, mock_obtain_certificate): domains = ["*.example.com", "example.com"] mock_obtain_certificate.return_value = (mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), None) self.client.config.dry_run = False self.assertTrue(self.client.obtain_and_enroll_certificate(domains, "example_cert")) self.assertTrue(self.client.obtain_and_enroll_certificate(domains, None)) self.assertTrue(self.client.obtain_and_enroll_certificate(domains[1:], None)) self.client.config.dry_run = True self.assertFalse(self.client.obtain_and_enroll_certificate(domains, None)) names = [call[0][0] for call in mock_storage.call_args_list] self.assertEqual(names, ["example_cert", "example.com", "example.com"]) @mock.patch("certbot.cli.helpful_parser") def test_save_certificate(self, mock_parser): # pylint: disable=too-many-locals certs = ["cert_512.pem", "cert-san_512.pem"] tmp_path = tempfile.mkdtemp() os.chmod(tmp_path, 0o755) # TODO: really?? cert_pem = test_util.load_vector(certs[0]) chain_pem = (test_util.load_vector(certs[0]) + test_util.load_vector(certs[1])) candidate_cert_path = os.path.join(tmp_path, "certs", "cert_512.pem") candidate_chain_path = os.path.join(tmp_path, "chains", "chain.pem") candidate_fullchain_path = os.path.join(tmp_path, "chains", "fullchain.pem") mock_parser.verb = "certonly" mock_parser.args = ["--cert-path", candidate_cert_path, "--chain-path", candidate_chain_path, "--fullchain-path", candidate_fullchain_path] cert_path, chain_path, fullchain_path = self.client.save_certificate( cert_pem, chain_pem, candidate_cert_path, candidate_chain_path, candidate_fullchain_path) self.assertEqual(os.path.dirname(cert_path), os.path.dirname(candidate_cert_path)) self.assertEqual(os.path.dirname(chain_path), os.path.dirname(candidate_chain_path)) self.assertEqual(os.path.dirname(fullchain_path), os.path.dirname(candidate_fullchain_path)) with open(cert_path, "rb") as cert_file: cert_contents = cert_file.read() self.assertEqual(cert_contents, test_util.load_vector(certs[0])) with open(chain_path, "rb") as chain_file: chain_contents = chain_file.read() self.assertEqual(chain_contents, test_util.load_vector(certs[0]) + test_util.load_vector(certs[1])) shutil.rmtree(tmp_path) def test_deploy_certificate_success(self): self.assertRaises(errors.Error, self.client.deploy_certificate, ["foo.bar"], "key", "cert", "chain", "fullchain") installer = mock.MagicMock() self.client.installer = installer self.client.deploy_certificate( ["foo.bar"], "key", "cert", "chain", "fullchain") installer.deploy_cert.assert_called_once_with( cert_path=os.path.abspath("cert"), chain_path=os.path.abspath("chain"), domain='foo.bar', fullchain_path='fullchain', key_path=os.path.abspath("key")) self.assertEqual(installer.save.call_count, 2) installer.restart.assert_called_once_with() def test_deploy_certificate_failure(self): installer = mock.MagicMock() self.client.installer = installer installer.deploy_cert.side_effect = errors.PluginError self.assertRaises(errors.PluginError, self.client.deploy_certificate, ["foo.bar"], "key", "cert", "chain", "fullchain") installer.recovery_routine.assert_called_once_with() def test_deploy_certificate_save_failure(self): installer = mock.MagicMock() self.client.installer = installer installer.save.side_effect = errors.PluginError self.assertRaises(errors.PluginError, self.client.deploy_certificate, ["foo.bar"], "key", "cert", "chain", "fullchain") installer.recovery_routine.assert_called_once_with() @test_util.patch_get_utility() def test_deploy_certificate_restart_failure(self, mock_get_utility): installer = mock.MagicMock() installer.restart.side_effect = [errors.PluginError, None] self.client.installer = installer self.assertRaises(errors.PluginError, self.client.deploy_certificate, ["foo.bar"], "key", "cert", "chain", "fullchain") self.assertEqual(mock_get_utility().add_message.call_count, 1) installer.rollback_checkpoints.assert_called_once_with() self.assertEqual(installer.restart.call_count, 2) @test_util.patch_get_utility() def test_deploy_certificate_restart_failure2(self, mock_get_utility): installer = mock.MagicMock() installer.restart.side_effect = errors.PluginError installer.rollback_checkpoints.side_effect = errors.ReverterError self.client.installer = installer self.assertRaises(errors.PluginError, self.client.deploy_certificate, ["foo.bar"], "key", "cert", "chain", "fullchain") self.assertEqual(mock_get_utility().add_message.call_count, 1) installer.rollback_checkpoints.assert_called_once_with() self.assertEqual(installer.restart.call_count, 1) class EnhanceConfigTest(ClientTestCommon): """Tests for certbot.client.Client.enhance_config.""" def setUp(self): super(EnhanceConfigTest, self).setUp() self.config.hsts = False self.config.redirect = False self.config.staple = False self.config.uir = False self.domain = "example.org" def test_no_installer(self): self.assertRaises( errors.Error, self.client.enhance_config, [self.domain], None) @mock.patch("certbot.client.enhancements") def test_unsupported(self, mock_enhancements): self.client.installer = mock.MagicMock() self.client.installer.supported_enhancements.return_value = [] self.config.redirect = None self.config.hsts = True with mock.patch("certbot.client.logger") as mock_logger: self.client.enhance_config([self.domain], None) self.assertEqual(mock_logger.warning.call_count, 1) self.client.installer.enhance.assert_not_called() mock_enhancements.ask.assert_not_called() @mock.patch("certbot.client.logger") def test_already_exists_header(self, mock_log): self.config.hsts = True self._test_with_already_existing() self.assertTrue(mock_log.warning.called) self.assertEquals(mock_log.warning.call_args[0][1], 'Strict-Transport-Security') @mock.patch("certbot.client.logger") def test_already_exists_redirect(self, mock_log): self.config.redirect = True self._test_with_already_existing() self.assertTrue(mock_log.warning.called) self.assertEquals(mock_log.warning.call_args[0][1], 'redirect') def test_no_ask_hsts(self): self.config.hsts = True self._test_with_all_supported() self.client.installer.enhance.assert_called_with( self.domain, "ensure-http-header", "Strict-Transport-Security") def test_no_ask_redirect(self): self.config.redirect = True self._test_with_all_supported() self.client.installer.enhance.assert_called_with( self.domain, "redirect", None) def test_no_ask_staple(self): self.config.staple = True self._test_with_all_supported() self.client.installer.enhance.assert_called_with( self.domain, "staple-ocsp", None) def test_no_ask_uir(self): self.config.uir = True self._test_with_all_supported() self.client.installer.enhance.assert_called_with( self.domain, "ensure-http-header", "Upgrade-Insecure-Requests") def test_enhance_failure(self): self.client.installer = mock.MagicMock() self.client.installer.enhance.side_effect = errors.PluginError self._test_error() self.client.installer.recovery_routine.assert_called_once_with() def test_save_failure(self): self.client.installer = mock.MagicMock() self.client.installer.save.side_effect = errors.PluginError self._test_error() self.client.installer.recovery_routine.assert_called_once_with() self.client.installer.save.assert_called_once_with(mock.ANY) def test_restart_failure(self): self.client.installer = mock.MagicMock() self.client.installer.restart.side_effect = [errors.PluginError, None] self._test_error_with_rollback() def test_restart_failure2(self): installer = mock.MagicMock() installer.restart.side_effect = errors.PluginError installer.rollback_checkpoints.side_effect = errors.ReverterError self.client.installer = installer self._test_error_with_rollback() @mock.patch("certbot.client.enhancements.ask") def test_ask(self, mock_ask): self.config.redirect = None mock_ask.return_value = True self._test_with_all_supported() def _test_error_with_rollback(self): self._test_error() self.assertTrue(self.client.installer.restart.called) def _test_error(self): self.config.redirect = True with test_util.patch_get_utility() as mock_gu: self.assertRaises( errors.PluginError, self._test_with_all_supported) self.assertEqual(mock_gu().add_message.call_count, 1) def _test_with_all_supported(self): if self.client.installer is None: self.client.installer = mock.MagicMock() self.client.installer.supported_enhancements.return_value = [ "ensure-http-header", "redirect", "staple-ocsp"] self.client.enhance_config([self.domain], None) self.assertEqual(self.client.installer.save.call_count, 1) self.assertEqual(self.client.installer.restart.call_count, 1) def _test_with_already_existing(self): self.client.installer = mock.MagicMock() self.client.installer.supported_enhancements.return_value = [ "ensure-http-header", "redirect", "staple-ocsp"] self.client.installer.enhance.side_effect = errors.PluginEnhancementAlreadyPresent() self.client.enhance_config([self.domain], None) class RollbackTest(unittest.TestCase): """Tests for certbot.client.rollback.""" def setUp(self): self.m_install = mock.MagicMock() @classmethod def _call(cls, checkpoints, side_effect): from certbot.client import rollback with mock.patch("certbot.client.plugin_selection.pick_installer") as mpi: mpi.side_effect = side_effect rollback(None, checkpoints, {}, mock.MagicMock()) def test_no_problems(self): self._call(1, self.m_install) self.assertEqual(self.m_install().rollback_checkpoints.call_count, 1) self.assertEqual(self.m_install().restart.call_count, 1) def test_no_installer(self): self._call(1, None) # Just make sure no exceptions are raised if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/cert_manager_test.py0000644000175000017500000007003713344054434022311 0ustar ericaerica00000000000000 """Tests for certbot.cert_manager.""" # pylint: disable=protected-access import os import re import shutil import tempfile import unittest import configobj import mock from certbot import configuration from certbot import errors from certbot.display import util as display_util from certbot.storage import ALL_FOUR from certbot.tests import storage_test from certbot.tests import util as test_util class BaseCertManagerTest(test_util.ConfigTestCase): """Base class for setting up Cert Manager tests. """ def setUp(self): super(BaseCertManagerTest, self).setUp() self.config.quiet = False os.makedirs(self.config.renewal_configs_dir) self.domains = { "example.org": None, "other.com": os.path.join(self.config.config_dir, "specialarchive") } self.config_files = dict((domain, self._set_up_config(domain, self.domains[domain])) for domain in self.domains) # We also create a file that isn't a renewal config in the same # location to test that logic that reads in all-and-only renewal # configs will ignore it and NOT attempt to parse it. junk = open(os.path.join(self.config.renewal_configs_dir, "IGNORE.THIS"), "w") junk.write("This file should be ignored!") junk.close() def _set_up_config(self, domain, custom_archive): # TODO: maybe provide NamespaceConfig.make_dirs? # TODO: main() should create those dirs, c.f. #902 os.makedirs(os.path.join(self.config.live_dir, domain)) config_file = configobj.ConfigObj() if custom_archive is not None: os.makedirs(custom_archive) config_file["archive_dir"] = custom_archive else: os.makedirs(os.path.join(self.config.default_archive_dir, domain)) for kind in ALL_FOUR: config_file[kind] = os.path.join(self.config.live_dir, domain, kind + ".pem") config_file.filename = os.path.join(self.config.renewal_configs_dir, domain + ".conf") config_file.write() return config_file class UpdateLiveSymlinksTest(BaseCertManagerTest): """Tests for certbot.cert_manager.update_live_symlinks """ def test_update_live_symlinks(self): """Test update_live_symlinks""" # pylint: disable=too-many-statements # create files with incorrect symlinks from certbot import cert_manager archive_paths = {} for domain in self.domains: custom_archive = self.domains[domain] if custom_archive is not None: archive_dir_path = custom_archive else: archive_dir_path = os.path.join(self.config.default_archive_dir, domain) archive_paths[domain] = dict((kind, os.path.join(archive_dir_path, kind + "1.pem")) for kind in ALL_FOUR) for kind in ALL_FOUR: live_path = self.config_files[domain][kind] archive_path = archive_paths[domain][kind] open(archive_path, 'a').close() # path is incorrect but base must be correct os.symlink(os.path.join(self.config.config_dir, kind + "1.pem"), live_path) # run update symlinks cert_manager.update_live_symlinks(self.config) # check that symlinks go where they should prev_dir = os.getcwd() try: for domain in self.domains: for kind in ALL_FOUR: os.chdir(os.path.dirname(self.config_files[domain][kind])) self.assertEqual( os.path.realpath(os.readlink(self.config_files[domain][kind])), os.path.realpath(archive_paths[domain][kind])) finally: os.chdir(prev_dir) class DeleteTest(storage_test.BaseRenewableCertTest): """Tests for certbot.cert_manager.delete """ def _call(self): from certbot import cert_manager cert_manager.delete(self.config) @test_util.patch_get_utility() @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.storage.delete_files') def test_delete_from_config(self, mock_delete_files, mock_lineage_for_certname, unused_get_utility): """Test delete""" mock_lineage_for_certname.return_value = self.test_rc self.config.certname = "example.org" self._call() mock_delete_files.assert_called_once_with(self.config, "example.org") @test_util.patch_get_utility() @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.storage.delete_files') def test_delete_interactive_single(self, mock_delete_files, mock_lineage_for_certname, mock_util): """Test delete""" mock_lineage_for_certname.return_value = self.test_rc mock_util().checklist.return_value = (display_util.OK, ["example.org"]) self._call() mock_delete_files.assert_called_once_with(self.config, "example.org") @test_util.patch_get_utility() @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.storage.delete_files') def test_delete_interactive_multiple(self, mock_delete_files, mock_lineage_for_certname, mock_util): """Test delete""" mock_lineage_for_certname.return_value = self.test_rc mock_util().checklist.return_value = (display_util.OK, ["example.org", "other.org"]) self._call() mock_delete_files.assert_any_call(self.config, "example.org") mock_delete_files.assert_any_call(self.config, "other.org") self.assertEqual(mock_delete_files.call_count, 2) class CertificatesTest(BaseCertManagerTest): """Tests for certbot.cert_manager.certificates """ def _certificates(self, *args, **kwargs): from certbot.cert_manager import certificates return certificates(*args, **kwargs) @mock.patch('certbot.cert_manager.logger') @test_util.patch_get_utility() def test_certificates_parse_fail(self, mock_utility, mock_logger): self._certificates(self.config) self.assertTrue(mock_logger.warning.called) #pylint: disable=no-member self.assertTrue(mock_utility.called) @mock.patch('certbot.cert_manager.logger') @test_util.patch_get_utility() def test_certificates_quiet(self, mock_utility, mock_logger): self.config.quiet = True self._certificates(self.config) self.assertFalse(mock_utility.notification.called) self.assertTrue(mock_logger.warning.called) #pylint: disable=no-member @mock.patch('certbot.crypto_util.verify_renewable_cert') @mock.patch('certbot.cert_manager.logger') @test_util.patch_get_utility() @mock.patch("certbot.storage.RenewableCert") @mock.patch('certbot.cert_manager._report_human_readable') def test_certificates_parse_success(self, mock_report, mock_renewable_cert, mock_utility, mock_logger, mock_verifier): mock_verifier.return_value = None mock_report.return_value = "" self._certificates(self.config) self.assertFalse(mock_logger.warning.called) #pylint: disable=no-member self.assertTrue(mock_report.called) self.assertTrue(mock_utility.called) self.assertTrue(mock_renewable_cert.called) @mock.patch('certbot.cert_manager.logger') @test_util.patch_get_utility() def test_certificates_no_files(self, mock_utility, mock_logger): empty_tempdir = tempfile.mkdtemp() empty_config = configuration.NamespaceConfig(mock.MagicMock( config_dir=os.path.join(empty_tempdir, "config"), work_dir=os.path.join(empty_tempdir, "work"), logs_dir=os.path.join(empty_tempdir, "logs"), quiet=False )) os.makedirs(empty_config.renewal_configs_dir) self._certificates(empty_config) self.assertFalse(mock_logger.warning.called) #pylint: disable=no-member self.assertTrue(mock_utility.called) shutil.rmtree(empty_tempdir) @mock.patch('certbot.cert_manager.ocsp.RevocationChecker.ocsp_revoked') def test_report_human_readable(self, mock_revoked): mock_revoked.return_value = None from certbot import cert_manager import datetime, pytz expiry = pytz.UTC.fromutc(datetime.datetime.utcnow()) cert = mock.MagicMock(lineagename="nameone") cert.target_expiry = expiry cert.names.return_value = ["nameone", "nametwo"] cert.is_test_cert = False parsed_certs = [cert] mock_config = mock.MagicMock(certname=None, lineagename=None) # pylint: disable=protected-access # pylint: disable=protected-access get_report = lambda: cert_manager._report_human_readable(mock_config, parsed_certs) out = get_report() self.assertTrue("INVALID: EXPIRED" in out) cert.target_expiry += datetime.timedelta(hours=2) # pylint: disable=protected-access out = get_report() self.assertTrue('1 hour(s)' in out) self.assertTrue('VALID' in out and not 'INVALID' in out) cert.target_expiry += datetime.timedelta(days=1) # pylint: disable=protected-access out = get_report() self.assertTrue('1 day' in out) self.assertFalse('under' in out) self.assertTrue('VALID' in out and not 'INVALID' in out) cert.target_expiry += datetime.timedelta(days=2) # pylint: disable=protected-access out = get_report() self.assertTrue('3 days' in out) self.assertTrue('VALID' in out and not 'INVALID' in out) cert.is_test_cert = True mock_revoked.return_value = True out = get_report() self.assertTrue('INVALID: TEST_CERT, REVOKED' in out) cert = mock.MagicMock(lineagename="indescribable") cert.target_expiry = expiry cert.names.return_value = ["nameone", "thrice.named"] cert.is_test_cert = True parsed_certs.append(cert) out = get_report() self.assertEqual(len(re.findall("INVALID:", out)), 2) mock_config.domains = ["thrice.named"] out = get_report() self.assertEqual(len(re.findall("INVALID:", out)), 1) mock_config.domains = ["nameone"] out = get_report() self.assertEqual(len(re.findall("INVALID:", out)), 2) mock_config.certname = "indescribable" out = get_report() self.assertEqual(len(re.findall("INVALID:", out)), 1) mock_config.certname = "horror" out = get_report() self.assertEqual(len(re.findall("INVALID:", out)), 0) class SearchLineagesTest(BaseCertManagerTest): """Tests for certbot.cert_manager._search_lineages.""" @mock.patch('certbot.util.make_or_verify_dir') @mock.patch('certbot.storage.renewal_conf_files') @mock.patch('certbot.storage.RenewableCert') def test_cert_storage_error(self, mock_renewable_cert, mock_renewal_conf_files, mock_make_or_verify_dir): mock_renewal_conf_files.return_value = ["badfile"] mock_renewable_cert.side_effect = errors.CertStorageError from certbot import cert_manager # pylint: disable=protected-access self.assertEqual(cert_manager._search_lineages(self.config, lambda x: x, "check"), "check") self.assertTrue(mock_make_or_verify_dir.called) class LineageForCertnameTest(BaseCertManagerTest): """Tests for certbot.cert_manager.lineage_for_certname""" @mock.patch('certbot.util.make_or_verify_dir') @mock.patch('certbot.storage.renewal_file_for_certname') @mock.patch('certbot.storage.RenewableCert') def test_found_match(self, mock_renewable_cert, mock_renewal_conf_file, mock_make_or_verify_dir): mock_renewal_conf_file.return_value = "somefile.conf" mock_match = mock.Mock(lineagename="example.com") mock_renewable_cert.return_value = mock_match from certbot import cert_manager self.assertEqual(cert_manager.lineage_for_certname(self.config, "example.com"), mock_match) self.assertTrue(mock_make_or_verify_dir.called) @mock.patch('certbot.util.make_or_verify_dir') @mock.patch('certbot.storage.renewal_file_for_certname') def test_no_match(self, mock_renewal_conf_file, mock_make_or_verify_dir): mock_renewal_conf_file.return_value = "other.com.conf" from certbot import cert_manager self.assertEqual(cert_manager.lineage_for_certname(self.config, "example.com"), None) self.assertTrue(mock_make_or_verify_dir.called) @mock.patch('certbot.util.make_or_verify_dir') @mock.patch('certbot.storage.renewal_file_for_certname') def test_no_renewal_file(self, mock_renewal_conf_file, mock_make_or_verify_dir): mock_renewal_conf_file.side_effect = errors.CertStorageError() from certbot import cert_manager self.assertEqual(cert_manager.lineage_for_certname(self.config, "example.com"), None) self.assertTrue(mock_make_or_verify_dir.called) class DomainsForCertnameTest(BaseCertManagerTest): """Tests for certbot.cert_manager.domains_for_certname""" @mock.patch('certbot.util.make_or_verify_dir') @mock.patch('certbot.storage.renewal_file_for_certname') @mock.patch('certbot.storage.RenewableCert') def test_found_match(self, mock_renewable_cert, mock_renewal_conf_file, mock_make_or_verify_dir): mock_renewal_conf_file.return_value = "somefile.conf" mock_match = mock.Mock(lineagename="example.com") domains = ["example.com", "example.org"] mock_match.names.return_value = domains mock_renewable_cert.return_value = mock_match from certbot import cert_manager self.assertEqual(cert_manager.domains_for_certname(self.config, "example.com"), domains) self.assertTrue(mock_make_or_verify_dir.called) @mock.patch('certbot.util.make_or_verify_dir') @mock.patch('certbot.storage.renewal_file_for_certname') def test_no_match(self, mock_renewal_conf_file, mock_make_or_verify_dir): mock_renewal_conf_file.return_value = "somefile.conf" from certbot import cert_manager self.assertEqual(cert_manager.domains_for_certname(self.config, "other.com"), None) self.assertTrue(mock_make_or_verify_dir.called) class RenameLineageTest(BaseCertManagerTest): """Tests for certbot.cert_manager.rename_lineage""" def setUp(self): super(RenameLineageTest, self).setUp() self.config.certname = "example.org" self.config.new_certname = "after" def _call(self, *args, **kwargs): from certbot import cert_manager return cert_manager.rename_lineage(*args, **kwargs) @mock.patch('certbot.storage.renewal_conf_files') @test_util.patch_get_utility() def test_no_certname(self, mock_get_utility, mock_renewal_conf_files): self.config.certname = None self.config.new_certname = "two" # if not choices mock_renewal_conf_files.return_value = [] self.assertRaises(errors.Error, self._call, self.config) mock_renewal_conf_files.return_value = ["one.conf"] util_mock = mock_get_utility() util_mock.menu.return_value = (display_util.CANCEL, 0) self.assertRaises(errors.Error, self._call, self.config) util_mock.menu.return_value = (display_util.OK, -1) self.assertRaises(errors.Error, self._call, self.config) @test_util.patch_get_utility() def test_no_new_certname(self, mock_get_utility): self.config.certname = "one" self.config.new_certname = None util_mock = mock_get_utility() util_mock.input.return_value = (display_util.CANCEL, "name") self.assertRaises(errors.Error, self._call, self.config) util_mock.input.return_value = (display_util.OK, None) self.assertRaises(errors.Error, self._call, self.config) @test_util.patch_get_utility() @mock.patch('certbot.cert_manager.lineage_for_certname') def test_no_existing_certname(self, mock_lineage_for_certname, unused_get_utility): self.config.certname = "one" self.config.new_certname = "two" mock_lineage_for_certname.return_value = None self.assertRaises(errors.ConfigurationError, self._call, self.config) @test_util.patch_get_utility() @mock.patch("certbot.storage.RenewableCert._check_symlinks") def test_rename_cert(self, mock_check, unused_get_utility): mock_check.return_value = True self._call(self.config) from certbot import cert_manager updated_lineage = cert_manager.lineage_for_certname(self.config, self.config.new_certname) self.assertTrue(updated_lineage is not None) self.assertEqual(updated_lineage.lineagename, self.config.new_certname) @test_util.patch_get_utility() @mock.patch("certbot.storage.RenewableCert._check_symlinks") def test_rename_cert_interactive_certname(self, mock_check, mock_get_utility): mock_check.return_value = True self.config.certname = None util_mock = mock_get_utility() util_mock.menu.return_value = (display_util.OK, 0) self._call(self.config) from certbot import cert_manager updated_lineage = cert_manager.lineage_for_certname(self.config, self.config.new_certname) self.assertTrue(updated_lineage is not None) self.assertEqual(updated_lineage.lineagename, self.config.new_certname) @test_util.patch_get_utility() @mock.patch("certbot.storage.RenewableCert._check_symlinks") def test_rename_cert_bad_new_certname(self, mock_check, unused_get_utility): mock_check.return_value = True # for example, don't rename to existing certname self.config.new_certname = "example.org" self.assertRaises(errors.ConfigurationError, self._call, self.config) self.config.new_certname = "one{0}two".format(os.path.sep) self.assertRaises(errors.ConfigurationError, self._call, self.config) class DuplicativeCertsTest(storage_test.BaseRenewableCertTest): """Test to avoid duplicate lineages.""" def setUp(self): super(DuplicativeCertsTest, self).setUp() self.config_file.write() self._write_out_ex_kinds() @mock.patch('certbot.util.make_or_verify_dir') def test_find_duplicative_names(self, unused_makedir): from certbot.cert_manager import find_duplicative_certs test_cert = test_util.load_vector('cert-san_512.pem') with open(self.test_rc.cert, 'wb') as f: f.write(test_cert) # No overlap at all result = find_duplicative_certs( self.config, ['wow.net', 'hooray.org']) self.assertEqual(result, (None, None)) # Totally identical result = find_duplicative_certs( self.config, ['example.com', 'www.example.com']) self.assertTrue(result[0].configfile.filename.endswith('example.org.conf')) self.assertEqual(result[1], None) # Superset result = find_duplicative_certs( self.config, ['example.com', 'www.example.com', 'something.new']) self.assertEqual(result[0], None) self.assertTrue(result[1].configfile.filename.endswith('example.org.conf')) # Partial overlap doesn't count result = find_duplicative_certs( self.config, ['example.com', 'something.new']) self.assertEqual(result, (None, None)) class CertPathToLineageTest(storage_test.BaseRenewableCertTest): """Tests for certbot.cert_manager.cert_path_to_lineage""" def setUp(self): super(CertPathToLineageTest, self).setUp() self.config_file.write() self._write_out_ex_kinds() self.fullchain = os.path.join(self.config.config_dir, 'live', 'example.org', 'fullchain.pem') self.config.cert_path = (self.fullchain, '') def _call(self, cli_config): from certbot.cert_manager import cert_path_to_lineage return cert_path_to_lineage(cli_config) def _archive_files(self, cli_config, filetype): from certbot.cert_manager import _archive_files return _archive_files(cli_config, filetype) def test_basic_match(self): self.assertEqual('example.org', self._call(self.config)) def test_no_match_exists(self): bad_test_config = self.config bad_test_config.cert_path = os.path.join(self.config.config_dir, 'live', 'SailorMoon', 'fullchain.pem') self.assertRaises(errors.Error, self._call, bad_test_config) @mock.patch('certbot.cert_manager._acceptable_matches') def test_options_fullchain(self, mock_acceptable_matches): mock_acceptable_matches.return_value = [lambda x: x.fullchain_path] self.config.fullchain_path = self.fullchain self.assertEqual('example.org', self._call(self.config)) @mock.patch('certbot.cert_manager._acceptable_matches') def test_options_cert_path(self, mock_acceptable_matches): mock_acceptable_matches.return_value = [lambda x: x.cert_path] test_cert_path = os.path.join(self.config.config_dir, 'live', 'example.org', 'cert.pem') self.config.cert_path = (test_cert_path, '') self.assertEqual('example.org', self._call(self.config)) @mock.patch('certbot.cert_manager._acceptable_matches') def test_options_archive_cert(self, mock_acceptable_matches): # Also this and the next test check that the regex of _archive_files is working. self.config.cert_path = (os.path.join(self.config.config_dir, 'archive', 'example.org', 'cert11.pem'), '') mock_acceptable_matches.return_value = [lambda x: self._archive_files(x, 'cert')] self.assertEqual('example.org', self._call(self.config)) @mock.patch('certbot.cert_manager._acceptable_matches') def test_options_archive_fullchain(self, mock_acceptable_matches): self.config.cert_path = (os.path.join(self.config.config_dir, 'archive', 'example.org', 'fullchain11.pem'), '') mock_acceptable_matches.return_value = [lambda x: self._archive_files(x, 'fullchain')] self.assertEqual('example.org', self._call(self.config)) class MatchAndCheckOverlaps(storage_test.BaseRenewableCertTest): """Tests for certbot.cert_manager.match_and_check_overlaps w/o overlapping archive dirs.""" # A test with real overlapping archive dirs can be found in tests/boulder_integration.sh def setUp(self): super(MatchAndCheckOverlaps, self).setUp() self.config_file.write() self._write_out_ex_kinds() self.fullchain = os.path.join(self.config.config_dir, 'live', 'example.org', 'fullchain.pem') self.config.cert_path = (self.fullchain, '') def _call(self, cli_config, acceptable_matches, match_func, rv_func): from certbot.cert_manager import match_and_check_overlaps return match_and_check_overlaps(cli_config, acceptable_matches, match_func, rv_func) def test_basic_match(self): from certbot.cert_manager import _acceptable_matches self.assertEqual(['example.org'], self._call(self.config, _acceptable_matches(), lambda x: self.config.cert_path[0], lambda x: x.lineagename)) @mock.patch('certbot.cert_manager._search_lineages') def test_no_matches(self, mock_search_lineages): mock_search_lineages.return_value = [] self.assertRaises(errors.Error, self._call, self.config, None, None, None) @mock.patch('certbot.cert_manager._search_lineages') def test_too_many_matches(self, mock_search_lineages): mock_search_lineages.return_value = ['spider', 'dance'] self.assertRaises(errors.OverlappingMatchFound, self._call, self.config, None, None, None) class GetCertnameTest(unittest.TestCase): """Tests for certbot.cert_manager.""" def setUp(self): self.get_utility_patch = test_util.patch_get_utility() self.mock_get_utility = self.get_utility_patch.start() self.config = mock.MagicMock() self.config.certname = None def tearDown(self): self.get_utility_patch.stop() @mock.patch('certbot.storage.renewal_conf_files') @mock.patch('certbot.storage.lineagename_for_filename') def test_get_certnames(self, mock_name, mock_files): mock_files.return_value = ['example.com.conf'] mock_name.return_value = 'example.com' from certbot import cert_manager prompt = "Which certificate would you" self.mock_get_utility().menu.return_value = (display_util.OK, 0) self.assertEquals( cert_manager.get_certnames( self.config, "verb", allow_multiple=False), ['example.com']) self.assertTrue( prompt in self.mock_get_utility().menu.call_args[0][0]) @mock.patch('certbot.storage.renewal_conf_files') @mock.patch('certbot.storage.lineagename_for_filename') def test_get_certnames_custom_prompt(self, mock_name, mock_files): mock_files.return_value = ['example.com.conf'] mock_name.return_value = 'example.com' from certbot import cert_manager prompt = "custom prompt" self.mock_get_utility().menu.return_value = (display_util.OK, 0) self.assertEquals( cert_manager.get_certnames( self.config, "verb", allow_multiple=False, custom_prompt=prompt), ['example.com']) self.assertEquals(self.mock_get_utility().menu.call_args[0][0], prompt) @mock.patch('certbot.storage.renewal_conf_files') @mock.patch('certbot.storage.lineagename_for_filename') def test_get_certnames_user_abort(self, mock_name, mock_files): mock_files.return_value = ['example.com.conf'] mock_name.return_value = 'example.com' from certbot import cert_manager self.mock_get_utility().menu.return_value = (display_util.CANCEL, 0) self.assertRaises( errors.Error, cert_manager.get_certnames, self.config, "erroring_anyway", allow_multiple=False) @mock.patch('certbot.storage.renewal_conf_files') @mock.patch('certbot.storage.lineagename_for_filename') def test_get_certnames_allow_multiple(self, mock_name, mock_files): mock_files.return_value = ['example.com.conf'] mock_name.return_value = 'example.com' from certbot import cert_manager prompt = "Which certificate(s) would you" self.mock_get_utility().checklist.return_value = (display_util.OK, ['example.com']) self.assertEquals( cert_manager.get_certnames( self.config, "verb", allow_multiple=True), ['example.com']) self.assertTrue( prompt in self.mock_get_utility().checklist.call_args[0][0]) @mock.patch('certbot.storage.renewal_conf_files') @mock.patch('certbot.storage.lineagename_for_filename') def test_get_certnames_allow_multiple_custom_prompt(self, mock_name, mock_files): mock_files.return_value = ['example.com.conf'] mock_name.return_value = 'example.com' from certbot import cert_manager prompt = "custom prompt" self.mock_get_utility().checklist.return_value = (display_util.OK, ['example.com']) self.assertEquals( cert_manager.get_certnames( self.config, "verb", allow_multiple=True, custom_prompt=prompt), ['example.com']) self.assertEquals( self.mock_get_utility().checklist.call_args[0][0], prompt) @mock.patch('certbot.storage.renewal_conf_files') @mock.patch('certbot.storage.lineagename_for_filename') def test_get_certnames_allow_multiple_user_abort(self, mock_name, mock_files): mock_files.return_value = ['example.com.conf'] mock_name.return_value = 'example.com' from certbot import cert_manager self.mock_get_utility().checklist.return_value = (display_util.CANCEL, []) self.assertRaises( errors.Error, cert_manager.get_certnames, self.config, "erroring_anyway", allow_multiple=True) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/lock_test.py0000644000175000017500000000744013344054434020610 0ustar ericaerica00000000000000"""Tests for certbot.lock.""" import functools import multiprocessing import os import unittest import mock from certbot import errors from certbot.tests import util as test_util class LockDirTest(test_util.TempDirTestCase): """Tests for certbot.lock.lock_dir.""" @classmethod def _call(cls, *args, **kwargs): from certbot.lock import lock_dir return lock_dir(*args, **kwargs) def test_it(self): assert_raises = functools.partial( self.assertRaises, errors.LockError, self._call, self.tempdir) lock_path = os.path.join(self.tempdir, '.certbot.lock') test_util.lock_and_call(assert_raises, lock_path) class LockFileTest(test_util.TempDirTestCase): """Tests for certbot.lock.LockFile.""" @classmethod def _call(cls, *args, **kwargs): from certbot.lock import LockFile return LockFile(*args, **kwargs) def setUp(self): super(LockFileTest, self).setUp() self.lock_path = os.path.join(self.tempdir, 'test.lock') def test_acquire_without_deletion(self): # acquire the lock in another process but don't delete the file child = multiprocessing.Process(target=self._call, args=(self.lock_path,)) child.start() child.join() self.assertEqual(child.exitcode, 0) self.assertTrue(os.path.exists(self.lock_path)) # Test we're still able to properly acquire and release the lock self.test_removed() def test_contention(self): assert_raises = functools.partial( self.assertRaises, errors.LockError, self._call, self.lock_path) test_util.lock_and_call(assert_raises, self.lock_path) def test_locked_repr(self): lock_file = self._call(self.lock_path) locked_repr = repr(lock_file) self._test_repr_common(lock_file, locked_repr) self.assertTrue('acquired' in locked_repr) def test_released_repr(self): lock_file = self._call(self.lock_path) lock_file.release() released_repr = repr(lock_file) self._test_repr_common(lock_file, released_repr) self.assertTrue('released' in released_repr) def _test_repr_common(self, lock_file, lock_repr): self.assertTrue(lock_file.__class__.__name__ in lock_repr) self.assertTrue(self.lock_path in lock_repr) def test_race(self): should_delete = [True, False] stat = os.stat def delete_and_stat(path): """Wrap os.stat and maybe delete the file first.""" if path == self.lock_path and should_delete.pop(0): os.remove(path) return stat(path) with mock.patch('certbot.lock.os.stat') as mock_stat: mock_stat.side_effect = delete_and_stat self._call(self.lock_path) self.assertFalse(should_delete) def test_removed(self): lock_file = self._call(self.lock_path) lock_file.release() self.assertFalse(os.path.exists(self.lock_path)) @mock.patch('certbot.lock.fcntl.lockf') def test_unexpected_lockf_err(self, mock_lockf): msg = 'hi there' mock_lockf.side_effect = IOError(msg) try: self._call(self.lock_path) except IOError as err: self.assertTrue(msg in str(err)) else: # pragma: no cover self.fail('IOError not raised') @mock.patch('certbot.lock.os.stat') def test_unexpected_stat_err(self, mock_stat): msg = 'hi there' mock_stat.side_effect = OSError(msg) try: self._call(self.lock_path) except OSError as err: self.assertTrue(msg in str(err)) else: # pragma: no cover self.fail('OSError not raised') if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/util.py0000644000175000017500000003033113344054434017571 0ustar ericaerica00000000000000"""Test utilities. .. warning:: This module is not part of the public API. """ import multiprocessing import os import pkg_resources import shutil import tempfile import unittest from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization import mock import OpenSSL import josepy as jose import six from six.moves import reload_module # pylint: disable=import-error from certbot import constants from certbot import interfaces from certbot import storage from certbot import util from certbot import configuration from certbot.display import util as display_util def vector_path(*names): """Path to a test vector.""" return pkg_resources.resource_filename( __name__, os.path.join('testdata', *names)) def load_vector(*names): """Load contents of a test vector.""" # luckily, resource_string opens file in binary mode return pkg_resources.resource_string( __name__, os.path.join('testdata', *names)) def _guess_loader(filename, loader_pem, loader_der): _, ext = os.path.splitext(filename) if ext.lower() == '.pem': return loader_pem elif ext.lower() == '.der': return loader_der else: # pragma: no cover raise ValueError("Loader could not be recognized based on extension") def load_cert(*names): """Load certificate.""" loader = _guess_loader( names[-1], OpenSSL.crypto.FILETYPE_PEM, OpenSSL.crypto.FILETYPE_ASN1) return OpenSSL.crypto.load_certificate(loader, load_vector(*names)) def load_csr(*names): """Load certificate request.""" loader = _guess_loader( names[-1], OpenSSL.crypto.FILETYPE_PEM, OpenSSL.crypto.FILETYPE_ASN1) return OpenSSL.crypto.load_certificate_request(loader, load_vector(*names)) def load_comparable_csr(*names): """Load ComparableX509 certificate request.""" return jose.ComparableX509(load_csr(*names)) def load_rsa_private_key(*names): """Load RSA private key.""" loader = _guess_loader(names[-1], serialization.load_pem_private_key, serialization.load_der_private_key) return jose.ComparableRSAKey(loader( load_vector(*names), password=None, backend=default_backend())) def load_pyopenssl_private_key(*names): """Load pyOpenSSL private key.""" loader = _guess_loader( names[-1], OpenSSL.crypto.FILETYPE_PEM, OpenSSL.crypto.FILETYPE_ASN1) return OpenSSL.crypto.load_privatekey(loader, load_vector(*names)) def skip_unless(condition, reason): # pragma: no cover """Skip tests unless a condition holds. This implements the basic functionality of unittest.skipUnless which is only available on Python 2.7+. :param bool condition: If ``False``, the test will be skipped :param str reason: the reason for skipping the test :rtype: callable :returns: decorator that hides tests unless condition is ``True`` """ if hasattr(unittest, "skipUnless"): return unittest.skipUnless(condition, reason) elif condition: return lambda cls: cls else: return lambda cls: None def make_lineage(config_dir, testfile): """Creates a lineage defined by testfile. This creates the archive, live, and renewal directories if necessary and creates a simple lineage. :param str config_dir: path to the configuration directory :param str testfile: configuration file to base the lineage on :returns: path to the renewal conf file for the created lineage :rtype: str """ lineage_name = testfile[:-len('.conf')] conf_dir = os.path.join( config_dir, constants.RENEWAL_CONFIGS_DIR) archive_dir = os.path.join( config_dir, constants.ARCHIVE_DIR, lineage_name) live_dir = os.path.join( config_dir, constants.LIVE_DIR, lineage_name) for directory in (archive_dir, conf_dir, live_dir,): if not os.path.exists(directory): os.makedirs(directory) sample_archive = vector_path('sample-archive') for kind in os.listdir(sample_archive): shutil.copyfile(os.path.join(sample_archive, kind), os.path.join(archive_dir, kind)) for kind in storage.ALL_FOUR: os.symlink(os.path.join(archive_dir, '{0}1.pem'.format(kind)), os.path.join(live_dir, '{0}.pem'.format(kind))) conf_path = os.path.join(config_dir, conf_dir, testfile) with open(vector_path(testfile)) as src: with open(conf_path, 'w') as dst: dst.writelines( line.replace('MAGICDIR', config_dir) for line in src) return conf_path def patch_get_utility(target='zope.component.getUtility'): """Patch zope.component.getUtility to use a special mock IDisplay. The mock IDisplay works like a regular mock object, except it also also asserts that methods are called with valid arguments. :param str target: path to patch :returns: mock zope.component.getUtility :rtype: mock.MagicMock """ return mock.patch(target, new_callable=_create_get_utility_mock) def patch_get_utility_with_stdout(target='zope.component.getUtility', stdout=None): """Patch zope.component.getUtility to use a special mock IDisplay. The mock IDisplay works like a regular mock object, except it also also asserts that methods are called with valid arguments. The `message` argument passed to the IDisplay methods is passed to stdout's write method. :param str target: path to patch :param object stdout: object to write standard output to; it is expected to have a `write` method :returns: mock zope.component.getUtility :rtype: mock.MagicMock """ stdout = stdout if stdout else six.StringIO() freezable_mock = _create_get_utility_mock_with_stdout(stdout) return mock.patch(target, new=freezable_mock) class FreezableMock(object): """Mock object with the ability to freeze attributes. This class works like a regular mock.MagicMock object, except attributes and behavior set before the object is frozen cannot be changed during tests. If a func argument is provided to the constructor, this function is called first when an instance of FreezableMock is called, followed by the usual behavior defined by MagicMock. The return value of func is ignored. """ def __init__(self, frozen=False, func=None, return_value=mock.sentinel.DEFAULT): self._frozen_set = set() if frozen else set(('freeze',)) self._func = func self._mock = mock.MagicMock() if return_value != mock.sentinel.DEFAULT: self.return_value = return_value self._frozen = frozen def freeze(self): """Freeze object preventing further changes.""" self._frozen = True def __call__(self, *args, **kwargs): if self._func is not None: self._func(*args, **kwargs) return self._mock(*args, **kwargs) def __getattribute__(self, name): if name == '_frozen': try: return object.__getattribute__(self, name) except AttributeError: return False elif name in ('return_value', 'side_effect',): return getattr(object.__getattribute__(self, '_mock'), name) elif name == '_frozen_set' or name in self._frozen_set: return object.__getattribute__(self, name) else: return getattr(object.__getattribute__(self, '_mock'), name) def __setattr__(self, name, value): """ Before it is frozen, attributes are set on the FreezableMock instance and added to the _frozen_set. Attributes in the _frozen_set cannot be changed after the FreezableMock is frozen. In this case, they are set on the underlying _mock. In cases of return_value and side_effect, these attributes are always passed through to the instance's _mock and added to the _frozen_set before the object is frozen. """ if self._frozen: if name in self._frozen_set: raise AttributeError('Cannot change frozen attribute ' + name) else: return setattr(self._mock, name, value) if name != '_frozen_set': self._frozen_set.add(name) if name in ('return_value', 'side_effect'): return setattr(self._mock, name, value) else: return object.__setattr__(self, name, value) def _create_get_utility_mock(): display = FreezableMock() for name in interfaces.IDisplay.names(): # pylint: disable=no-member if name != 'notification': frozen_mock = FreezableMock(frozen=True, func=_assert_valid_call) setattr(display, name, frozen_mock) display.freeze() return FreezableMock(frozen=True, return_value=display) def _create_get_utility_mock_with_stdout(stdout): def _write_msg(message, *unused_args, **unused_kwargs): """Write to message to stdout. """ if message: stdout.write(message) def mock_method(*args, **kwargs): """ Mock function for IDisplay methods. """ _assert_valid_call(args, kwargs) _write_msg(*args, **kwargs) display = FreezableMock() for name in interfaces.IDisplay.names(): # pylint: disable=no-member if name == 'notification': frozen_mock = FreezableMock(frozen=True, func=_write_msg) setattr(display, name, frozen_mock) else: frozen_mock = FreezableMock(frozen=True, func=mock_method) setattr(display, name, frozen_mock) display.freeze() return FreezableMock(frozen=True, return_value=display) def _assert_valid_call(*args, **kwargs): assert_args = [args[0] if args else kwargs['message']] assert_kwargs = {} assert_kwargs['default'] = kwargs.get('default', None) assert_kwargs['cli_flag'] = kwargs.get('cli_flag', None) assert_kwargs['force_interactive'] = kwargs.get('force_interactive', False) # pylint: disable=star-args display_util.assert_valid_call(*assert_args, **assert_kwargs) class TempDirTestCase(unittest.TestCase): """Base test class which sets up and tears down a temporary directory""" def setUp(self): self.tempdir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tempdir) class ConfigTestCase(TempDirTestCase): """Test class which sets up a NamespaceConfig object. """ def setUp(self): super(ConfigTestCase, self).setUp() self.config = configuration.NamespaceConfig( mock.MagicMock(**constants.CLI_DEFAULTS) ) self.config.verb = "certonly" self.config.config_dir = os.path.join(self.tempdir, 'config') self.config.work_dir = os.path.join(self.tempdir, 'work') self.config.logs_dir = os.path.join(self.tempdir, 'logs') self.config.cert_path = constants.CLI_DEFAULTS['auth_cert_path'] self.config.fullchain_path = constants.CLI_DEFAULTS['auth_chain_path'] self.config.chain_path = constants.CLI_DEFAULTS['auth_chain_path'] self.config.server = "https://example.com" def lock_and_call(func, lock_path): """Grab a lock for lock_path and call func. :param callable func: object to call after acquiring the lock :param str lock_path: path to file or directory to lock """ # Reload module to reset internal _LOCKS dictionary reload_module(util) # start child and wait for it to grab the lock cv = multiprocessing.Condition() cv.acquire() child_args = (cv, lock_path,) child = multiprocessing.Process(target=hold_lock, args=child_args) child.start() cv.wait() # call func and terminate the child func() cv.notify() cv.release() child.join() assert child.exitcode == 0 def hold_lock(cv, lock_path): # pragma: no cover """Acquire a file lock at lock_path and wait to release it. :param multiprocessing.Condition cv: condition for synchronization :param str lock_path: path to the file lock """ from certbot import lock if os.path.isdir(lock_path): my_lock = lock.lock_dir(lock_path) else: my_lock = lock.LockFile(lock_path) cv.acquire() cv.notify() cv.wait() my_lock.release() certbot-0.27.0/certbot/tests/reverter_test.py0000644000175000017500000004457613344054434021531 0ustar ericaerica00000000000000"""Test certbot.reverter.""" import csv import logging import os import shutil import tempfile import unittest import mock import six from certbot import errors from certbot.tests import util as test_util class ReverterCheckpointLocalTest(test_util.ConfigTestCase): # pylint: disable=too-many-instance-attributes, too-many-public-methods """Test the Reverter Class.""" def setUp(self): super(ReverterCheckpointLocalTest, self).setUp() from certbot.reverter import Reverter # Disable spurious errors... we are trying to test for them logging.disable(logging.CRITICAL) self.reverter = Reverter(self.config) tup = setup_test_files() self.config1, self.config2, self.dir1, self.dir2, self.sets = tup def tearDown(self): shutil.rmtree(self.config.work_dir) shutil.rmtree(self.dir1) shutil.rmtree(self.dir2) logging.disable(logging.NOTSET) @mock.patch("certbot.reverter.Reverter._read_and_append") def test_no_change(self, mock_read): mock_read.side_effect = OSError("cannot even") try: self.reverter.add_to_checkpoint(self.sets[0], "save1") except OSError: pass self.reverter.finalize_checkpoint("blah") path = os.listdir(self.reverter.config.backup_dir)[0] no_change = os.path.join(self.reverter.config.backup_dir, path, "CHANGES_SINCE") with open(no_change, "r") as f: x = f.read() self.assertTrue("No changes" in x) def test_basic_add_to_temp_checkpoint(self): # These shouldn't conflict even though they are both named config.txt self.reverter.add_to_temp_checkpoint(self.sets[0], "save1") self.reverter.add_to_temp_checkpoint(self.sets[1], "save2") self.assertTrue(os.path.isdir(self.config.temp_checkpoint_dir)) self.assertEqual(get_save_notes( self.config.temp_checkpoint_dir), "save1save2") self.assertFalse(os.path.isfile( os.path.join(self.config.temp_checkpoint_dir, "NEW_FILES"))) self.assertEqual( get_filepaths(self.config.temp_checkpoint_dir), "{0}\n{1}\n".format(self.config1, self.config2)) def test_add_to_checkpoint_copy_failure(self): with mock.patch("certbot.reverter.shutil.copy2") as mock_copy2: mock_copy2.side_effect = IOError("bad copy") self.assertRaises( errors.ReverterError, self.reverter.add_to_checkpoint, self.sets[0], "save1") def test_checkpoint_conflict(self): """Make sure that checkpoint errors are thrown appropriately.""" config3 = os.path.join(self.dir1, "config3.txt") self.reverter.register_file_creation(True, config3) update_file(config3, "This is a new file!") self.reverter.add_to_checkpoint(self.sets[2], "save1") # This shouldn't throw an error self.reverter.add_to_temp_checkpoint(self.sets[0], "save2") # Raise error self.assertRaises(errors.ReverterError, self.reverter.add_to_checkpoint, self.sets[2], "save3") # Should not cause an error self.reverter.add_to_checkpoint(self.sets[1], "save4") # Check to make sure new files are also checked... self.assertRaises(errors.ReverterError, self.reverter.add_to_checkpoint, set([config3]), "invalid save") def test_multiple_saves_and_temp_revert(self): self.reverter.add_to_temp_checkpoint(self.sets[0], "save1") update_file(self.config1, "updated-directive") self.reverter.add_to_temp_checkpoint(self.sets[0], "save2-updated dir") update_file(self.config1, "new directive change that we won't keep") self.reverter.revert_temporary_config() self.assertEqual(read_in(self.config1), "directive-dir1") def test_multiple_registration_fail_and_revert(self): config3 = os.path.join(self.dir1, "config3.txt") update_file(config3, "Config3") config4 = os.path.join(self.dir2, "config4.txt") update_file(config4, "Config4") # Test multiple registrations and two registrations at once self.reverter.register_file_creation(True, self.config1) self.reverter.register_file_creation(True, self.config2) self.reverter.register_file_creation(True, config3, config4) # Simulate Certbot crash... recovery routine is run self.reverter.recovery_routine() self.assertFalse(os.path.isfile(self.config1)) self.assertFalse(os.path.isfile(self.config2)) self.assertFalse(os.path.isfile(config3)) self.assertFalse(os.path.isfile(config4)) def test_multiple_registration_same_file(self): self.reverter.register_file_creation(True, self.config1) self.reverter.register_file_creation(True, self.config1) self.reverter.register_file_creation(True, self.config1) self.reverter.register_file_creation(True, self.config1) files = get_new_files(self.config.temp_checkpoint_dir) self.assertEqual(len(files), 1) def test_register_file_creation_write_error(self): m_open = mock.mock_open() with mock.patch("certbot.reverter.open", m_open, create=True): m_open.side_effect = OSError("bad open") self.assertRaises( errors.ReverterError, self.reverter.register_file_creation, True, self.config1) def test_bad_registration(self): # Made this mistake and want to make sure it doesn't happen again... self.assertRaises( errors.ReverterError, self.reverter.register_file_creation, "filepath") def test_register_undo_command(self): coms = [ ["a2dismod", "ssl"], ["a2dismod", "rewrite"], ["cleanslate"] ] for com in coms: self.reverter.register_undo_command(True, com) act_coms = get_undo_commands(self.config.temp_checkpoint_dir) for a_com, com in six.moves.zip(act_coms, coms): self.assertEqual(a_com, com) def test_bad_register_undo_command(self): m_open = mock.mock_open() with mock.patch("certbot.reverter.open", m_open, create=True): m_open.side_effect = OSError("bad open") self.assertRaises( errors.ReverterError, self.reverter.register_undo_command, True, ["command"]) @mock.patch("certbot.util.run_script") def test_run_undo_commands(self, mock_run): mock_run.side_effect = ["", errors.SubprocessError] coms = [ ["invalid_command"], ["a2dismod", "ssl"], ] for com in coms: self.reverter.register_undo_command(True, com) self.reverter.revert_temporary_config() self.assertEqual(mock_run.call_count, 2) def test_recovery_routine_in_progress_failure(self): self.reverter.add_to_checkpoint(self.sets[0], "perm save") # pylint: disable=protected-access self.reverter._recover_checkpoint = mock.MagicMock( side_effect=errors.ReverterError) self.assertRaises(errors.ReverterError, self.reverter.recovery_routine) def test_recover_checkpoint_revert_temp_failures(self): mock_recover = mock.MagicMock( side_effect=errors.ReverterError("e")) # pylint: disable=protected-access self.reverter._recover_checkpoint = mock_recover self.reverter.add_to_temp_checkpoint(self.sets[0], "config1 save") self.assertRaises( errors.ReverterError, self.reverter.revert_temporary_config) def test_recover_checkpoint_rollback_failure(self): mock_recover = mock.MagicMock( side_effect=errors.ReverterError("e")) # pylint: disable=protected-access self.reverter._recover_checkpoint = mock_recover self.reverter.add_to_checkpoint(self.sets[0], "config1 save") self.reverter.finalize_checkpoint("Title") self.assertRaises( errors.ReverterError, self.reverter.rollback_checkpoints, 1) def test_recover_checkpoint_copy_failure(self): self.reverter.add_to_temp_checkpoint(self.sets[0], "save1") with mock.patch("certbot.reverter.shutil.copy2") as mock_copy2: mock_copy2.side_effect = OSError("bad copy") self.assertRaises( errors.ReverterError, self.reverter.revert_temporary_config) def test_recover_checkpoint_rm_failure(self): self.reverter.add_to_temp_checkpoint(self.sets[0], "temp save") with mock.patch("certbot.reverter.shutil.rmtree") as mock_rmtree: mock_rmtree.side_effect = OSError("Cannot remove tree") self.assertRaises( errors.ReverterError, self.reverter.revert_temporary_config) @mock.patch("certbot.reverter.logger.warning") def test_recover_checkpoint_missing_new_files(self, mock_warn): self.reverter.register_file_creation( True, os.path.join(self.dir1, "missing_file.txt")) self.reverter.revert_temporary_config() self.assertEqual(mock_warn.call_count, 1) @mock.patch("certbot.reverter.os.remove") def test_recover_checkpoint_remove_failure(self, mock_remove): self.reverter.register_file_creation(True, self.config1) mock_remove.side_effect = OSError("Can't remove") self.assertRaises( errors.ReverterError, self.reverter.revert_temporary_config) def test_recovery_routine_temp_and_perm(self): # Register a new perm checkpoint file config3 = os.path.join(self.dir1, "config3.txt") self.reverter.register_file_creation(False, config3) update_file(config3, "This is a new perm file!") # Add changes to perm checkpoint self.reverter.add_to_checkpoint(self.sets[0], "perm save1") update_file(self.config1, "updated perm config1") self.reverter.add_to_checkpoint(self.sets[1], "perm save2") update_file(self.config2, "updated perm config2") # Add changes to a temporary checkpoint self.reverter.add_to_temp_checkpoint(self.sets[0], "temp save1") update_file(self.config1, "second update now temp config1") # Register a new temp checkpoint file config4 = os.path.join(self.dir2, "config4.txt") self.reverter.register_file_creation(True, config4) update_file(config4, "New temporary file!") # Now erase everything self.reverter.recovery_routine() # Now Run tests # These were new files.. they should be removed self.assertFalse(os.path.isfile(config3)) self.assertFalse(os.path.isfile(config4)) # Check to make sure everything got rolled back appropriately self.assertEqual(read_in(self.config1), "directive-dir1") self.assertEqual(read_in(self.config2), "directive-dir2") class TestFullCheckpointsReverter(test_util.ConfigTestCase): # pylint: disable=too-many-instance-attributes """Tests functions having to deal with full checkpoints.""" def setUp(self): super(TestFullCheckpointsReverter, self).setUp() from certbot.reverter import Reverter # Disable spurious errors... logging.disable(logging.CRITICAL) self.reverter = Reverter(self.config) tup = setup_test_files() self.config1, self.config2, self.dir1, self.dir2, self.sets = tup def tearDown(self): shutil.rmtree(self.config.work_dir) shutil.rmtree(self.dir1) shutil.rmtree(self.dir2) logging.disable(logging.NOTSET) def test_rollback_improper_inputs(self): self.assertRaises( errors.ReverterError, self.reverter.rollback_checkpoints, "-1") self.assertRaises( errors.ReverterError, self.reverter.rollback_checkpoints, -1000) self.assertRaises( errors.ReverterError, self.reverter.rollback_checkpoints, "one") def test_rollback_finalize_checkpoint_valid_inputs(self): config3 = self._setup_three_checkpoints() # Check resulting backup directory self.assertEqual(len(os.listdir(self.config.backup_dir)), 3) # Check rollbacks # First rollback self.reverter.rollback_checkpoints(1) self.assertEqual(read_in(self.config1), "update config1") self.assertEqual(read_in(self.config2), "update config2") # config3 was not included in checkpoint self.assertEqual(read_in(config3), "Final form config3") # Second rollback self.reverter.rollback_checkpoints(1) self.assertEqual(read_in(self.config1), "update config1") self.assertEqual(read_in(self.config2), "directive-dir2") self.assertFalse(os.path.isfile(config3)) # One dir left... check title all_dirs = os.listdir(self.config.backup_dir) self.assertEqual(len(all_dirs), 1) self.assertTrue( "First Checkpoint" in get_save_notes( os.path.join(self.config.backup_dir, all_dirs[0]))) # Final rollback self.reverter.rollback_checkpoints(1) self.assertEqual(read_in(self.config1), "directive-dir1") def test_finalize_checkpoint_no_in_progress(self): # No need to warn for this... just make sure there are no errors. self.reverter.finalize_checkpoint("No checkpoint...") @mock.patch("certbot.reverter.shutil.move") def test_finalize_checkpoint_cannot_title(self, mock_move): self.reverter.add_to_checkpoint(self.sets[0], "perm save") mock_move.side_effect = OSError("cannot move") self.assertRaises( errors.ReverterError, self.reverter.finalize_checkpoint, "Title") @mock.patch("certbot.reverter.os.rename") def test_finalize_checkpoint_no_rename_directory(self, mock_rename): self.reverter.add_to_checkpoint(self.sets[0], "perm save") mock_rename.side_effect = OSError self.assertRaises( errors.ReverterError, self.reverter.finalize_checkpoint, "Title") @mock.patch("certbot.reverter.logger") def test_rollback_too_many(self, mock_logger): # Test no exist warning... self.reverter.rollback_checkpoints(1) self.assertEqual(mock_logger.warning.call_count, 1) # Test Generic warning self._setup_three_checkpoints() mock_logger.warning.call_count = 0 self.reverter.rollback_checkpoints(4) self.assertEqual(mock_logger.warning.call_count, 1) def test_multi_rollback(self): config3 = self._setup_three_checkpoints() self.reverter.rollback_checkpoints(3) self.assertEqual(read_in(self.config1), "directive-dir1") self.assertEqual(read_in(self.config2), "directive-dir2") self.assertFalse(os.path.isfile(config3)) @test_util.patch_get_utility() def test_view_config_changes(self, mock_output): """This is not strict as this is subject to change.""" self._setup_three_checkpoints() # Make sure it doesn't throw any errors self.reverter.view_config_changes() # Make sure notification is output self.assertEqual(mock_output().notification.call_count, 1) @mock.patch("certbot.reverter.logger") def test_view_config_changes_no_backups(self, mock_logger): self.reverter.view_config_changes() self.assertTrue(mock_logger.info.call_count > 0) def test_view_config_changes_bad_backups_dir(self): # There shouldn't be any "in progress directories when this is called # It must just be clean checkpoints os.makedirs(os.path.join(self.config.backup_dir, "in_progress")) self.assertRaises( errors.ReverterError, self.reverter.view_config_changes) def test_view_config_changes_for_logging(self): self._setup_three_checkpoints() config_changes = self.reverter.view_config_changes(for_logging=True) self.assertTrue("First Checkpoint" in config_changes) self.assertTrue("Second Checkpoint" in config_changes) self.assertTrue("Third Checkpoint" in config_changes) def _setup_three_checkpoints(self): """Generate some finalized checkpoints.""" # Checkpoint1 - config1 self.reverter.add_to_checkpoint(self.sets[0], "first save") self.reverter.finalize_checkpoint("First Checkpoint") update_file(self.config1, "update config1") # Checkpoint2 - new file config3, update config2 config3 = os.path.join(self.dir1, "config3.txt") self.reverter.register_file_creation(False, config3) update_file(config3, "directive-config3") self.reverter.add_to_checkpoint(self.sets[1], "second save") self.reverter.finalize_checkpoint("Second Checkpoint") update_file(self.config2, "update config2") update_file(config3, "update config3") # Checkpoint3 - update config1, config2 self.reverter.add_to_checkpoint(self.sets[2], "third save") self.reverter.finalize_checkpoint("Third Checkpoint - Save both") update_file(self.config1, "Final form config1") update_file(self.config2, "Final form config2") update_file(config3, "Final form config3") return config3 def setup_test_files(): """Setup sample configuration files.""" dir1 = tempfile.mkdtemp("dir1") dir2 = tempfile.mkdtemp("dir2") config1 = os.path.join(dir1, "config.txt") config2 = os.path.join(dir2, "config.txt") with open(config1, "w") as file_fd: file_fd.write("directive-dir1") with open(config2, "w") as file_fd: file_fd.write("directive-dir2") sets = [set([config1]), set([config2]), set([config1, config2])] return config1, config2, dir1, dir2, sets def get_save_notes(dire): """Read save notes""" return read_in(os.path.join(dire, "CHANGES_SINCE")) def get_filepaths(dire): """Get Filepaths""" return read_in(os.path.join(dire, "FILEPATHS")) def get_new_files(dire): """Get new files.""" return read_in(os.path.join(dire, "NEW_FILES")).splitlines() def get_undo_commands(dire): """Get new files.""" with open(os.path.join(dire, "COMMANDS")) as csvfile: return list(csv.reader(csvfile)) def read_in(path): """Read in a file, return the str""" with open(path, "r") as file_fd: return file_fd.read() def update_file(filename, string): """Update a file with a new value.""" with open(filename, "w") as file_fd: file_fd.write(string) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/reporter_test.py0000644000175000017500000000535713344054434021527 0ustar ericaerica00000000000000"""Tests for certbot.reporter.""" import mock import sys import unittest import six class ReporterTest(unittest.TestCase): """Tests for certbot.reporter.Reporter.""" def setUp(self): from certbot import reporter self.reporter = reporter.Reporter(mock.MagicMock(quiet=False)) self.old_stdout = sys.stdout # type: ignore sys.stdout = six.StringIO() def tearDown(self): sys.stdout = self.old_stdout def test_multiline_message(self): self.reporter.add_message("Line 1\nLine 2", self.reporter.LOW_PRIORITY) self.reporter.print_messages() output = sys.stdout.getvalue() # type: ignore self.assertTrue("Line 1\n" in output) self.assertTrue("Line 2" in output) def test_tty_print_empty(self): sys.stdout.isatty = lambda: True # type: ignore self.test_no_tty_print_empty() def test_no_tty_print_empty(self): self.reporter.print_messages() self.assertEqual(sys.stdout.getvalue(), "") # type: ignore try: raise ValueError except ValueError: self.reporter.print_messages() self.assertEqual(sys.stdout.getvalue(), "") # type: ignore def test_tty_successful_exit(self): sys.stdout.isatty = lambda: True # type: ignore self._successful_exit_common() def test_no_tty_successful_exit(self): self._successful_exit_common() def test_tty_unsuccessful_exit(self): sys.stdout.isatty = lambda: True # type: ignore self._unsuccessful_exit_common() def test_no_tty_unsuccessful_exit(self): self._unsuccessful_exit_common() def _successful_exit_common(self): self._add_messages() self.reporter.print_messages() output = sys.stdout.getvalue() # type: ignore self.assertTrue("IMPORTANT NOTES:" in output) self.assertTrue("High" in output) self.assertTrue("Med" in output) self.assertTrue("Low" in output) def _unsuccessful_exit_common(self): self._add_messages() try: raise ValueError except ValueError: self.reporter.print_messages() output = sys.stdout.getvalue() # type: ignore self.assertTrue("IMPORTANT NOTES:" in output) self.assertTrue("High" in output) self.assertTrue("Med" not in output) self.assertTrue("Low" not in output) def _add_messages(self): self.reporter.add_message("High", self.reporter.HIGH_PRIORITY) self.reporter.add_message( "Med", self.reporter.MEDIUM_PRIORITY, on_crash=False) self.reporter.add_message( "Low", self.reporter.LOW_PRIORITY, on_crash=False) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/hook_test.py0000644000175000017500000004121713344054434020620 0ustar ericaerica00000000000000"""Tests for certbot.hooks.""" import os import stat import unittest import mock from acme.magic_typing import List # pylint: disable=unused-import, no-name-in-module from certbot import errors from certbot.tests import util class ValidateHooksTest(unittest.TestCase): """Tests for certbot.hooks.validate_hooks.""" @classmethod def _call(cls, *args, **kwargs): from certbot.hooks import validate_hooks return validate_hooks(*args, **kwargs) @mock.patch("certbot.hooks.validate_hook") def test_it(self, mock_validate_hook): config = mock.MagicMock() self._call(config) types = [call[0][1] for call in mock_validate_hook.call_args_list] self.assertEqual(set(("pre", "post", "deploy",)), set(types[:-1])) # This ensures error messages are about deploy hooks when appropriate self.assertEqual("renew", types[-1]) class ValidateHookTest(util.TempDirTestCase): """Tests for certbot.hooks.validate_hook.""" @classmethod def _call(cls, *args, **kwargs): from certbot.hooks import validate_hook return validate_hook(*args, **kwargs) def test_not_executable(self): file_path = os.path.join(self.tempdir, "foo") # create a non-executable file os.close(os.open(file_path, os.O_CREAT | os.O_WRONLY, 0o666)) # prevent unnecessary modifications to PATH with mock.patch("certbot.hooks.plug_util.path_surgery"): self.assertRaises(errors.HookCommandNotFound, self._call, file_path, "foo") @mock.patch("certbot.hooks.util.exe_exists") def test_not_found(self, mock_exe_exists): mock_exe_exists.return_value = False with mock.patch("certbot.hooks.plug_util.path_surgery") as mock_ps: self.assertRaises(errors.HookCommandNotFound, self._call, "foo", "bar") self.assertTrue(mock_ps.called) @mock.patch("certbot.hooks._prog") def test_unset(self, mock_prog): self._call(None, "foo") self.assertFalse(mock_prog.called) class HookTest(util.ConfigTestCase): """Common base class for hook tests.""" @classmethod def _call(cls, *args, **kwargs): """Calls the method being tested with the given arguments.""" raise NotImplementedError @classmethod def _call_with_mock_execute(cls, *args, **kwargs): """Calls self._call after mocking out certbot.hooks.execute. The mock execute object is returned rather than the return value of self._call. """ with mock.patch("certbot.hooks.execute") as mock_execute: mock_execute.return_value = ("", "") cls._call(*args, **kwargs) return mock_execute class PreHookTest(HookTest): """Tests for certbot.hooks.pre_hook.""" @classmethod def _call(cls, *args, **kwargs): from certbot.hooks import pre_hook return pre_hook(*args, **kwargs) def setUp(self): super(PreHookTest, self).setUp() self.config.pre_hook = "foo" os.makedirs(self.config.renewal_pre_hooks_dir) self.dir_hook = os.path.join(self.config.renewal_pre_hooks_dir, "bar") create_hook(self.dir_hook) # Reset this value as it may have been modified by past tests self._reset_pre_hook_already() def tearDown(self): # Reset this value so it's unmodified for future tests self._reset_pre_hook_already() super(PreHookTest, self).tearDown() def _reset_pre_hook_already(self): from certbot.hooks import executed_pre_hooks executed_pre_hooks.clear() def test_certonly(self): self.config.verb = "certonly" self._test_nonrenew_common() def test_run(self): self.config.verb = "run" self._test_nonrenew_common() def _test_nonrenew_common(self): mock_execute = self._call_with_mock_execute(self.config) mock_execute.assert_called_once_with(self.config.pre_hook) self._test_no_executions_common() def test_no_hooks(self): self.config.pre_hook = None self.config.verb = "renew" os.remove(self.dir_hook) with mock.patch("certbot.hooks.logger") as mock_logger: mock_execute = self._call_with_mock_execute(self.config) self.assertFalse(mock_execute.called) self.assertFalse(mock_logger.info.called) def test_renew_disabled_dir_hooks(self): self.config.directory_hooks = False mock_execute = self._call_with_mock_execute(self.config) mock_execute.assert_called_once_with(self.config.pre_hook) self._test_no_executions_common() def test_renew_no_overlap(self): self.config.verb = "renew" mock_execute = self._call_with_mock_execute(self.config) mock_execute.assert_any_call(self.dir_hook) mock_execute.assert_called_with(self.config.pre_hook) self._test_no_executions_common() def test_renew_with_overlap(self): self.config.pre_hook = self.dir_hook self.config.verb = "renew" mock_execute = self._call_with_mock_execute(self.config) mock_execute.assert_called_once_with(self.dir_hook) self._test_no_executions_common() def _test_no_executions_common(self): with mock.patch("certbot.hooks.logger") as mock_logger: mock_execute = self._call_with_mock_execute(self.config) self.assertFalse(mock_execute.called) self.assertTrue(mock_logger.info.called) class PostHookTest(HookTest): """Tests for certbot.hooks.post_hook.""" @classmethod def _call(cls, *args, **kwargs): from certbot.hooks import post_hook return post_hook(*args, **kwargs) def setUp(self): super(PostHookTest, self).setUp() self.config.post_hook = "bar" os.makedirs(self.config.renewal_post_hooks_dir) self.dir_hook = os.path.join(self.config.renewal_post_hooks_dir, "foo") create_hook(self.dir_hook) # Reset this value as it may have been modified by past tests self._reset_post_hook_eventually() def tearDown(self): # Reset this value so it's unmodified for future tests self._reset_post_hook_eventually() super(PostHookTest, self).tearDown() def _reset_post_hook_eventually(self): from certbot.hooks import post_hooks del post_hooks[:] def test_certonly_and_run_with_hook(self): for verb in ("certonly", "run",): self.config.verb = verb mock_execute = self._call_with_mock_execute(self.config) mock_execute.assert_called_once_with(self.config.post_hook) self.assertFalse(self._get_eventually()) def test_cert_only_and_run_without_hook(self): self.config.post_hook = None for verb in ("certonly", "run",): self.config.verb = verb self.assertFalse(self._call_with_mock_execute(self.config).called) self.assertFalse(self._get_eventually()) def test_renew_disabled_dir_hooks(self): self.config.directory_hooks = False self._test_renew_common([self.config.post_hook]) def test_renew_no_config_hook(self): self.config.post_hook = None self._test_renew_common([self.dir_hook]) def test_renew_no_dir_hook(self): os.remove(self.dir_hook) self._test_renew_common([self.config.post_hook]) def test_renew_no_hooks(self): self.config.post_hook = None os.remove(self.dir_hook) self._test_renew_common([]) def test_renew_no_overlap(self): expected = [self.dir_hook, self.config.post_hook] self._test_renew_common(expected) self.config.post_hook = "baz" expected.append(self.config.post_hook) self._test_renew_common(expected) def test_renew_with_overlap(self): self.config.post_hook = self.dir_hook self._test_renew_common([self.dir_hook]) def _test_renew_common(self, expected): self.config.verb = "renew" for _ in range(2): self._call(self.config) self.assertEqual(self._get_eventually(), expected) def _get_eventually(self): from certbot.hooks import post_hooks return post_hooks class RunSavedPostHooksTest(HookTest): """Tests for certbot.hooks.run_saved_post_hooks.""" @classmethod def _call(cls, *args, **kwargs): from certbot.hooks import run_saved_post_hooks return run_saved_post_hooks() def _call_with_mock_execute_and_eventually(self, *args, **kwargs): """Call run_saved_post_hooks but mock out execute and eventually certbot.hooks.post_hooks is replaced with self.eventually. The mock execute object is returned rather than the return value of run_saved_post_hooks. """ eventually_path = "certbot.hooks.post_hooks" with mock.patch(eventually_path, new=self.eventually): return self._call_with_mock_execute(*args, **kwargs) def setUp(self): super(RunSavedPostHooksTest, self).setUp() self.eventually = [] # type: List[str] def test_empty(self): self.assertFalse(self._call_with_mock_execute_and_eventually().called) def test_multiple(self): self.eventually = ["foo", "bar", "baz", "qux"] mock_execute = self._call_with_mock_execute_and_eventually() calls = mock_execute.call_args_list for actual_call, expected_arg in zip(calls, self.eventually): self.assertEqual(actual_call[0][0], expected_arg) def test_single(self): self.eventually = ["foo"] mock_execute = self._call_with_mock_execute_and_eventually() mock_execute.assert_called_once_with(self.eventually[0]) class RenewalHookTest(HookTest): """Common base class for testing deploy/renew hooks.""" # Needed for https://github.com/PyCQA/pylint/issues/179 # pylint: disable=abstract-method def _call_with_mock_execute(self, *args, **kwargs): """Calls self._call after mocking out certbot.hooks.execute. The mock execute object is returned rather than the return value of self._call. The mock execute object asserts that environment variables were properly set. """ domains = kwargs["domains"] if "domains" in kwargs else args[1] lineage = kwargs["lineage"] if "lineage" in kwargs else args[2] def execute_side_effect(*unused_args, **unused_kwargs): """Assert environment variables are properly set. :returns: two strings imitating no output from the hook :rtype: `tuple` of `str` """ self.assertEqual(os.environ["RENEWED_DOMAINS"], " ".join(domains)) self.assertEqual(os.environ["RENEWED_LINEAGE"], lineage) return ("", "") with mock.patch("certbot.hooks.execute") as mock_execute: mock_execute.side_effect = execute_side_effect self._call(*args, **kwargs) return mock_execute def setUp(self): super(RenewalHookTest, self).setUp() self.vars_to_clear = set( var for var in ("RENEWED_DOMAINS", "RENEWED_LINEAGE",) if var not in os.environ) def tearDown(self): for var in self.vars_to_clear: os.environ.pop(var, None) super(RenewalHookTest, self).tearDown() class DeployHookTest(RenewalHookTest): """Tests for certbot.hooks.deploy_hook.""" @classmethod def _call(cls, *args, **kwargs): from certbot.hooks import deploy_hook return deploy_hook(*args, **kwargs) @mock.patch("certbot.hooks.logger") def test_dry_run(self, mock_logger): self.config.deploy_hook = "foo" self.config.dry_run = True mock_execute = self._call_with_mock_execute( self.config, ["example.org"], "/foo/bar") self.assertFalse(mock_execute.called) self.assertTrue(mock_logger.warning.called) @mock.patch("certbot.hooks.logger") def test_no_hook(self, mock_logger): self.config.deploy_hook = None mock_execute = self._call_with_mock_execute( self.config, ["example.org"], "/foo/bar") self.assertFalse(mock_execute.called) self.assertFalse(mock_logger.info.called) def test_success(self): domains = ["example.org", "example.net"] lineage = "/foo/bar" self.config.deploy_hook = "foo" mock_execute = self._call_with_mock_execute( self.config, domains, lineage) mock_execute.assert_called_once_with(self.config.deploy_hook) class RenewHookTest(RenewalHookTest): """Tests for certbot.hooks.renew_hook""" @classmethod def _call(cls, *args, **kwargs): from certbot.hooks import renew_hook return renew_hook(*args, **kwargs) def setUp(self): super(RenewHookTest, self).setUp() self.config.renew_hook = "foo" os.makedirs(self.config.renewal_deploy_hooks_dir) self.dir_hook = os.path.join(self.config.renewal_deploy_hooks_dir, "bar") create_hook(self.dir_hook) def test_disabled_dir_hooks(self): self.config.directory_hooks = False mock_execute = self._call_with_mock_execute( self.config, ["example.org"], "/foo/bar") mock_execute.assert_called_once_with(self.config.renew_hook) @mock.patch("certbot.hooks.logger") def test_dry_run(self, mock_logger): self.config.dry_run = True mock_execute = self._call_with_mock_execute( self.config, ["example.org"], "/foo/bar") self.assertFalse(mock_execute.called) self.assertEqual(mock_logger.warning.call_count, 2) def test_no_hooks(self): self.config.renew_hook = None os.remove(self.dir_hook) with mock.patch("certbot.hooks.logger") as mock_logger: mock_execute = self._call_with_mock_execute( self.config, ["example.org"], "/foo/bar") self.assertFalse(mock_execute.called) self.assertFalse(mock_logger.info.called) def test_overlap(self): self.config.renew_hook = self.dir_hook mock_execute = self._call_with_mock_execute( self.config, ["example.net", "example.org"], "/foo/bar") mock_execute.assert_called_once_with(self.dir_hook) def test_no_overlap(self): mock_execute = self._call_with_mock_execute( self.config, ["example.org"], "/foo/bar") mock_execute.assert_any_call(self.dir_hook) mock_execute.assert_called_with(self.config.renew_hook) class ExecuteTest(unittest.TestCase): """Tests for certbot.hooks.execute.""" @classmethod def _call(cls, *args, **kwargs): from certbot.hooks import execute return execute(*args, **kwargs) def test_it(self): for returncode in range(0, 2): for stdout in ("", "Hello World!",): for stderr in ("", "Goodbye Cruel World!"): self._test_common(returncode, stdout, stderr) def _test_common(self, returncode, stdout, stderr): given_command = "foo" with mock.patch("certbot.hooks.Popen") as mock_popen: mock_popen.return_value.communicate.return_value = (stdout, stderr) mock_popen.return_value.returncode = returncode with mock.patch("certbot.hooks.logger") as mock_logger: self.assertEqual(self._call(given_command), (stderr, stdout)) executed_command = mock_popen.call_args[1].get( "args", mock_popen.call_args[0][0]) self.assertEqual(executed_command, given_command) if stdout: self.assertTrue(mock_logger.info.called) if stderr or returncode: self.assertTrue(mock_logger.error.called) class ListHooksTest(util.TempDirTestCase): """Tests for certbot.hooks.list_hooks.""" @classmethod def _call(cls, *args, **kwargs): from certbot.hooks import list_hooks return list_hooks(*args, **kwargs) def test_empty(self): self.assertFalse(self._call(self.tempdir)) def test_multiple(self): names = sorted( os.path.join(self.tempdir, basename) for basename in ("foo", "bar", "baz", "qux") ) for name in names: create_hook(name) self.assertEqual(self._call(self.tempdir), names) def test_single(self): name = os.path.join(self.tempdir, "foo") create_hook(name) self.assertEqual(self._call(self.tempdir), [name]) def create_hook(file_path): """Creates an executable file at the specified path. :param str file_path: path to create the file at """ open(file_path, "w").close() os.chmod(file_path, os.stat(file_path).st_mode | stat.S_IXUSR) if __name__ == '__main__': unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/log_test.py0000644000175000017500000003562013344054434020442 0ustar ericaerica00000000000000"""Tests for certbot.log.""" import logging import logging.handlers import os import sys import time import unittest import mock import six from acme import messages from acme.magic_typing import Optional # pylint: disable=unused-import, no-name-in-module from certbot import constants from certbot import errors from certbot import util from certbot.tests import util as test_util class PreArgParseSetupTest(unittest.TestCase): """Tests for certbot.log.pre_arg_parse_setup.""" @classmethod def _call(cls, *args, **kwargs): # pylint: disable=unused-argument from certbot.log import pre_arg_parse_setup return pre_arg_parse_setup() @mock.patch('certbot.log.sys') @mock.patch('certbot.log.pre_arg_parse_except_hook') @mock.patch('certbot.log.logging.getLogger') @mock.patch('certbot.log.util.atexit_register') def test_it(self, mock_register, mock_get, mock_except_hook, mock_sys): mock_sys.argv = ['--debug'] mock_sys.version_info = sys.version_info self._call() mock_root_logger = mock_get() mock_root_logger.setLevel.assert_called_once_with(logging.DEBUG) self.assertEqual(mock_root_logger.addHandler.call_count, 2) memory_handler = None # type: Optional[logging.handlers.MemoryHandler] for call in mock_root_logger.addHandler.call_args_list: handler = call[0][0] if memory_handler is None and isinstance(handler, logging.handlers.MemoryHandler): memory_handler = handler target = memory_handler.target # type: ignore else: self.assertTrue(isinstance(handler, logging.StreamHandler)) self.assertTrue( isinstance(target, logging.StreamHandler)) mock_register.assert_called_once_with(logging.shutdown) mock_sys.excepthook(1, 2, 3) mock_except_hook.assert_called_once_with( memory_handler, 1, 2, 3, debug=True, log_path=mock.ANY) class PostArgParseSetupTest(test_util.ConfigTestCase): """Tests for certbot.log.post_arg_parse_setup.""" @classmethod def _call(cls, *args, **kwargs): from certbot.log import post_arg_parse_setup return post_arg_parse_setup(*args, **kwargs) def setUp(self): super(PostArgParseSetupTest, self).setUp() self.config.debug = False self.config.max_log_backups = 1000 self.config.quiet = False self.config.verbose_count = constants.CLI_DEFAULTS['verbose_count'] self.devnull = open(os.devnull, 'w') from certbot.log import ColoredStreamHandler self.stream_handler = ColoredStreamHandler(six.StringIO()) from certbot.log import MemoryHandler, TempHandler self.temp_handler = TempHandler() self.temp_path = self.temp_handler.path self.memory_handler = MemoryHandler(self.temp_handler) self.root_logger = mock.MagicMock( handlers=[self.memory_handler, self.stream_handler]) def tearDown(self): self.memory_handler.close() self.stream_handler.close() self.temp_handler.close() super(PostArgParseSetupTest, self).tearDown() def test_common(self): with mock.patch('certbot.log.logging.getLogger') as mock_get_logger: mock_get_logger.return_value = self.root_logger except_hook_path = 'certbot.log.post_arg_parse_except_hook' with mock.patch(except_hook_path) as mock_except_hook: with mock.patch('certbot.log.sys') as mock_sys: mock_sys.version_info = sys.version_info self._call(self.config) self.root_logger.removeHandler.assert_called_once_with( self.memory_handler) self.assertTrue(self.root_logger.addHandler.called) self.assertTrue(os.path.exists(os.path.join( self.config.logs_dir, 'letsencrypt.log'))) self.assertFalse(os.path.exists(self.temp_path)) mock_sys.excepthook(1, 2, 3) mock_except_hook.assert_called_once_with( 1, 2, 3, debug=self.config.debug, log_path=self.config.logs_dir) level = self.stream_handler.level if self.config.quiet: self.assertEqual(level, constants.QUIET_LOGGING_LEVEL) else: self.assertEqual(level, -self.config.verbose_count * 10) def test_debug(self): self.config.debug = True self.test_common() def test_quiet(self): self.config.quiet = True self.test_common() class SetupLogFileHandlerTest(test_util.ConfigTestCase): """Tests for certbot.log.setup_log_file_handler.""" @classmethod def _call(cls, *args, **kwargs): from certbot.log import setup_log_file_handler return setup_log_file_handler(*args, **kwargs) def setUp(self): super(SetupLogFileHandlerTest, self).setUp() self.config.max_log_backups = 42 @mock.patch('certbot.main.logging.handlers.RotatingFileHandler') def test_failure(self, mock_handler): mock_handler.side_effect = IOError try: self._call(self.config, 'test.log', '%(message)s') except errors.Error as err: self.assertTrue('--logs-dir' in str(err)) else: # pragma: no cover self.fail('Error not raised.') def test_success_with_rollover(self): self._test_success_common(should_rollover=True) def test_success_without_rollover(self): self.config.max_log_backups = 0 self._test_success_common(should_rollover=False) def _test_success_common(self, should_rollover): log_file = 'test.log' handler, log_path = self._call(self.config, log_file, '%(message)s') handler.close() self.assertEqual(handler.level, logging.DEBUG) self.assertEqual(handler.formatter.converter, time.localtime) expected_path = os.path.join(self.config.logs_dir, log_file) self.assertEqual(log_path, expected_path) backup_path = os.path.join(self.config.logs_dir, log_file + '.1') self.assertEqual(os.path.exists(backup_path), should_rollover) @mock.patch('certbot.log.logging.handlers.RotatingFileHandler') def test_max_log_backups_used(self, mock_handler): self._call(self.config, 'test.log', '%(message)s') backup_count = mock_handler.call_args[1]['backupCount'] self.assertEqual(self.config.max_log_backups, backup_count) class ColoredStreamHandlerTest(unittest.TestCase): """Tests for certbot.log.ColoredStreamHandler""" def setUp(self): self.stream = six.StringIO() self.stream.isatty = lambda: True self.logger = logging.getLogger() self.logger.setLevel(logging.DEBUG) from certbot.log import ColoredStreamHandler self.handler = ColoredStreamHandler(self.stream) self.logger.addHandler(self.handler) def tearDown(self): self.handler.close() def test_format(self): msg = 'I did a thing' self.logger.debug(msg) self.assertEqual(self.stream.getvalue(), '{0}\n'.format(msg)) def test_format_and_red_level(self): msg = 'I did another thing' self.handler.red_level = logging.DEBUG self.logger.debug(msg) self.assertEqual(self.stream.getvalue(), '{0}{1}{2}\n'.format(util.ANSI_SGR_RED, msg, util.ANSI_SGR_RESET)) class MemoryHandlerTest(unittest.TestCase): """Tests for certbot.log.MemoryHandler""" def setUp(self): self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) self.msg = 'hi there' self.stream = six.StringIO() self.stream_handler = logging.StreamHandler(self.stream) from certbot.log import MemoryHandler self.handler = MemoryHandler(self.stream_handler) self.logger.addHandler(self.handler) def tearDown(self): self.handler.close() self.stream_handler.close() def test_flush(self): self._test_log_debug() self.handler.flush(force=True) self.assertEqual(self.stream.getvalue(), self.msg + '\n') def test_not_flushed(self): # By default, logging.ERROR messages and higher are flushed self.logger.critical(self.msg) self.handler.flush() self.assertEqual(self.stream.getvalue(), '') def test_target_reset(self): self._test_log_debug() new_stream = six.StringIO() new_stream_handler = logging.StreamHandler(new_stream) self.handler.setTarget(new_stream_handler) self.handler.flush(force=True) self.assertEqual(self.stream.getvalue(), '') self.assertEqual(new_stream.getvalue(), self.msg + '\n') new_stream_handler.close() def _test_log_debug(self): self.logger.debug(self.msg) class TempHandlerTest(unittest.TestCase): """Tests for certbot.log.TempHandler.""" def setUp(self): self.closed = False from certbot.log import TempHandler self.handler = TempHandler() def tearDown(self): self.handler.close() def test_permissions(self): self.assertTrue( util.check_permissions(self.handler.path, 0o600, os.getuid())) def test_delete(self): self.handler.close() self.assertFalse(os.path.exists(self.handler.path)) def test_no_delete(self): self.handler.emit(mock.MagicMock()) self.handler.close() self.assertTrue(os.path.exists(self.handler.path)) os.remove(self.handler.path) class PreArgParseExceptHookTest(unittest.TestCase): """Tests for certbot.log.pre_arg_parse_except_hook.""" @classmethod def _call(cls, *args, **kwargs): from certbot.log import pre_arg_parse_except_hook return pre_arg_parse_except_hook(*args, **kwargs) @mock.patch('certbot.log.post_arg_parse_except_hook') def test_it(self, mock_post_arg_parse_except_hook): # pylint: disable=star-args memory_handler = mock.MagicMock() args = ('some', 'args',) kwargs = {'some': 'kwargs'} self._call(memory_handler, *args, **kwargs) mock_post_arg_parse_except_hook.assert_called_once_with( *args, **kwargs) memory_handler.flush.assert_called_once_with(force=True) class PostArgParseExceptHookTest(unittest.TestCase): """Tests for certbot.log.post_arg_parse_except_hook.""" @classmethod def _call(cls, *args, **kwargs): from certbot.log import post_arg_parse_except_hook return post_arg_parse_except_hook(*args, **kwargs) def setUp(self): self.error_msg = 'test error message' self.log_path = 'foo.log' def test_base_exception(self): exc_type = KeyboardInterrupt mock_logger, output = self._test_common(exc_type, debug=False) self._assert_exception_logged(mock_logger.error, exc_type) self._assert_logfile_output(output) def test_debug(self): exc_type = ValueError mock_logger, output = self._test_common(exc_type, debug=True) self._assert_exception_logged(mock_logger.error, exc_type) self._assert_logfile_output(output) def test_custom_error(self): exc_type = errors.PluginError mock_logger, output = self._test_common(exc_type, debug=False) self._assert_exception_logged(mock_logger.debug, exc_type) self._assert_quiet_output(mock_logger, output) def test_acme_error(self): # Get an arbitrary error code acme_code = next(six.iterkeys(messages.ERROR_CODES)) def get_acme_error(msg): """Wraps ACME errors so the constructor takes only a msg.""" return messages.Error.with_code(acme_code, detail=msg) mock_logger, output = self._test_common(get_acme_error, debug=False) self._assert_exception_logged(mock_logger.debug, messages.Error) self._assert_quiet_output(mock_logger, output) self.assertFalse(messages.ERROR_PREFIX in output) def test_other_error(self): exc_type = ValueError mock_logger, output = self._test_common(exc_type, debug=False) self._assert_exception_logged(mock_logger.debug, exc_type) self._assert_quiet_output(mock_logger, output) def _test_common(self, error_type, debug): """Returns the mocked logger and stderr output.""" mock_err = six.StringIO() def write_err(*args, **unused_kwargs): """Write error to mock_err.""" mock_err.write(args[0]) try: raise error_type(self.error_msg) except BaseException: exc_info = sys.exc_info() with mock.patch('certbot.log.logger') as mock_logger: mock_logger.error.side_effect = write_err with mock.patch('certbot.log.sys.stderr', mock_err): try: # pylint: disable=star-args self._call( *exc_info, debug=debug, log_path=self.log_path) except SystemExit as exit_err: mock_err.write(str(exit_err)) else: # pragma: no cover self.fail('SystemExit not raised.') output = mock_err.getvalue() return mock_logger, output def _assert_exception_logged(self, log_func, exc_type): self.assertTrue(log_func.called) call_kwargs = log_func.call_args[1] self.assertTrue('exc_info' in call_kwargs) actual_exc_info = call_kwargs['exc_info'] expected_exc_info = (exc_type, mock.ANY, mock.ANY) self.assertEqual(actual_exc_info, expected_exc_info) def _assert_logfile_output(self, output): self.assertTrue('Please see the logfile' in output) self.assertTrue(self.log_path in output) def _assert_quiet_output(self, mock_logger, output): self.assertFalse(mock_logger.exception.called) self.assertTrue(mock_logger.debug.called) self.assertTrue(self.error_msg in output) class ExitWithLogPathTest(test_util.TempDirTestCase): """Tests for certbot.log.exit_with_log_path.""" @classmethod def _call(cls, *args, **kwargs): from certbot.log import exit_with_log_path return exit_with_log_path(*args, **kwargs) def test_log_file(self): log_file = os.path.join(self.tempdir, 'test.log') open(log_file, 'w').close() err_str = self._test_common(log_file) self.assertTrue('logfiles' not in err_str) self.assertTrue(log_file in err_str) def test_log_dir(self): err_str = self._test_common(self.tempdir) self.assertTrue('logfiles' in err_str) self.assertTrue(self.tempdir in err_str) def _test_common(self, *args, **kwargs): try: self._call(*args, **kwargs) except SystemExit as err: return str(err) else: # pragma: no cover self.fail('SystemExit was not raised.') if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/error_handler_test.py0000644000175000017500000001165013344054434022504 0ustar ericaerica00000000000000"""Tests for certbot.error_handler.""" import contextlib import os import signal import sys import unittest import mock # pylint: disable=unused-import, no-name-in-module from acme.magic_typing import Callable, Dict, Union # pylint: enable=unused-import, no-name-in-module def get_signals(signums): """Get the handlers for an iterable of signums.""" return dict((s, signal.getsignal(s)) for s in signums) def set_signals(sig_handler_dict): """Set the signal (keys) with the handler (values) from the input dict.""" for s, h in sig_handler_dict.items(): signal.signal(s, h) @contextlib.contextmanager def signal_receiver(signums): """Context manager to catch signals""" signals = [] prev_handlers = get_signals(signums) # type: Dict[int, Union[int, None, Callable]] set_signals(dict((s, lambda s, _: signals.append(s)) for s in signums)) yield signals set_signals(prev_handlers) def send_signal(signum): """Send the given signal""" os.kill(os.getpid(), signum) class ErrorHandlerTest(unittest.TestCase): """Tests for certbot.error_handler.ErrorHandler.""" def setUp(self): from certbot import error_handler self.init_func = mock.MagicMock() self.init_args = set((42,)) self.init_kwargs = {'foo': 'bar'} self.handler = error_handler.ErrorHandler(self.init_func, *self.init_args, **self.init_kwargs) # pylint: disable=protected-access self.signals = error_handler._SIGNALS def test_context_manager(self): exception_raised = False try: with self.handler: raise ValueError except ValueError: exception_raised = True self.assertTrue(exception_raised) self.init_func.assert_called_once_with(*self.init_args, **self.init_kwargs) def test_context_manager_with_signal(self): init_signals = get_signals(self.signals) with signal_receiver(self.signals) as signals_received: with self.handler: should_be_42 = 42 send_signal(self.signals[0]) should_be_42 *= 10 # check execution stoped when the signal was sent self.assertEqual(42, should_be_42) # assert signals were caught self.assertEqual([self.signals[0]], signals_received) # assert the error handling function was just called once self.init_func.assert_called_once_with(*self.init_args, **self.init_kwargs) for signum in self.signals: self.assertEqual(init_signals[signum], signal.getsignal(signum)) def test_bad_recovery(self): bad_func = mock.MagicMock(side_effect=[ValueError]) self.handler.register(bad_func) try: with self.handler: raise ValueError except ValueError: pass self.init_func.assert_called_once_with(*self.init_args, **self.init_kwargs) bad_func.assert_called_once_with() def test_bad_recovery_with_signal(self): sig1 = self.signals[0] sig2 = self.signals[-1] bad_func = mock.MagicMock(side_effect=lambda: send_signal(sig1)) self.handler.register(bad_func) with signal_receiver(self.signals) as signals_received: with self.handler: send_signal(sig2) self.assertEqual([sig2, sig1], signals_received) self.init_func.assert_called_once_with(*self.init_args, **self.init_kwargs) bad_func.assert_called_once_with() def test_sysexit_ignored(self): try: with self.handler: sys.exit(0) except SystemExit: pass self.assertFalse(self.init_func.called) def test_regular_exit(self): func = mock.MagicMock() self.handler.register(func) with self.handler: pass self.init_func.assert_not_called() func.assert_not_called() class ExitHandlerTest(ErrorHandlerTest): """Tests for certbot.error_handler.ExitHandler.""" def setUp(self): from certbot import error_handler super(ExitHandlerTest, self).setUp() self.handler = error_handler.ExitHandler(self.init_func, *self.init_args, **self.init_kwargs) def test_regular_exit(self): func = mock.MagicMock() self.handler.register(func) with self.handler: pass self.init_func.assert_called_once_with(*self.init_args, **self.init_kwargs) func.assert_called_once_with() if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/acme_util.py0000644000175000017500000000574313344054434020567 0ustar ericaerica00000000000000"""ACME utilities for testing.""" import datetime import josepy as jose import six from acme import challenges from acme import messages from certbot import auth_handler from certbot.tests import util JWK = jose.JWK.load(util.load_vector('rsa512_key.pem')) KEY = util.load_rsa_private_key('rsa512_key.pem') # Challenges HTTP01 = challenges.HTTP01( token=b"evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ+PCt92wr+oA") TLSSNI01 = challenges.TLSSNI01( token=jose.b64decode(b"evaGxfADs6pSRb2LAv9IZf17Dt3juxGJyPCt92wrDoA")) DNS01 = challenges.DNS01(token=b"17817c66b60ce2e4012dfad92657527a") CHALLENGES = [HTTP01, TLSSNI01, DNS01] def gen_combos(challbs): """Generate natural combinations for challbs.""" # completing a single DV challenge satisfies the CA return tuple((i,) for i, _ in enumerate(challbs)) def chall_to_challb(chall, status): # pylint: disable=redefined-outer-name """Return ChallengeBody from Challenge.""" kwargs = { "chall": chall, "uri": chall.typ + "_uri", "status": status, } if status == messages.STATUS_VALID: kwargs.update({"validated": datetime.datetime.now()}) return messages.ChallengeBody(**kwargs) # pylint: disable=star-args # Pending ChallengeBody objects TLSSNI01_P = chall_to_challb(TLSSNI01, messages.STATUS_PENDING) HTTP01_P = chall_to_challb(HTTP01, messages.STATUS_PENDING) DNS01_P = chall_to_challb(DNS01, messages.STATUS_PENDING) CHALLENGES_P = [HTTP01_P, TLSSNI01_P, DNS01_P] # AnnotatedChallenge objects HTTP01_A = auth_handler.challb_to_achall(HTTP01_P, JWK, "example.com") TLSSNI01_A = auth_handler.challb_to_achall(TLSSNI01_P, JWK, "example.net") DNS01_A = auth_handler.challb_to_achall(DNS01_P, JWK, "example.org") ACHALLENGES = [HTTP01_A, TLSSNI01_A, DNS01_A] def gen_authzr(authz_status, domain, challs, statuses, combos=True): """Generate an authorization resource. :param authz_status: Status object :type authz_status: :class:`acme.messages.Status` :param list challs: Challenge objects :param list statuses: status of each challenge object :param bool combos: Whether or not to add combinations """ # pylint: disable=redefined-outer-name challbs = tuple( chall_to_challb(chall, status) for chall, status in six.moves.zip(challs, statuses) ) authz_kwargs = { "identifier": messages.Identifier( typ=messages.IDENTIFIER_FQDN, value=domain), "challenges": challbs, } if combos: authz_kwargs.update({"combinations": gen_combos(challbs)}) if authz_status == messages.STATUS_VALID: authz_kwargs.update({ "status": authz_status, "expires": datetime.datetime.now() + datetime.timedelta(days=31), }) else: authz_kwargs.update({ "status": authz_status, }) # pylint: disable=star-args return messages.AuthorizationResource( uri="https://trusted.ca/new-authz-resource", body=messages.Authorization(**authz_kwargs) ) certbot-0.27.0/certbot/tests/main_test.py0000644000175000017500000024305613344054434020611 0ustar ericaerica00000000000000# coding=utf-8 """Tests for certbot.main.""" # pylint: disable=too-many-lines from __future__ import print_function import itertools import mock import os import shutil import traceback import unittest import datetime import pytz import josepy as jose import six from six.moves import reload_module # pylint: disable=import-error from acme.magic_typing import List # pylint: disable=unused-import, no-name-in-module from certbot import account from certbot import cli from certbot import constants from certbot import configuration from certbot import crypto_util from certbot import errors from certbot import interfaces # pylint: disable=unused-import from certbot import main from certbot import updater from certbot import util from certbot.plugins import disco from certbot.plugins import enhancements from certbot.plugins import manual from certbot.plugins import null import certbot.tests.util as test_util CERT_PATH = test_util.vector_path('cert_512.pem') CERT = test_util.vector_path('cert_512.pem') CSR = test_util.vector_path('csr_512.der') KEY = test_util.vector_path('rsa256_key.pem') JWK = jose.JWKRSA.load(test_util.load_vector('rsa512_key.pem')) RSA2048_KEY_PATH = test_util.vector_path('rsa2048_key.pem') SS_CERT_PATH = test_util.vector_path('cert_2048.pem') class TestHandleIdenticalCerts(unittest.TestCase): """Test for certbot.main._handle_identical_cert_request""" def test_handle_identical_cert_request_pending(self): mock_lineage = mock.Mock() mock_lineage.ensure_deployed.return_value = False # pylint: disable=protected-access ret = main._handle_identical_cert_request(mock.Mock(), mock_lineage) self.assertEqual(ret, ("reinstall", mock_lineage)) class RunTest(test_util.ConfigTestCase): """Tests for certbot.main.run.""" def setUp(self): super(RunTest, self).setUp() self.domain = 'example.org' self.patches = [ mock.patch('certbot.main._get_and_save_cert'), mock.patch('certbot.main.display_ops.success_installation'), mock.patch('certbot.main.display_ops.success_renewal'), mock.patch('certbot.main._init_le_client'), mock.patch('certbot.main._suggest_donation_if_appropriate'), mock.patch('certbot.main._report_new_cert'), mock.patch('certbot.main._find_cert')] self.mock_auth = self.patches[0].start() self.mock_success_installation = self.patches[1].start() self.mock_success_renewal = self.patches[2].start() self.mock_init = self.patches[3].start() self.mock_suggest_donation = self.patches[4].start() self.mock_report_cert = self.patches[5].start() self.mock_find_cert = self.patches[6].start() def tearDown(self): for patch in self.patches: patch.stop() def _call(self): args = '-a webroot -i null -d {0}'.format(self.domain).split() plugins = disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot.main import run run(config, plugins) def test_newcert_success(self): self.mock_auth.return_value = mock.Mock() self.mock_find_cert.return_value = True, None self._call() self.mock_success_installation.assert_called_once_with([self.domain]) def test_reinstall_success(self): self.mock_auth.return_value = mock.Mock() self.mock_find_cert.return_value = False, mock.Mock() self._call() self.mock_success_installation.assert_called_once_with([self.domain]) def test_renewal_success(self): self.mock_auth.return_value = mock.Mock() self.mock_find_cert.return_value = True, mock.Mock() self._call() self.mock_success_renewal.assert_called_once_with([self.domain]) @mock.patch('certbot.main.plug_sel.choose_configurator_plugins') def test_run_enhancement_not_supported(self, mock_choose): mock_choose.return_value = (null.Installer(self.config, "null"), None) plugins = disco.PluginsRegistry.find_all() self.config.auto_hsts = True self.assertRaises(errors.NotSupportedError, main.run, self.config, plugins) class CertonlyTest(unittest.TestCase): """Tests for certbot.main.certonly.""" def setUp(self): self.get_utility_patch = test_util.patch_get_utility() self.mock_get_utility = self.get_utility_patch.start() def tearDown(self): self.get_utility_patch.stop() def _call(self, args): plugins = disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) with mock.patch('certbot.main._init_le_client') as mock_init: with mock.patch('certbot.main._suggest_donation_if_appropriate'): main.certonly(config, plugins) return mock_init() # returns the client @mock.patch('certbot.main._find_cert') @mock.patch('certbot.main._get_and_save_cert') @mock.patch('certbot.main._report_new_cert') def test_no_reinstall_text_pause(self, unused_report, mock_auth, mock_find_cert): mock_notification = self.mock_get_utility().notification mock_notification.side_effect = self._assert_no_pause mock_auth.return_value = mock.Mock() mock_find_cert.return_value = False, None self._call('certonly --webroot -d example.com'.split()) def _assert_no_pause(self, message, pause=True): # pylint: disable=unused-argument self.assertFalse(pause) @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.cert_manager.domains_for_certname') @mock.patch('certbot.renewal.renew_cert') @mock.patch('certbot.main._report_new_cert') def test_find_lineage_for_domains_and_certname(self, mock_report_cert, mock_renew_cert, mock_domains, mock_lineage): domains = ['example.com', 'test.org'] mock_domains.return_value = domains mock_lineage.names.return_value = domains self._call(('certonly --webroot -d example.com -d test.org ' '--cert-name example.com').split()) self.assertTrue(mock_lineage.call_count == 1) self.assertTrue(mock_domains.call_count == 1) self.assertTrue(mock_renew_cert.call_count == 1) self.assertTrue(mock_report_cert.call_count == 1) # user confirms updating lineage with new domains self._call(('certonly --webroot -d example.com -d test.com ' '--cert-name example.com').split()) self.assertTrue(mock_lineage.call_count == 2) self.assertTrue(mock_domains.call_count == 2) self.assertTrue(mock_renew_cert.call_count == 2) self.assertTrue(mock_report_cert.call_count == 2) # error in _ask_user_to_confirm_new_names self.mock_get_utility().yesno.return_value = False self.assertRaises(errors.ConfigurationError, self._call, ('certonly --webroot -d example.com -d test.com --cert-name example.com').split()) @mock.patch('certbot.cert_manager.domains_for_certname') @mock.patch('certbot.display.ops.choose_names') @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.main._report_new_cert') def test_find_lineage_for_domains_new_certname(self, mock_report_cert, mock_lineage, mock_choose_names, mock_domains_for_certname): mock_lineage.return_value = None # no lineage with this name but we specified domains so create a new cert self._call(('certonly --webroot -d example.com -d test.com ' '--cert-name example.com').split()) self.assertTrue(mock_lineage.call_count == 1) self.assertTrue(mock_report_cert.call_count == 1) # no lineage with this name and we didn't give domains mock_choose_names.return_value = ["somename"] mock_domains_for_certname.return_value = None self._call(('certonly --webroot --cert-name example.com').split()) self.assertTrue(mock_choose_names.called) class FindDomainsOrCertnameTest(unittest.TestCase): """Tests for certbot.main._find_domains_or_certname.""" @mock.patch('certbot.display.ops.choose_names') def test_display_ops(self, mock_choose_names): mock_config = mock.Mock(domains=None, certname=None) mock_choose_names.return_value = "domainname" # pylint: disable=protected-access self.assertEqual(main._find_domains_or_certname(mock_config, None), ("domainname", None)) @mock.patch('certbot.display.ops.choose_names') def test_no_results(self, mock_choose_names): mock_config = mock.Mock(domains=None, certname=None) mock_choose_names.return_value = [] # pylint: disable=protected-access self.assertRaises(errors.Error, main._find_domains_or_certname, mock_config, None) @mock.patch('certbot.cert_manager.domains_for_certname') def test_grab_domains(self, mock_domains): mock_config = mock.Mock(domains=None, certname="one.com") mock_domains.return_value = ["one.com", "two.com"] # pylint: disable=protected-access self.assertEqual(main._find_domains_or_certname(mock_config, None), (["one.com", "two.com"], "one.com")) class RevokeTest(test_util.TempDirTestCase): """Tests for certbot.main.revoke.""" def setUp(self): super(RevokeTest, self).setUp() shutil.copy(CERT_PATH, self.tempdir) self.tmp_cert_path = os.path.abspath(os.path.join(self.tempdir, 'cert_512.pem')) self.patches = [ mock.patch('acme.client.BackwardsCompatibleClientV2'), mock.patch('certbot.client.Client'), mock.patch('certbot.main._determine_account'), mock.patch('certbot.main.display_ops.success_revocation') ] self.mock_acme_client = self.patches[0].start() self.patches[1].start() self.mock_determine_account = self.patches[2].start() self.mock_success_revoke = self.patches[3].start() from certbot.account import Account self.regr = mock.MagicMock() self.meta = Account.Meta( creation_host="test.certbot.org", creation_dt=datetime.datetime( 2015, 7, 4, 14, 4, 10, tzinfo=pytz.UTC)) self.acc = Account(self.regr, JWK, self.meta) self.mock_determine_account.return_value = (self.acc, None) def tearDown(self): super(RevokeTest, self).tearDown() for patch in self.patches: patch.stop() def _call(self, extra_args=""): args = 'revoke --cert-path={0} ' + extra_args args = args.format(self.tmp_cert_path).split() plugins = disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot.main import revoke revoke(config, plugins) @mock.patch('certbot.main._delete_if_appropriate') @mock.patch('certbot.main.client.acme_client') def test_revoke_with_reason(self, mock_acme_client, mock_delete_if_appropriate): mock_delete_if_appropriate.return_value = False mock_revoke = mock_acme_client.BackwardsCompatibleClientV2().revoke expected = [] for reason, code in constants.REVOCATION_REASONS.items(): self._call("--reason " + reason) expected.append(mock.call(mock.ANY, code)) self._call("--reason " + reason.upper()) expected.append(mock.call(mock.ANY, code)) self.assertEqual(expected, mock_revoke.call_args_list) @mock.patch('certbot.main._delete_if_appropriate') def test_revocation_success(self, mock_delete_if_appropriate): self._call() mock_delete_if_appropriate.return_value = False self.mock_success_revoke.assert_called_once_with(self.tmp_cert_path) def test_revocation_error(self): from acme import errors as acme_errors self.mock_acme_client.side_effect = acme_errors.ClientError() self.assertRaises(acme_errors.ClientError, self._call) self.mock_success_revoke.assert_not_called() @mock.patch('certbot.main._delete_if_appropriate') @mock.patch('certbot.cert_manager.delete') @test_util.patch_get_utility() def test_revocation_with_prompt(self, mock_get_utility, mock_delete, mock_delete_if_appropriate): mock_get_utility().yesno.return_value = False mock_delete_if_appropriate.return_value = False self._call() self.assertFalse(mock_delete.called) class DeleteIfAppropriateTest(test_util.ConfigTestCase): """Tests for certbot.main._delete_if_appropriate """ def _call(self, mock_config): from certbot.main import _delete_if_appropriate _delete_if_appropriate(mock_config) def _test_delete_opt_out_common(self, mock_get_utility): with mock.patch('certbot.cert_manager.delete') as mock_delete: self._call(self.config) mock_delete.assert_not_called() self.assertTrue(mock_get_utility().add_message.called) @test_util.patch_get_utility() def test_delete_flag_opt_out(self, mock_get_utility): self.config.delete_after_revoke = False self._test_delete_opt_out_common(mock_get_utility) @test_util.patch_get_utility() def test_delete_prompt_opt_out(self, mock_get_utility): util_mock = mock_get_utility() util_mock.yesno.return_value = False self._test_delete_opt_out_common(mock_get_utility) # pylint: disable=too-many-arguments @mock.patch('certbot.storage.renewal_file_for_certname') @mock.patch('certbot.cert_manager.delete') @mock.patch('certbot.cert_manager.match_and_check_overlaps') @mock.patch('certbot.storage.full_archive_path') @mock.patch('certbot.cert_manager.cert_path_to_lineage') @test_util.patch_get_utility() def test_overlapping_archive_dirs(self, mock_get_utility, mock_cert_path_to_lineage, mock_archive, mock_match_and_check_overlaps, mock_delete, mock_renewal_file_for_certname): # pylint: disable = unused-argument config = self.config config.cert_path = "/some/reasonable/path" config.certname = "" mock_cert_path_to_lineage.return_value = "example.com" mock_match_and_check_overlaps.side_effect = errors.OverlappingMatchFound() self._call(config) mock_delete.assert_not_called() # pylint: disable=too-many-arguments @mock.patch('certbot.storage.renewal_file_for_certname') @mock.patch('certbot.cert_manager.match_and_check_overlaps') @mock.patch('certbot.storage.full_archive_path') @mock.patch('certbot.cert_manager.delete') @mock.patch('certbot.storage.cert_path_for_cert_name') @test_util.patch_get_utility() def test_cert_name_only(self, mock_get_utility, mock_cert_path_for_cert_name, mock_delete, mock_archive, mock_overlapping_archive_dirs, mock_renewal_file_for_certname): # pylint: disable = unused-argument config = self.config config.certname = "example.com" config.cert_path = "" mock_cert_path_for_cert_name.return_value = "/some/reasonable/path" mock_overlapping_archive_dirs.return_value = False self._call(config) self.assertEqual(mock_delete.call_count, 1) # pylint: disable=too-many-arguments @mock.patch('certbot.storage.renewal_file_for_certname') @mock.patch('certbot.cert_manager.match_and_check_overlaps') @mock.patch('certbot.storage.full_archive_path') @mock.patch('certbot.cert_manager.delete') @mock.patch('certbot.cert_manager.cert_path_to_lineage') @test_util.patch_get_utility() def test_cert_path_only(self, mock_get_utility, mock_cert_path_to_lineage, mock_delete, mock_archive, mock_overlapping_archive_dirs, mock_renewal_file_for_certname): # pylint: disable = unused-argument config = self.config config.cert_path = "/some/reasonable/path" config.certname = "" mock_cert_path_to_lineage.return_value = "example.com" mock_overlapping_archive_dirs.return_value = False self._call(config) self.assertEqual(mock_delete.call_count, 1) # pylint: disable=too-many-arguments @mock.patch('certbot.storage.renewal_file_for_certname') @mock.patch('certbot.cert_manager.match_and_check_overlaps') @mock.patch('certbot.storage.full_archive_path') @mock.patch('certbot.cert_manager.cert_path_to_lineage') @mock.patch('certbot.cert_manager.delete') @test_util.patch_get_utility() def test_noninteractive_deletion(self, mock_get_utility, mock_delete, mock_cert_path_to_lineage, mock_full_archive_dir, mock_match_and_check_overlaps, mock_renewal_file_for_certname): # pylint: disable = unused-argument config = self.config config.namespace.noninteractive_mode = True config.cert_path = "/some/reasonable/path" config.certname = "" mock_cert_path_to_lineage.return_value = "example.com" mock_full_archive_dir.return_value = "" mock_match_and_check_overlaps.return_value = "" self._call(config) self.assertEqual(mock_delete.call_count, 1) # pylint: disable=too-many-arguments @mock.patch('certbot.storage.renewal_file_for_certname') @mock.patch('certbot.cert_manager.match_and_check_overlaps') @mock.patch('certbot.storage.full_archive_path') @mock.patch('certbot.cert_manager.cert_path_to_lineage') @mock.patch('certbot.cert_manager.delete') @test_util.patch_get_utility() def test_opt_in_deletion(self, mock_get_utility, mock_delete, mock_cert_path_to_lineage, mock_full_archive_dir, mock_match_and_check_overlaps, mock_renewal_file_for_certname): # pylint: disable = unused-argument config = self.config config.namespace.delete_after_revoke = True config.cert_path = "/some/reasonable/path" config.certname = "" mock_cert_path_to_lineage.return_value = "example.com" mock_full_archive_dir.return_value = "" mock_match_and_check_overlaps.return_value = "" self._call(config) self.assertEqual(mock_delete.call_count, 1) self.assertFalse(mock_get_utility().yesno.called) # pylint: disable=too-many-arguments @mock.patch('certbot.storage.renewal_file_for_certname') @mock.patch('certbot.cert_manager.match_and_check_overlaps') @mock.patch('certbot.storage.full_archive_path') @mock.patch('certbot.cert_manager.delete') @mock.patch('certbot.cert_manager.cert_path_to_lineage') @test_util.patch_get_utility() def test_certname_and_cert_path_match(self, mock_get_utility, mock_cert_path_to_lineage, mock_delete, mock_archive, mock_overlapping_archive_dirs, mock_renewal_file_for_certname): # pylint: disable = unused-argument config = self.config config.certname = "example.com" config.cert_path = "/some/reasonable/path" mock_cert_path_to_lineage.return_value = config.certname mock_overlapping_archive_dirs.return_value = False self._call(config) self.assertEqual(mock_delete.call_count, 1) # pylint: disable=too-many-arguments @mock.patch('certbot.cert_manager.match_and_check_overlaps') @mock.patch('certbot.storage.full_archive_path') @mock.patch('certbot.cert_manager.delete') @mock.patch('certbot.cert_manager.human_readable_cert_info') @mock.patch('certbot.storage.RenewableCert') @mock.patch('certbot.storage.renewal_file_for_certname') @mock.patch('certbot.cert_manager.cert_path_to_lineage') @test_util.patch_get_utility() def test_certname_and_cert_path_mismatch(self, mock_get_utility, mock_cert_path_to_lineage, mock_renewal_file_for_certname, mock_RenewableCert, mock_human_readable_cert_info, mock_delete, mock_archive, mock_overlapping_archive_dirs): # pylint: disable=unused-argument config = self.config config.certname = "example.com" config.cert_path = "/some/reasonable/path" mock_cert_path_to_lineage = "something else" mock_RenewableCert.return_value = mock.Mock() mock_human_readable_cert_info.return_value = "" mock_overlapping_archive_dirs.return_value = False from certbot.display import util as display_util util_mock = mock_get_utility() util_mock.menu.return_value = (display_util.OK, 0) self._call(config) self.assertEqual(mock_delete.call_count, 1) # pylint: disable=too-many-arguments @mock.patch('certbot.cert_manager.match_and_check_overlaps') @mock.patch('certbot.storage.full_archive_path') @mock.patch('certbot.cert_manager.delete') @mock.patch('certbot.cert_manager.human_readable_cert_info') @mock.patch('certbot.storage.RenewableCert') @mock.patch('certbot.storage.renewal_file_for_certname') @mock.patch('certbot.cert_manager.cert_path_to_lineage') @test_util.patch_get_utility() def test_noninteractive_certname_cert_path_mismatch(self, mock_get_utility, mock_cert_path_to_lineage, mock_renewal_file_for_certname, mock_RenewableCert, mock_human_readable_cert_info, mock_delete, mock_archive, mock_overlapping_archive_dirs): # pylint: disable=unused-argument config = self.config config.certname = "example.com" config.cert_path = "/some/reasonable/path" mock_cert_path_to_lineage.return_value = "some-reasonable-path.com" mock_RenewableCert.return_value = mock.Mock() mock_human_readable_cert_info.return_value = "" mock_overlapping_archive_dirs.return_value = False # Test for non-interactive mode util_mock = mock_get_utility() util_mock.menu.side_effect = errors.MissingCommandlineFlag("Oh no.") self.assertRaises(errors.Error, self._call, config) mock_delete.assert_not_called() @mock.patch('certbot.cert_manager.delete') @test_util.patch_get_utility() def test_no_certname_or_cert_path(self, mock_get_utility, mock_delete): # pylint: disable=unused-argument config = self.config config.certname = None config.cert_path = None self.assertRaises(errors.Error, self._call, config) mock_delete.assert_not_called() class DetermineAccountTest(test_util.ConfigTestCase): """Tests for certbot.main._determine_account.""" def setUp(self): super(DetermineAccountTest, self).setUp() self.config.account = None self.config.email = None self.config.register_unsafely_without_email = False self.accs = [mock.MagicMock(id='x'), mock.MagicMock(id='y')] self.account_storage = account.AccountMemoryStorage() # For use in saving accounts: fake out the new_authz URL. self.mock_client = mock.MagicMock() self.mock_client.directory.new_authz = "hi" def _call(self): # pylint: disable=protected-access from certbot.main import _determine_account with mock.patch('certbot.main.account.AccountFileStorage') as mock_storage: mock_storage.return_value = self.account_storage return _determine_account(self.config) def test_args_account_set(self): self.account_storage.save(self.accs[1], self.mock_client) self.config.account = self.accs[1].id self.assertEqual((self.accs[1], None), self._call()) self.assertEqual(self.accs[1].id, self.config.account) self.assertTrue(self.config.email is None) def test_single_account(self): self.account_storage.save(self.accs[0], self.mock_client) self.assertEqual((self.accs[0], None), self._call()) self.assertEqual(self.accs[0].id, self.config.account) self.assertTrue(self.config.email is None) @mock.patch('certbot.client.display_ops.choose_account') def test_multiple_accounts(self, mock_choose_accounts): for acc in self.accs: self.account_storage.save(acc, self.mock_client) mock_choose_accounts.return_value = self.accs[1] self.assertEqual((self.accs[1], None), self._call()) self.assertEqual( set(mock_choose_accounts.call_args[0][0]), set(self.accs)) self.assertEqual(self.accs[1].id, self.config.account) self.assertTrue(self.config.email is None) @mock.patch('certbot.client.display_ops.get_email') def test_no_accounts_no_email(self, mock_get_email): mock_get_email.return_value = 'foo@bar.baz' with mock.patch('certbot.main.client') as client: client.register.return_value = ( self.accs[0], mock.sentinel.acme) self.assertEqual((self.accs[0], mock.sentinel.acme), self._call()) client.register.assert_called_once_with( self.config, self.account_storage, tos_cb=mock.ANY) self.assertEqual(self.accs[0].id, self.config.account) self.assertEqual('foo@bar.baz', self.config.email) def test_no_accounts_email(self): self.config.email = 'other email' with mock.patch('certbot.main.client') as client: client.register.return_value = (self.accs[1], mock.sentinel.acme) self._call() self.assertEqual(self.accs[1].id, self.config.account) self.assertEqual('other email', self.config.email) class MainTest(test_util.ConfigTestCase): # pylint: disable=too-many-public-methods """Tests for different commands.""" def setUp(self): super(MainTest, self).setUp() os.mkdir(self.config.logs_dir) self.standard_args = ['--config-dir', self.config.config_dir, '--work-dir', self.config.work_dir, '--logs-dir', self.config.logs_dir, '--text'] def tearDown(self): # Reset globals in cli reload_module(cli) super(MainTest, self).tearDown() def _call(self, args, stdout=None, mockisfile=False): """Run the cli with output streams, actual client and optionally os.path.isfile() mocked out""" if mockisfile: orig_open = os.path.isfile def mock_isfile(fn, *args, **kwargs): # pylint: disable=unused-argument """Mock os.path.isfile()""" if (fn.endswith("cert") or fn.endswith("chain") or fn.endswith("privkey")): return True else: return orig_open(fn) with mock.patch("os.path.isfile") as mock_if: mock_if.side_effect = mock_isfile with mock.patch('certbot.main.client') as client: ret, stdout, stderr = self._call_no_clientmock(args, stdout) return ret, stdout, stderr, client else: with mock.patch('certbot.main.client') as client: ret, stdout, stderr = self._call_no_clientmock(args, stdout) return ret, stdout, stderr, client def _call_no_clientmock(self, args, stdout=None): "Run the client with output streams mocked out" args = self.standard_args + args toy_stdout = stdout if stdout else six.StringIO() with mock.patch('certbot.main.sys.stdout', new=toy_stdout): with mock.patch('certbot.main.sys.stderr') as stderr: with mock.patch("certbot.util.atexit"): ret = main.main(args[:]) # NOTE: parser can alter its args! return ret, toy_stdout, stderr def test_no_flags(self): with mock.patch('certbot.main.run') as mock_run: self._call([]) self.assertEqual(1, mock_run.call_count) def test_version_string_program_name(self): toy_out = six.StringIO() toy_err = six.StringIO() with mock.patch('certbot.main.sys.stdout', new=toy_out): with mock.patch('certbot.main.sys.stderr', new=toy_err): try: main.main(["--version"]) except SystemExit: pass finally: output = toy_out.getvalue() or toy_err.getvalue() self.assertTrue("certbot" in output, "Output is {0}".format(output)) def _cli_missing_flag(self, args, message): "Ensure that a particular error raises a missing cli flag error containing message" exc = None try: with mock.patch('certbot.main.sys.stderr'): main.main(self.standard_args + args[:]) # NOTE: parser can alter its args! except errors.MissingCommandlineFlag as exc_: exc = exc_ self.assertTrue(message in str(exc)) self.assertTrue(exc is not None) def test_noninteractive(self): args = ['-n', 'certonly'] self._cli_missing_flag(args, "specify a plugin") args.extend(['--standalone', '-d', 'eg.is']) self._cli_missing_flag(args, "register before running") @mock.patch('certbot.main._report_new_cert') @mock.patch('certbot.main.client.acme_client.Client') @mock.patch('certbot.main._determine_account') @mock.patch('certbot.main.client.Client.obtain_and_enroll_certificate') @mock.patch('certbot.main._get_and_save_cert') def test_user_agent(self, gsc, _obt, det, _client, unused_report): # Normally the client is totally mocked out, but here we need more # arguments to automate it... args = ["--standalone", "certonly", "-m", "none@none.com", "-d", "example.com", '--agree-tos'] + self.standard_args det.return_value = mock.MagicMock(), None gsc.return_value = mock.MagicMock() with mock.patch('certbot.main.client.acme_client.ClientNetwork') as acme_net: self._call_no_clientmock(args) os_ver = util.get_os_info_ua() ua = acme_net.call_args[1]["user_agent"] self.assertTrue(os_ver in ua) import platform plat = platform.platform() if "linux" in plat.lower(): self.assertTrue(util.get_os_info_ua() in ua) with mock.patch('certbot.main.client.acme_client.ClientNetwork') as acme_net: ua = "bandersnatch" args += ["--user-agent", ua] self._call_no_clientmock(args) acme_net.assert_called_once_with(mock.ANY, account=mock.ANY, verify_ssl=True, user_agent=ua) @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @mock.patch('certbot.main.plug_sel.pick_installer') def test_installer_selection(self, mock_pick_installer, _rec): self._call(['install', '--domains', 'foo.bar', '--cert-path', 'cert', '--key-path', 'privkey', '--chain-path', 'chain'], mockisfile=True) self.assertEqual(mock_pick_installer.call_count, 1) @mock.patch('certbot.main._install_cert') @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @mock.patch('certbot.main.plug_sel.pick_installer') def test_installer_certname(self, _inst, _rec, mock_install): mock_lineage = mock.MagicMock(cert_path="/tmp/cert", chain_path="/tmp/chain", fullchain_path="/tmp/chain", key_path="/tmp/privkey") with mock.patch("certbot.cert_manager.lineage_for_certname") as mock_getlin: mock_getlin.return_value = mock_lineage self._call(['install', '--cert-name', 'whatever'], mockisfile=True) call_config = mock_install.call_args[0][0] self.assertEqual(call_config.cert_path, "/tmp/cert") self.assertEqual(call_config.fullchain_path, "/tmp/chain") self.assertEqual(call_config.key_path, "/tmp/privkey") @mock.patch('certbot.main._install_cert') @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @mock.patch('certbot.main.plug_sel.pick_installer') def test_installer_param_override(self, _inst, _rec, mock_install): mock_lineage = mock.MagicMock(cert_path="/tmp/cert", chain_path="/tmp/chain", fullchain_path="/tmp/chain", key_path="/tmp/privkey") with mock.patch("certbot.cert_manager.lineage_for_certname") as mock_getlin: mock_getlin.return_value = mock_lineage self._call(['install', '--cert-name', 'whatever', '--key-path', '/tmp/overriding_privkey'], mockisfile=True) call_config = mock_install.call_args[0][0] self.assertEqual(call_config.cert_path, "/tmp/cert") self.assertEqual(call_config.fullchain_path, "/tmp/chain") self.assertEqual(call_config.chain_path, "/tmp/chain") self.assertEqual(call_config.key_path, "/tmp/overriding_privkey") mock_install.reset() self._call(['install', '--cert-name', 'whatever', '--cert-path', '/tmp/overriding_cert'], mockisfile=True) call_config = mock_install.call_args[0][0] self.assertEqual(call_config.cert_path, "/tmp/overriding_cert") self.assertEqual(call_config.fullchain_path, "/tmp/chain") self.assertEqual(call_config.key_path, "/tmp/privkey") @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @mock.patch('certbot.main.plug_sel.pick_installer') def test_installer_param_error(self, _inst, _rec): self.assertRaises(errors.ConfigurationError, self._call, ['install', '--cert-name', 'notfound', '--key-path', 'invalid']) @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @mock.patch('certbot.main.plug_sel.pick_installer') @mock.patch('certbot.cert_manager.get_certnames') @mock.patch('certbot.main._install_cert') def test_installer_select_cert(self, mock_inst, mock_getcert, _inst, _rec): mock_lineage = mock.MagicMock(cert_path="/tmp/cert", chain_path="/tmp/chain", fullchain_path="/tmp/chain", key_path="/tmp/privkey") with mock.patch("certbot.cert_manager.lineage_for_certname") as mock_getlin: mock_getlin.return_value = mock_lineage self._call(['install'], mockisfile=True) self.assertTrue(mock_getcert.called) self.assertTrue(mock_inst.called) @mock.patch('certbot.main._report_new_cert') @mock.patch('certbot.util.exe_exists') def test_configurator_selection(self, mock_exe_exists, unused_report): mock_exe_exists.return_value = True real_plugins = disco.PluginsRegistry.find_all() args = ['--apache', '--authenticator', 'standalone'] # This needed two calls to find_all(), which we're avoiding for now # because of possible side effects: # https://github.com/letsencrypt/letsencrypt/commit/51ed2b681f87b1eb29088dd48718a54f401e4855 #with mock.patch('certbot.cli.plugins_testable') as plugins: # plugins.return_value = {"apache": True, "nginx": True} # ret, _, _, _ = self._call(args) # self.assertTrue("Too many flags setting" in ret) args = ["install", "--nginx", "--cert-path", "/tmp/blah", "--key-path", "/tmp/blah", "--nginx-server-root", "/nonexistent/thing", "-d", "example.com", "--debug"] if "nginx" in real_plugins: # Sending nginx a non-existent conf dir will simulate misconfiguration # (we can only do that if certbot-nginx is actually present) ret, _, _, _ = self._call(args) self.assertTrue("The nginx plugin is not working" in ret) self.assertTrue("MisconfigurationError" in ret) self._cli_missing_flag(["--standalone"], "With the standalone plugin, you probably") with mock.patch("certbot.main._init_le_client") as mock_init: with mock.patch("certbot.main._get_and_save_cert") as mock_gsc: mock_gsc.return_value = mock.MagicMock() self._call(["certonly", "--manual", "-d", "foo.bar"]) unused_config, auth, unused_installer = mock_init.call_args[0] self.assertTrue(isinstance(auth, manual.Authenticator)) with mock.patch('certbot.main.certonly') as mock_certonly: self._call(["auth", "--standalone"]) self.assertEqual(1, mock_certonly.call_count) def test_rollback(self): _, _, _, client = self._call(['rollback']) self.assertEqual(1, client.rollback.call_count) _, _, _, client = self._call(['rollback', '--checkpoints', '123']) client.rollback.assert_called_once_with( mock.ANY, 123, mock.ANY, mock.ANY) def test_config_changes(self): _, _, _, client = self._call(['config_changes']) self.assertEqual(1, client.view_config_changes.call_count) @mock.patch('certbot.cert_manager.update_live_symlinks') def test_update_symlinks(self, mock_cert_manager): self._call_no_clientmock(['update_symlinks']) self.assertEqual(1, mock_cert_manager.call_count) @mock.patch('certbot.cert_manager.certificates') def test_certificates(self, mock_cert_manager): self._call_no_clientmock(['certificates']) self.assertEqual(1, mock_cert_manager.call_count) @mock.patch('certbot.cert_manager.delete') def test_delete(self, mock_cert_manager): self._call_no_clientmock(['delete']) self.assertEqual(1, mock_cert_manager.call_count) def test_plugins(self): flags = ['--init', '--prepare', '--authenticators', '--installers'] for args in itertools.chain( *(itertools.combinations(flags, r) for r in six.moves.range(len(flags)))): self._call(['plugins'] + list(args)) @mock.patch('certbot.main.plugins_disco') @mock.patch('certbot.main.cli.HelpfulArgumentParser.determine_help_topics') def test_plugins_no_args(self, _det, mock_disco): ifaces = [] # type: List[interfaces.IPlugin] plugins = mock_disco.PluginsRegistry.find_all() stdout = six.StringIO() with test_util.patch_get_utility_with_stdout(stdout=stdout): _, stdout, _, _ = self._call(['plugins'], stdout) plugins.visible.assert_called_once_with() plugins.visible().ifaces.assert_called_once_with(ifaces) filtered = plugins.visible().ifaces() self.assertEqual(stdout.getvalue().strip(), str(filtered)) @mock.patch('certbot.main.plugins_disco') @mock.patch('certbot.main.cli.HelpfulArgumentParser.determine_help_topics') def test_plugins_no_args_unprivileged(self, _det, mock_disco): ifaces = [] # type: List[interfaces.IPlugin] plugins = mock_disco.PluginsRegistry.find_all() def throw_error(directory, mode, uid, strict): """Raises error.Error.""" _, _, _, _ = directory, mode, uid, strict raise errors.Error() stdout = six.StringIO() with mock.patch('certbot.util.set_up_core_dir') as mock_set_up_core_dir: with test_util.patch_get_utility_with_stdout(stdout=stdout): mock_set_up_core_dir.side_effect = throw_error _, stdout, _, _ = self._call(['plugins'], stdout) plugins.visible.assert_called_once_with() plugins.visible().ifaces.assert_called_once_with(ifaces) filtered = plugins.visible().ifaces() self.assertEqual(stdout.getvalue().strip(), str(filtered)) @mock.patch('certbot.main.plugins_disco') @mock.patch('certbot.main.cli.HelpfulArgumentParser.determine_help_topics') def test_plugins_init(self, _det, mock_disco): ifaces = [] # type: List[interfaces.IPlugin] plugins = mock_disco.PluginsRegistry.find_all() stdout = six.StringIO() with test_util.patch_get_utility_with_stdout(stdout=stdout): _, stdout, _, _ = self._call(['plugins', '--init'], stdout) plugins.visible.assert_called_once_with() plugins.visible().ifaces.assert_called_once_with(ifaces) filtered = plugins.visible().ifaces() self.assertEqual(filtered.init.call_count, 1) filtered.verify.assert_called_once_with(ifaces) verified = filtered.verify() self.assertEqual(stdout.getvalue().strip(), str(verified)) @mock.patch('certbot.main.plugins_disco') @mock.patch('certbot.main.cli.HelpfulArgumentParser.determine_help_topics') def test_plugins_prepare(self, _det, mock_disco): ifaces = [] # type: List[interfaces.IPlugin] plugins = mock_disco.PluginsRegistry.find_all() stdout = six.StringIO() with test_util.patch_get_utility_with_stdout(stdout=stdout): _, stdout, _, _ = self._call(['plugins', '--init', '--prepare'], stdout) plugins.visible.assert_called_once_with() plugins.visible().ifaces.assert_called_once_with(ifaces) filtered = plugins.visible().ifaces() self.assertEqual(filtered.init.call_count, 1) filtered.verify.assert_called_once_with(ifaces) verified = filtered.verify() verified.prepare.assert_called_once_with() verified.available.assert_called_once_with() available = verified.available() self.assertEqual(stdout.getvalue().strip(), str(available)) def test_certonly_abspath(self): cert = 'cert' key = 'key' chain = 'chain' fullchain = 'fullchain' with mock.patch('certbot.main.certonly') as mock_certonly: self._call(['certonly', '--cert-path', cert, '--key-path', 'key', '--chain-path', 'chain', '--fullchain-path', 'fullchain']) config, unused_plugins = mock_certonly.call_args[0] self.assertEqual(config.cert_path, os.path.abspath(cert)) self.assertEqual(config.key_path, os.path.abspath(key)) self.assertEqual(config.chain_path, os.path.abspath(chain)) self.assertEqual(config.fullchain_path, os.path.abspath(fullchain)) def test_certonly_bad_args(self): try: self._call(['-a', 'bad_auth', 'certonly']) assert False, "Exception should have been raised" except errors.PluginSelectionError as e: self.assertTrue('The requested bad_auth plugin does not appear' in str(e)) def test_check_config_sanity_domain(self): # FQDN self.assertRaises(errors.ConfigurationError, self._call, ['-d', 'a' * 64]) # FQDN 2 self.assertRaises(errors.ConfigurationError, self._call, ['-d', (('a' * 50) + '.') * 10]) # Bare IP address (this is actually a different error message now) self.assertRaises(errors.ConfigurationError, self._call, ['-d', '204.11.231.35']) def test_csr_with_besteffort(self): self.assertRaises( errors.Error, self._call, 'certonly --csr {0} --allow-subset-of-names'.format(CSR).split()) def test_run_with_csr(self): # This is an error because you can only use --csr with certonly try: self._call(['--csr', CSR]) except errors.Error as e: assert "Please try the certonly" in repr(e) return assert False, "Expected supplying --csr to fail with default verb" def test_csr_with_no_domains(self): self.assertRaises( errors.Error, self._call, 'certonly --csr {0}'.format( test_util.vector_path('csr-nonames_512.pem')).split()) def test_csr_with_inconsistent_domains(self): self.assertRaises( errors.Error, self._call, 'certonly -d example.org --csr {0}'.format(CSR).split()) def _certonly_new_request_common(self, mock_client, args=None): with mock.patch('certbot.main._find_lineage_for_domains_and_certname') as mock_renewal: mock_renewal.return_value = ("newcert", None) with mock.patch('certbot.main._init_le_client') as mock_init: mock_init.return_value = mock_client if args is None: args = [] args += '-d foo.bar -a standalone certonly'.split() self._call(args) @test_util.patch_get_utility() def test_certonly_dry_run_new_request_success(self, mock_get_utility): mock_client = mock.MagicMock() mock_client.obtain_and_enroll_certificate.return_value = None self._certonly_new_request_common(mock_client, ['--dry-run']) self.assertEqual( mock_client.obtain_and_enroll_certificate.call_count, 1) self.assertTrue( 'dry run' in mock_get_utility().add_message.call_args[0][0]) # Asserts we don't suggest donating after a successful dry run self.assertEqual(mock_get_utility().add_message.call_count, 1) @mock.patch('certbot.crypto_util.notAfter') @test_util.patch_get_utility() def test_certonly_new_request_success(self, mock_get_utility, mock_notAfter): cert_path = '/etc/letsencrypt/live/foo.bar' key_path = '/etc/letsencrypt/live/baz.qux' date = '1970-01-01' mock_notAfter().date.return_value = date mock_lineage = mock.MagicMock(cert=cert_path, fullchain=cert_path, fullchain_path=cert_path, key_path=key_path) mock_client = mock.MagicMock() mock_client.obtain_and_enroll_certificate.return_value = mock_lineage self._certonly_new_request_common(mock_client) self.assertEqual( mock_client.obtain_and_enroll_certificate.call_count, 1) cert_msg = mock_get_utility().add_message.call_args_list[0][0][0] self.assertTrue(cert_path in cert_msg) self.assertTrue(date in cert_msg) self.assertTrue(key_path in cert_msg) self.assertTrue( 'donate' in mock_get_utility().add_message.call_args[0][0]) def test_certonly_new_request_failure(self): mock_client = mock.MagicMock() mock_client.obtain_and_enroll_certificate.return_value = False self.assertRaises(errors.Error, self._certonly_new_request_common, mock_client) def _test_renewal_common(self, due_for_renewal, extra_args, log_out=None, args=None, should_renew=True, error_expected=False, quiet_mode=False, expiry_date=datetime.datetime.now(), reuse_key=False): # pylint: disable=too-many-locals,too-many-arguments,too-many-branches cert_path = test_util.vector_path('cert_512.pem') chain_path = '/etc/letsencrypt/live/foo.bar/fullchain.pem' mock_lineage = mock.MagicMock(cert=cert_path, fullchain=chain_path, cert_path=cert_path, fullchain_path=chain_path) mock_lineage.should_autorenew.return_value = due_for_renewal mock_lineage.has_pending_deployment.return_value = False mock_lineage.names.return_value = ['isnot.org'] mock_certr = mock.MagicMock() mock_key = mock.MagicMock(pem='pem_key') mock_client = mock.MagicMock() stdout = six.StringIO() mock_client.obtain_certificate.return_value = (mock_certr, 'chain', mock_key, 'csr') def write_msg(message, *args, **kwargs): # pylint: disable=unused-argument """Write message to stdout.""" stdout.write(message) try: with mock.patch('certbot.cert_manager.find_duplicative_certs') as mock_fdc: mock_fdc.return_value = (mock_lineage, None) with mock.patch('certbot.main._init_le_client') as mock_init: mock_init.return_value = mock_client with test_util.patch_get_utility() as mock_get_utility: if not quiet_mode: mock_get_utility().notification.side_effect = write_msg with mock.patch('certbot.main.renewal.OpenSSL') as mock_ssl: mock_latest = mock.MagicMock() mock_latest.get_issuer.return_value = "Fake fake" mock_ssl.crypto.load_certificate.return_value = mock_latest with mock.patch('certbot.main.renewal.crypto_util') as mock_crypto_util: mock_crypto_util.notAfter.return_value = expiry_date if not args: args = ['-d', 'isnot.org', '-a', 'standalone', 'certonly'] if extra_args: args += extra_args try: ret, stdout, _, _ = self._call(args, stdout) if ret: print("Returned", ret) raise AssertionError(ret) assert not error_expected, "renewal should have errored" except: # pylint: disable=bare-except if not error_expected: raise AssertionError( "Unexpected renewal error:\n" + traceback.format_exc()) if should_renew: if reuse_key: # The location of the previous live privkey.pem is passed # to obtain_certificate mock_client.obtain_certificate.assert_called_once_with(['isnot.org'], os.path.join(self.config.config_dir, "live/sample-renewal/privkey.pem")) else: mock_client.obtain_certificate.assert_called_once_with(['isnot.org'], None) else: self.assertEqual(mock_client.obtain_certificate.call_count, 0) except: self._dump_log() raise finally: if log_out: with open(os.path.join(self.config.logs_dir, "letsencrypt.log")) as lf: self.assertTrue(log_out in lf.read()) return mock_lineage, mock_get_utility, stdout @mock.patch('certbot.crypto_util.notAfter') def test_certonly_renewal(self, unused_notafter): lineage, get_utility, _ = self._test_renewal_common(True, []) self.assertEqual(lineage.save_successor.call_count, 1) lineage.update_all_links_to.assert_called_once_with( lineage.latest_common_version()) cert_msg = get_utility().add_message.call_args_list[0][0][0] self.assertTrue('fullchain.pem' in cert_msg) self.assertTrue('donate' in get_utility().add_message.call_args[0][0]) @mock.patch('certbot.crypto_util.notAfter') def test_certonly_renewal_triggers(self, unused_notafter): # --dry-run should force renewal _, get_utility, _ = self._test_renewal_common(False, ['--dry-run', '--keep'], log_out="simulating renewal") self.assertEqual(get_utility().add_message.call_count, 1) self.assertTrue('dry run' in get_utility().add_message.call_args[0][0]) self._test_renewal_common(False, ['--renew-by-default', '-tvv', '--debug'], log_out="Auto-renewal forced") self.assertEqual(get_utility().add_message.call_count, 1) self._test_renewal_common(False, ['-tvv', '--debug', '--keep'], log_out="not yet due", should_renew=False) def _dump_log(self): print("Logs:") log_path = os.path.join(self.config.logs_dir, "letsencrypt.log") if os.path.exists(log_path): with open(log_path) as lf: print(lf.read()) def test_renew_verb(self): test_util.make_lineage(self.config.config_dir, 'sample-renewal.conf') args = ["renew", "--dry-run", "-tvv"] self._test_renewal_common(True, [], args=args, should_renew=True) def test_reuse_key(self): test_util.make_lineage(self.config.config_dir, 'sample-renewal.conf') args = ["renew", "--dry-run", "--reuse-key"] self._test_renewal_common(True, [], args=args, should_renew=True, reuse_key=True) @mock.patch('certbot.storage.RenewableCert.save_successor') def test_reuse_key_no_dry_run(self, unused_save_successor): test_util.make_lineage(self.config.config_dir, 'sample-renewal.conf') args = ["renew", "--reuse-key"] self._test_renewal_common(True, [], args=args, should_renew=True, reuse_key=True) @mock.patch('certbot.renewal.should_renew') def test_renew_skips_recent_certs(self, should_renew): should_renew.return_value = False test_util.make_lineage(self.config.config_dir, 'sample-renewal.conf') expiry = datetime.datetime.now() + datetime.timedelta(days=90) _, _, stdout = self._test_renewal_common(False, extra_args=None, should_renew=False, args=['renew'], expiry_date=expiry) self.assertTrue('No renewals were attempted.' in stdout.getvalue()) self.assertTrue('The following certs are not due for renewal yet:' in stdout.getvalue()) def test_quiet_renew(self): test_util.make_lineage(self.config.config_dir, 'sample-renewal.conf') args = ["renew", "--dry-run"] _, _, stdout = self._test_renewal_common(True, [], args=args, should_renew=True) out = stdout.getvalue() self.assertTrue("renew" in out) args = ["renew", "--dry-run", "-q"] _, _, stdout = self._test_renewal_common(True, [], args=args, should_renew=True, quiet_mode=True) out = stdout.getvalue() self.assertEqual("", out) def test_renew_hook_validation(self): test_util.make_lineage(self.config.config_dir, 'sample-renewal.conf') args = ["renew", "--dry-run", "--post-hook=no-such-command"] self._test_renewal_common(True, [], args=args, should_renew=False, error_expected=True) def test_renew_no_hook_validation(self): test_util.make_lineage(self.config.config_dir, 'sample-renewal.conf') args = ["renew", "--dry-run", "--post-hook=no-such-command", "--disable-hook-validation"] with mock.patch("certbot.hooks.post_hook"): self._test_renewal_common(True, [], args=args, should_renew=True, error_expected=False) def test_renew_verb_empty_config(self): rd = os.path.join(self.config.config_dir, 'renewal') if not os.path.exists(rd): os.makedirs(rd) with open(os.path.join(rd, 'empty.conf'), 'w'): pass # leave the file empty args = ["renew", "--dry-run", "-tvv"] self._test_renewal_common(False, [], args=args, should_renew=False, error_expected=True) def test_renew_with_certname(self): test_util.make_lineage(self.config.config_dir, 'sample-renewal.conf') self._test_renewal_common(True, [], should_renew=True, args=['renew', '--dry-run', '--cert-name', 'sample-renewal']) def test_renew_with_bad_certname(self): self._test_renewal_common(True, [], should_renew=False, args=['renew', '--dry-run', '--cert-name', 'sample-renewal'], error_expected=True) def _make_dummy_renewal_config(self): renewer_configs_dir = os.path.join(self.config.config_dir, 'renewal') os.makedirs(renewer_configs_dir) with open(os.path.join(renewer_configs_dir, 'test.conf'), 'w') as f: f.write("My contents don't matter") def _test_renew_common(self, renewalparams=None, names=None, assert_oc_called=None, **kwargs): self._make_dummy_renewal_config() with mock.patch('certbot.storage.RenewableCert') as mock_rc: mock_lineage = mock.MagicMock() mock_lineage.fullchain = "somepath/fullchain.pem" if renewalparams is not None: mock_lineage.configuration = {'renewalparams': renewalparams} if names is not None: mock_lineage.names.return_value = names mock_rc.return_value = mock_lineage with mock.patch('certbot.main.renew_cert') as mock_renew_cert: kwargs.setdefault('args', ['renew']) self._test_renewal_common(True, None, should_renew=False, **kwargs) if assert_oc_called is not None: if assert_oc_called: self.assertTrue(mock_renew_cert.called) else: self.assertFalse(mock_renew_cert.called) def test_renew_no_renewalparams(self): self._test_renew_common(assert_oc_called=False, error_expected=True) def test_renew_no_authenticator(self): self._test_renew_common(renewalparams={}, assert_oc_called=False, error_expected=True) def test_renew_with_bad_int(self): renewalparams = {'authenticator': 'webroot', 'rsa_key_size': 'over 9000'} self._test_renew_common(renewalparams=renewalparams, error_expected=True, assert_oc_called=False) def test_renew_with_nonetype_http01(self): renewalparams = {'authenticator': 'webroot', 'http01_port': 'None'} self._test_renew_common(renewalparams=renewalparams, assert_oc_called=True) def test_renew_with_bad_domain(self): renewalparams = {'authenticator': 'webroot'} names = ['uniçodé.com'] self._test_renew_common(renewalparams=renewalparams, error_expected=True, names=names, assert_oc_called=False) @mock.patch('certbot.plugins.selection.choose_configurator_plugins') def test_renew_with_configurator(self, mock_sel): mock_sel.return_value = (mock.MagicMock(), mock.MagicMock()) renewalparams = {'authenticator': 'webroot'} self._test_renew_common( renewalparams=renewalparams, assert_oc_called=True, args='renew --configurator apache'.split()) def test_renew_plugin_config_restoration(self): renewalparams = {'authenticator': 'webroot', 'webroot_path': 'None', 'webroot_imaginary_flag': '42'} self._test_renew_common(renewalparams=renewalparams, assert_oc_called=True) def test_renew_with_webroot_map(self): renewalparams = {'authenticator': 'webroot'} self._test_renew_common( renewalparams=renewalparams, assert_oc_called=True, args=['renew', '--webroot-map', '{"example.com": "/tmp"}']) def test_renew_reconstitute_error(self): # pylint: disable=protected-access with mock.patch('certbot.main.renewal._reconstitute') as mock_reconstitute: mock_reconstitute.side_effect = Exception self._test_renew_common(assert_oc_called=False, error_expected=True) def test_renew_obtain_cert_error(self): self._make_dummy_renewal_config() with mock.patch('certbot.storage.RenewableCert') as mock_rc: mock_lineage = mock.MagicMock() mock_lineage.fullchain = "somewhere/fullchain.pem" mock_rc.return_value = mock_lineage mock_lineage.configuration = { 'renewalparams': {'authenticator': 'webroot'}} with mock.patch('certbot.main.renew_cert') as mock_renew_cert: mock_renew_cert.side_effect = Exception self._test_renewal_common(True, None, error_expected=True, args=['renew'], should_renew=False) def test_renew_with_bad_cli_args(self): self._test_renewal_common(True, None, args='renew -d example.com'.split(), should_renew=False, error_expected=True) self._test_renewal_common(True, None, args='renew --csr {0}'.format(CSR).split(), should_renew=False, error_expected=True) def test_no_renewal_with_hooks(self): _, _, stdout = self._test_renewal_common( due_for_renewal=False, extra_args=None, should_renew=False, args=['renew', '--post-hook', 'echo hello world']) self.assertTrue('No hooks were run.' in stdout.getvalue()) @test_util.patch_get_utility() @mock.patch('certbot.main._find_lineage_for_domains_and_certname') @mock.patch('certbot.main._init_le_client') def test_certonly_reinstall(self, mock_init, mock_renewal, mock_get_utility): mock_renewal.return_value = ('reinstall', mock.MagicMock()) mock_init.return_value = mock_client = mock.MagicMock() self._call(['-d', 'foo.bar', '-a', 'standalone', 'certonly']) self.assertFalse(mock_client.obtain_certificate.called) self.assertFalse(mock_client.obtain_and_enroll_certificate.called) self.assertEqual(mock_get_utility().add_message.call_count, 0) #self.assertTrue('donate' not in mock_get_utility().add_message.call_args[0][0]) def _test_certonly_csr_common(self, extra_args=None): certr = 'certr' chain = 'chain' mock_client = mock.MagicMock() mock_client.obtain_certificate_from_csr.return_value = (certr, chain) cert_path = '/etc/letsencrypt/live/example.com/cert_512.pem' full_path = '/etc/letsencrypt/live/example.com/fullchain.pem' mock_client.save_certificate.return_value = cert_path, None, full_path with mock.patch('certbot.main._init_le_client') as mock_init: mock_init.return_value = mock_client with test_util.patch_get_utility() as mock_get_utility: chain_path = '/etc/letsencrypt/live/example.com/chain.pem' args = ('-a standalone certonly --csr {0} --cert-path {1} ' '--chain-path {2} --fullchain-path {3}').format( CSR, cert_path, chain_path, full_path).split() if extra_args: args += extra_args with mock.patch('certbot.main.crypto_util'): self._call(args) if '--dry-run' in args: self.assertFalse(mock_client.save_certificate.called) else: mock_client.save_certificate.assert_called_once_with( certr, chain, cert_path, chain_path, full_path) return mock_get_utility def test_certonly_csr(self): mock_get_utility = self._test_certonly_csr_common() cert_msg = mock_get_utility().add_message.call_args_list[0][0][0] self.assertTrue('fullchain.pem' in cert_msg) self.assertFalse('Your key file has been saved at' in cert_msg) self.assertTrue( 'donate' in mock_get_utility().add_message.call_args[0][0]) def test_certonly_csr_dry_run(self): mock_get_utility = self._test_certonly_csr_common(['--dry-run']) self.assertEqual(mock_get_utility().add_message.call_count, 1) self.assertTrue( 'dry run' in mock_get_utility().add_message.call_args[0][0]) @mock.patch('certbot.main._delete_if_appropriate') @mock.patch('certbot.main.client.acme_client') def test_revoke_with_key(self, mock_acme_client, mock_delete_if_appropriate): mock_delete_if_appropriate.return_value = False server = 'foo.bar' self._call_no_clientmock(['--cert-path', SS_CERT_PATH, '--key-path', RSA2048_KEY_PATH, '--server', server, 'revoke']) with open(RSA2048_KEY_PATH, 'rb') as f: mock_acme_client.BackwardsCompatibleClientV2.assert_called_once_with( mock.ANY, jose.JWK.load(f.read()), server) with open(SS_CERT_PATH, 'rb') as f: cert = crypto_util.pyopenssl_load_certificate(f.read())[0] mock_revoke = mock_acme_client.BackwardsCompatibleClientV2().revoke mock_revoke.assert_called_once_with( jose.ComparableX509(cert), mock.ANY) def test_revoke_with_key_mismatch(self): server = 'foo.bar' self.assertRaises(errors.Error, self._call_no_clientmock, ['--cert-path', CERT, '--key-path', KEY, '--server', server, 'revoke']) @mock.patch('certbot.main._delete_if_appropriate') @mock.patch('certbot.main._determine_account') def test_revoke_without_key(self, mock_determine_account, mock_delete_if_appropriate): mock_delete_if_appropriate.return_value = False mock_determine_account.return_value = (mock.MagicMock(), None) _, _, _, client = self._call(['--cert-path', CERT, 'revoke']) with open(CERT) as f: cert = crypto_util.pyopenssl_load_certificate(f.read())[0] mock_revoke = client.acme_from_config_key().revoke mock_revoke.assert_called_once_with( jose.ComparableX509(cert), mock.ANY) def test_agree_dev_preview_config(self): with mock.patch('certbot.main.run') as mocked_run: self._call(['-c', test_util.vector_path('cli.ini')]) self.assertTrue(mocked_run.called) def test_register(self): with mock.patch('certbot.main.client') as mocked_client: acc = mock.MagicMock() acc.id = "imaginary_account" mocked_client.register.return_value = (acc, "worked") self._call_no_clientmock(["register", "--email", "user@example.org"]) # TODO: It would be more correct to explicitly check that # _determine_account() gets called in the above case, # but coverage statistics should also show that it did. with mock.patch('certbot.main.account') as mocked_account: mocked_storage = mock.MagicMock() mocked_account.AccountFileStorage.return_value = mocked_storage mocked_storage.find_all.return_value = ["an account"] x = self._call_no_clientmock(["register", "--email", "user@example.org"]) self.assertTrue("There is an existing account" in x[0]) def test_update_registration_no_existing_accounts(self): # with mock.patch('certbot.main.client') as mocked_client: with mock.patch('certbot.main.account') as mocked_account: mocked_storage = mock.MagicMock() mocked_account.AccountFileStorage.return_value = mocked_storage mocked_storage.find_all.return_value = [] x = self._call_no_clientmock( ["register", "--update-registration", "--email", "user@example.org"]) self.assertTrue("Could not find an existing account" in x[0]) def test_update_registration_unsafely(self): # This test will become obsolete when register --update-registration # supports removing an e-mail address from the account with mock.patch('certbot.main.account') as mocked_account: mocked_storage = mock.MagicMock() mocked_account.AccountFileStorage.return_value = mocked_storage mocked_storage.find_all.return_value = ["an account"] x = self._call_no_clientmock( "register --update-registration " "--register-unsafely-without-email".split()) self.assertTrue("--register-unsafely-without-email" in x[0]) @mock.patch('certbot.main.display_ops.get_email') @test_util.patch_get_utility() def test_update_registration_with_email(self, mock_utility, mock_email): email = "user@example.com" mock_email.return_value = email with mock.patch('certbot.eff.handle_subscription') as mock_handle: with mock.patch('certbot.main._determine_account') as mocked_det: with mock.patch('certbot.main.account') as mocked_account: with mock.patch('certbot.main.client') as mocked_client: mocked_storage = mock.MagicMock() mocked_account.AccountFileStorage.return_value = mocked_storage mocked_storage.find_all.return_value = ["an account"] mock_acc = mock.MagicMock() mock_regr = mock_acc.regr mocked_det.return_value = (mock_acc, "foo") cb_client = mock.MagicMock() mocked_client.Client.return_value = cb_client x = self._call_no_clientmock( ["register", "--update-registration"]) # When registration change succeeds, the return value # of register() is None self.assertTrue(x[0] is None) # and we got supposedly did update the registration from # the server reg_arg = cb_client.acme.update_registration.call_args[0][0] # Test the return value of .update() was used because # the regr is immutable. self.assertEqual(reg_arg, mock_regr.update()) # and we saved the updated registration on disk self.assertTrue(mocked_storage.save_regr.called) self.assertTrue( email in mock_utility().add_message.call_args[0][0]) self.assertTrue(mock_handle.called) @mock.patch('certbot.plugins.selection.choose_configurator_plugins') @mock.patch('certbot.updater._run_updaters') def test_plugin_selection_error(self, mock_run, mock_choose): mock_choose.side_effect = errors.PluginSelectionError self.assertRaises(errors.PluginSelectionError, main.renew_cert, None, None, None) self.config.dry_run = False updater.run_generic_updaters(self.config, None, None) # Make sure we're returning None, and hence not trying to run the # without installer self.assertFalse(mock_run.called) class UnregisterTest(unittest.TestCase): def setUp(self): self.patchers = { '_determine_account': mock.patch('certbot.main._determine_account'), 'account': mock.patch('certbot.main.account'), 'client': mock.patch('certbot.main.client'), 'get_utility': test_util.patch_get_utility()} self.mocks = dict((k, v.start()) for k, v in self.patchers.items()) def tearDown(self): for patch in self.patchers.values(): patch.stop() def test_abort_unregister(self): self.mocks['account'].AccountFileStorage.return_value = mock.Mock() util_mock = self.mocks['get_utility']() util_mock.yesno.return_value = False config = mock.Mock() unused_plugins = mock.Mock() res = main.unregister(config, unused_plugins) self.assertEqual(res, "Deactivation aborted.") def test_unregister(self): mocked_storage = mock.MagicMock() mocked_storage.find_all.return_value = ["an account"] self.mocks['account'].AccountFileStorage.return_value = mocked_storage self.mocks['_determine_account'].return_value = (mock.MagicMock(), "foo") cb_client = mock.MagicMock() self.mocks['client'].Client.return_value = cb_client config = mock.MagicMock() unused_plugins = mock.MagicMock() res = main.unregister(config, unused_plugins) self.assertTrue(res is None) self.assertTrue(cb_client.acme.deactivate_registration.called) m = "Account deactivated." self.assertTrue(m in self.mocks['get_utility']().add_message.call_args[0][0]) def test_unregister_no_account(self): mocked_storage = mock.MagicMock() mocked_storage.find_all.return_value = [] self.mocks['account'].AccountFileStorage.return_value = mocked_storage cb_client = mock.MagicMock() self.mocks['client'].Client.return_value = cb_client config = mock.MagicMock() unused_plugins = mock.MagicMock() res = main.unregister(config, unused_plugins) m = "Could not find existing account to deactivate." self.assertEqual(res, m) self.assertFalse(cb_client.acme.deactivate_registration.called) class MakeOrVerifyNeededDirs(test_util.ConfigTestCase): """Tests for certbot.main.make_or_verify_needed_dirs.""" @mock.patch("certbot.main.util") def test_it(self, mock_util): main.make_or_verify_needed_dirs(self.config) for core_dir in (self.config.config_dir, self.config.work_dir,): mock_util.set_up_core_dir.assert_any_call( core_dir, constants.CONFIG_DIRS_MODE, os.geteuid(), self.config.strict_permissions ) hook_dirs = (self.config.renewal_pre_hooks_dir, self.config.renewal_deploy_hooks_dir, self.config.renewal_post_hooks_dir,) for hook_dir in hook_dirs: # default mode of 755 is used mock_util.make_or_verify_dir.assert_any_call( hook_dir, uid=os.geteuid(), strict=self.config.strict_permissions) class EnhanceTest(test_util.ConfigTestCase): """Tests for certbot.main.enhance.""" def setUp(self): super(EnhanceTest, self).setUp() self.get_utility_patch = test_util.patch_get_utility() self.mock_get_utility = self.get_utility_patch.start() self.mockinstaller = mock.MagicMock(spec=enhancements.AutoHSTSEnhancement) def tearDown(self): self.get_utility_patch.stop() def _call(self, args): plugins = disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) with mock.patch('certbot.cert_manager.get_certnames') as mock_certs: mock_certs.return_value = ['example.com'] with mock.patch('certbot.cert_manager.domains_for_certname') as mock_dom: mock_dom.return_value = ['example.com'] with mock.patch('certbot.main._init_le_client') as mock_init: mock_client = mock.MagicMock() mock_client.config = config mock_init.return_value = mock_client main.enhance(config, plugins) return mock_client # returns the client @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.main.display_ops.choose_values') @mock.patch('certbot.main._find_domains_or_certname') def test_selection_question(self, mock_find, mock_choose, mock_lineage, _rec): mock_lineage.return_value = mock.MagicMock(chain_path="/tmp/nonexistent") mock_choose.return_value = ['example.com'] mock_find.return_value = (None, None) with mock.patch('certbot.main.plug_sel.pick_installer') as mock_pick: self._call(['enhance', '--redirect']) self.assertTrue(mock_pick.called) # Check that the message includes "enhancements" self.assertTrue("enhancements" in mock_pick.call_args[0][3]) @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.main.display_ops.choose_values') @mock.patch('certbot.main._find_domains_or_certname') def test_selection_auth_warning(self, mock_find, mock_choose, mock_lineage, _rec): mock_lineage.return_value = mock.MagicMock(chain_path="/tmp/nonexistent") mock_choose.return_value = ["example.com"] mock_find.return_value = (None, None) with mock.patch('certbot.main.plug_sel.pick_installer'): with mock.patch('certbot.main.plug_sel.logger.warning') as mock_log: mock_client = self._call(['enhance', '-a', 'webroot', '--redirect']) self.assertTrue(mock_log.called) self.assertTrue("make sense" in mock_log.call_args[0][0]) self.assertTrue(mock_client.enhance_config.called) @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.main.display_ops.choose_values') @mock.patch('certbot.main.plug_sel.record_chosen_plugins') def test_enhance_config_call(self, _rec, mock_choose, mock_lineage): mock_lineage.return_value = mock.MagicMock(chain_path="/tmp/nonexistent") mock_choose.return_value = ["example.com"] with mock.patch('certbot.main.plug_sel.pick_installer'): mock_client = self._call(['enhance', '--redirect', '--hsts']) req_enh = ["redirect", "hsts"] not_req_enh = ["uir"] self.assertTrue(mock_client.enhance_config.called) self.assertTrue( all([getattr(mock_client.config, e) for e in req_enh])) self.assertFalse( any([getattr(mock_client.config, e) for e in not_req_enh])) self.assertTrue( "example.com" in mock_client.enhance_config.call_args[0][0]) @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.main.display_ops.choose_values') @mock.patch('certbot.main.plug_sel.record_chosen_plugins') def test_enhance_noninteractive(self, _rec, mock_choose, mock_lineage): mock_lineage.return_value = mock.MagicMock( chain_path="/tmp/nonexistent") mock_choose.return_value = ["example.com"] with mock.patch('certbot.main.plug_sel.pick_installer'): mock_client = self._call(['enhance', '--redirect', '--hsts', '--non-interactive']) self.assertTrue(mock_client.enhance_config.called) self.assertFalse(mock_choose.called) @mock.patch('certbot.main.display_ops.choose_values') @mock.patch('certbot.main.plug_sel.record_chosen_plugins') def test_user_abort_domains(self, _rec, mock_choose): mock_choose.return_value = [] with mock.patch('certbot.main.plug_sel.pick_installer'): self.assertRaises(errors.Error, self._call, ['enhance', '--redirect', '--hsts']) def test_no_enhancements_defined(self): self.assertRaises(errors.MisconfigurationError, self._call, ['enhance', '-a', 'null']) @mock.patch('certbot.main.plug_sel.choose_configurator_plugins') @mock.patch('certbot.main.display_ops.choose_values') @mock.patch('certbot.main.plug_sel.record_chosen_plugins') def test_plugin_selection_error(self, _rec, mock_choose, mock_pick): mock_choose.return_value = ["example.com"] mock_pick.return_value = (None, None) mock_pick.side_effect = errors.PluginSelectionError() mock_client = self._call(['enhance', '--hsts']) self.assertFalse(mock_client.enhance_config.called) @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.main.display_ops.choose_values') @mock.patch('certbot.main.plug_sel.pick_installer') @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @test_util.patch_get_utility() def test_enhancement_enable(self, _, _rec, mock_inst, mock_choose, mock_lineage): mock_inst.return_value = self.mockinstaller mock_choose.return_value = ["example.com", "another.tld"] mock_lineage.return_value = mock.MagicMock(chain_path="/tmp/nonexistent") self._call(['enhance', '--auto-hsts']) self.assertTrue(self.mockinstaller.enable_autohsts.called) self.assertEquals(self.mockinstaller.enable_autohsts.call_args[0][1], ["example.com", "another.tld"]) @mock.patch('certbot.cert_manager.lineage_for_certname') @mock.patch('certbot.main.display_ops.choose_values') @mock.patch('certbot.main.plug_sel.pick_installer') @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @test_util.patch_get_utility() def test_enhancement_enable_not_supported(self, _, _rec, mock_inst, mock_choose, mock_lineage): mock_inst.return_value = null.Installer(self.config, "null") mock_choose.return_value = ["example.com", "another.tld"] mock_lineage.return_value = mock.MagicMock(chain_path="/tmp/nonexistent") self.assertRaises( errors.NotSupportedError, self._call, ['enhance', '--auto-hsts']) def test_enhancement_enable_conflict(self): self.assertRaises( errors.Error, self._call, ['enhance', '--auto-hsts', '--hsts']) class InstallTest(test_util.ConfigTestCase): """Tests for certbot.main.install.""" def setUp(self): super(InstallTest, self).setUp() self.mockinstaller = mock.MagicMock(spec=enhancements.AutoHSTSEnhancement) @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @mock.patch('certbot.main.plug_sel.pick_installer') def test_install_enhancement_not_supported(self, mock_inst, _rec): mock_inst.return_value = null.Installer(self.config, "null") plugins = disco.PluginsRegistry.find_all() self.config.auto_hsts = True self.config.certname = "nonexistent" self.assertRaises(errors.NotSupportedError, main.install, self.config, plugins) @mock.patch('certbot.main.plug_sel.record_chosen_plugins') @mock.patch('certbot.main.plug_sel.pick_installer') def test_install_enhancement_no_certname(self, mock_inst, _rec): mock_inst.return_value = self.mockinstaller plugins = disco.PluginsRegistry.find_all() self.config.auto_hsts = True self.config.certname = None self.config.key_path = "/tmp/nonexistent" self.config.cert_path = "/tmp/nonexistent" self.assertRaises(errors.ConfigurationError, main.install, self.config, plugins) if __name__ == '__main__': unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/__init__.py0000644000175000017500000000002413344054434020347 0ustar ericaerica00000000000000"""Certbot Tests""" certbot-0.27.0/certbot/tests/display/0002755000175000017500000000000013344054435017712 5ustar ericaerica00000000000000certbot-0.27.0/certbot/tests/display/__init__.py0000644000175000017500000000003413344054434022015 0ustar ericaerica00000000000000"""Certbot Display Tests""" certbot-0.27.0/certbot/tests/display/ops_test.py0000644000175000017500000005214413344054434022127 0ustar ericaerica00000000000000# coding=utf-8 """Test certbot.display.ops.""" import os import sys import unittest import josepy as jose import mock import zope.component from acme import messages from certbot import account from certbot import errors from certbot.display import util as display_util from certbot.display import ops import certbot.tests.util as test_util KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem")) class GetEmailTest(unittest.TestCase): """Tests for certbot.display.ops.get_email.""" @classmethod def _call(cls, **kwargs): from certbot.display.ops import get_email return get_email(**kwargs) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_cancel_none(self, mock_get_utility): mock_input = mock_get_utility().input mock_input.return_value = (display_util.CANCEL, "foo@bar.baz") self.assertRaises(errors.Error, self._call) self.assertRaises(errors.Error, self._call, optional=False) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_ok_safe(self, mock_get_utility): mock_input = mock_get_utility().input mock_input.return_value = (display_util.OK, "foo@bar.baz") with mock.patch("certbot.display.ops.util.safe_email") as mock_safe_email: mock_safe_email.return_value = True self.assertTrue(self._call() is "foo@bar.baz") @test_util.patch_get_utility("certbot.display.ops.z_util") def test_ok_not_safe(self, mock_get_utility): mock_input = mock_get_utility().input mock_input.return_value = (display_util.OK, "foo@bar.baz") with mock.patch("certbot.display.ops.util.safe_email") as mock_safe_email: mock_safe_email.side_effect = [False, True] self.assertTrue(self._call() is "foo@bar.baz") @test_util.patch_get_utility("certbot.display.ops.z_util") def test_invalid_flag(self, mock_get_utility): invalid_txt = "There seem to be problems" mock_input = mock_get_utility().input mock_input.return_value = (display_util.OK, "foo@bar.baz") with mock.patch("certbot.display.ops.util.safe_email") as mock_safe_email: mock_safe_email.return_value = True self._call() self.assertTrue(invalid_txt not in mock_input.call_args[0][0]) self._call(invalid=True) self.assertTrue(invalid_txt in mock_input.call_args[0][0]) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_optional_flag(self, mock_get_utility): mock_input = mock_get_utility().input mock_input.return_value = (display_util.OK, "foo@bar.baz") with mock.patch("certbot.display.ops.util.safe_email") as mock_safe_email: mock_safe_email.side_effect = [False, True] self._call(optional=False) for call in mock_input.call_args_list: self.assertTrue( "--register-unsafely-without-email" not in call[0][0]) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_optional_invalid_unsafe(self, mock_get_utility): invalid_txt = "There seem to be problems" mock_input = mock_get_utility().input mock_input.return_value = (display_util.OK, "foo@bar.baz") with mock.patch("certbot.display.ops.util.safe_email") as mock_safe_email: mock_safe_email.side_effect = [False, True] self._call(invalid=True) self.assertTrue(invalid_txt in mock_input.call_args[0][0]) class ChooseAccountTest(test_util.TempDirTestCase): """Tests for certbot.display.ops.choose_account.""" def setUp(self): super(ChooseAccountTest, self).setUp() zope.component.provideUtility(display_util.FileDisplay(sys.stdout, False)) self.account_keys_dir = os.path.join(self.tempdir, "keys") os.makedirs(self.account_keys_dir, 0o700) self.config = mock.MagicMock( accounts_dir=self.tempdir, account_keys_dir=self.account_keys_dir, server="certbot-demo.org") self.key = KEY self.acc1 = account.Account(messages.RegistrationResource( uri=None, body=messages.Registration.from_data( email="email1@g.com")), self.key) self.acc2 = account.Account(messages.RegistrationResource( uri=None, body=messages.Registration.from_data( email="email2@g.com", phone="phone")), self.key) @classmethod def _call(cls, accounts): return ops.choose_account(accounts) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_one(self, mock_util): mock_util().menu.return_value = (display_util.OK, 0) self.assertEqual(self._call([self.acc1]), self.acc1) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_two(self, mock_util): mock_util().menu.return_value = (display_util.OK, 1) self.assertEqual(self._call([self.acc1, self.acc2]), self.acc2) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_cancel(self, mock_util): mock_util().menu.return_value = (display_util.CANCEL, 1) self.assertTrue(self._call([self.acc1, self.acc2]) is None) class GenSSLLabURLs(unittest.TestCase): """Loose test of _gen_ssl_lab_urls. URL can change easily in the future.""" def setUp(self): zope.component.provideUtility(display_util.FileDisplay(sys.stdout, False)) @classmethod def _call(cls, domains): from certbot.display.ops import _gen_ssl_lab_urls return _gen_ssl_lab_urls(domains) def test_zero(self): self.assertEqual(self._call([]), []) def test_two(self): urls = self._call(["eff.org", "umich.edu"]) self.assertTrue("eff.org" in urls[0]) self.assertTrue("umich.edu" in urls[1]) class GenHttpsNamesTest(unittest.TestCase): """Test _gen_https_names.""" def setUp(self): zope.component.provideUtility(display_util.FileDisplay(sys.stdout, False)) @classmethod def _call(cls, domains): from certbot.display.ops import _gen_https_names return _gen_https_names(domains) def test_zero(self): self.assertEqual(self._call([]), "") def test_one(self): doms = [ "example.com", "asllkjsadfljasdf.c", ] for dom in doms: self.assertEqual(self._call([dom]), "https://%s" % dom) def test_two(self): domains_list = [ ["foo.bar.org", "bar.org"], ["paypal.google.facebook.live.com", "*.zombo.example.com"], ] for doms in domains_list: self.assertEqual( self._call(doms), "https://{dom[0]} and https://{dom[1]}".format(dom=doms)) def test_three(self): doms = ["a.org", "b.org", "c.org"] # We use an oxford comma self.assertEqual( self._call(doms), "https://{dom[0]}, https://{dom[1]}, and https://{dom[2]}".format( dom=doms)) def test_four(self): doms = ["a.org", "b.org", "c.org", "d.org"] exp = ("https://{dom[0]}, https://{dom[1]}, https://{dom[2]}, " "and https://{dom[3]}".format(dom=doms)) self.assertEqual(self._call(doms), exp) class ChooseNamesTest(unittest.TestCase): """Test choose names.""" def setUp(self): zope.component.provideUtility(display_util.FileDisplay(sys.stdout, False)) self.mock_install = mock.MagicMock() @classmethod def _call(cls, installer, question=None): from certbot.display.ops import choose_names return choose_names(installer, question) @mock.patch("certbot.display.ops._choose_names_manually") def test_no_installer(self, mock_manual): self._call(None) self.assertEqual(mock_manual.call_count, 1) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_no_installer_cancel(self, mock_util): mock_util().input.return_value = (display_util.CANCEL, []) self.assertEqual(self._call(None), []) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_no_names_choose(self, mock_util): self.mock_install().get_all_names.return_value = set() domain = "example.com" mock_util().input.return_value = (display_util.OK, domain) actual_doms = self._call(self.mock_install) self.assertEqual(mock_util().input.call_count, 1) self.assertEqual(actual_doms, [domain]) self.assertTrue( "configuration files" in mock_util().input.call_args[0][0]) def test_sort_names_trivial(self): from certbot.display.ops import _sort_names #sort an empty list self.assertEqual(_sort_names([]), []) #sort simple domains some_domains = ["ex.com", "zx.com", "ax.com"] self.assertEqual(_sort_names(some_domains), ["ax.com", "ex.com", "zx.com"]) #Sort subdomains of a single domain domain = ".ex.com" unsorted_short = ["e", "a", "z", "y"] unsorted_long = [us + domain for us in unsorted_short] sorted_short = sorted(unsorted_short) sorted_long = [us + domain for us in sorted_short] self.assertEqual(_sort_names(unsorted_long), sorted_long) def test_sort_names_many(self): from certbot.display.ops import _sort_names unsorted_domains = [".cx.com", ".bx.com", ".ax.com", ".dx.com"] unsorted_short = ["www", "bnother.long.subdomain", "a", "a.long.subdomain", "z", "b"] #Of course sorted doesn't work here ;-) sorted_short = ["a", "b", "a.long.subdomain", "bnother.long.subdomain", "www", "z"] to_sort = [] for short in unsorted_short: for domain in unsorted_domains: to_sort.append(short+domain) sortd = [] for domain in sorted(unsorted_domains): for short in sorted_short: sortd.append(short+domain) self.assertEqual(_sort_names(to_sort), sortd) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_filter_names_valid_return(self, mock_util): self.mock_install.get_all_names.return_value = set(["example.com"]) mock_util().checklist.return_value = (display_util.OK, ["example.com"]) names = self._call(self.mock_install) self.assertEqual(names, ["example.com"]) self.assertEqual(mock_util().checklist.call_count, 1) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_filter_namees_override_question(self, mock_util): self.mock_install.get_all_names.return_value = set(["example.com"]) mock_util().checklist.return_value = (display_util.OK, ["example.com"]) names = self._call(self.mock_install, "Custom") self.assertEqual(names, ["example.com"]) self.assertEqual(mock_util().checklist.call_count, 1) self.assertEqual(mock_util().checklist.call_args[0][0], "Custom") @test_util.patch_get_utility("certbot.display.ops.z_util") def test_filter_names_nothing_selected(self, mock_util): self.mock_install.get_all_names.return_value = set(["example.com"]) mock_util().checklist.return_value = (display_util.OK, []) self.assertEqual(self._call(self.mock_install), []) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_filter_names_cancel(self, mock_util): self.mock_install.get_all_names.return_value = set(["example.com"]) mock_util().checklist.return_value = ( display_util.CANCEL, ["example.com"]) self.assertEqual(self._call(self.mock_install), []) def test_get_valid_domains(self): from certbot.display.ops import get_valid_domains all_valid = ["example.com", "second.example.com", "also.example.com", "under_score.example.com", "justtld", "*.wildcard.com"] all_invalid = ["öóòps.net", "uniçodé.com"] two_valid = ["example.com", "úniçøde.com", "also.example.com"] self.assertEqual(get_valid_domains(all_valid), all_valid) self.assertEqual(get_valid_domains(all_invalid), []) self.assertEqual(len(get_valid_domains(two_valid)), 2) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_choose_manually(self, mock_util): from certbot.display.ops import _choose_names_manually utility_mock = mock_util() # No retry utility_mock.yesno.return_value = False # IDN and no retry utility_mock.input.return_value = (display_util.OK, "uniçodé.com") self.assertEqual(_choose_names_manually(), []) # IDN exception with previous mocks with mock.patch( "certbot.display.ops.display_util.separate_list_input" ) as mock_sli: unicode_error = UnicodeEncodeError('mock', u'', 0, 1, 'mock') mock_sli.side_effect = unicode_error self.assertEqual(_choose_names_manually(), []) # Valid domains utility_mock.input.return_value = (display_util.OK, ("example.com," "under_score.example.com," "justtld," "valid.example.com")) self.assertEqual(_choose_names_manually(), ["example.com", "under_score.example.com", "justtld", "valid.example.com"]) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_choose_manually_retry(self, mock_util): from certbot.display.ops import _choose_names_manually utility_mock = mock_util() # Three iterations utility_mock.input.return_value = (display_util.OK, "uniçodé.com") utility_mock.yesno.side_effect = [True, True, False] _choose_names_manually() self.assertEqual(utility_mock.yesno.call_count, 3) class SuccessInstallationTest(unittest.TestCase): # pylint: disable=too-few-public-methods """Test the success installation message.""" @classmethod def _call(cls, names): from certbot.display.ops import success_installation success_installation(names) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_success_installation(self, mock_util): mock_util().notification.return_value = None names = ["example.com", "abc.com"] self._call(names) self.assertEqual(mock_util().notification.call_count, 1) arg = mock_util().notification.call_args_list[0][0][0] for name in names: self.assertTrue(name in arg) class SuccessRenewalTest(unittest.TestCase): # pylint: disable=too-few-public-methods """Test the success renewal message.""" @classmethod def _call(cls, names): from certbot.display.ops import success_renewal success_renewal(names) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_success_renewal(self, mock_util): mock_util().notification.return_value = None names = ["example.com", "abc.com"] self._call(names) self.assertEqual(mock_util().notification.call_count, 1) arg = mock_util().notification.call_args_list[0][0][0] for name in names: self.assertTrue(name in arg) class SuccessRevocationTest(unittest.TestCase): # pylint: disable=too-few-public-methods """Test the success revocation message.""" @classmethod def _call(cls, path): from certbot.display.ops import success_revocation success_revocation(path) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_success_revocation(self, mock_util): mock_util().notification.return_value = None path = "/path/to/cert.pem" self._call(path) mock_util().notification.assert_called_once_with( "Congratulations! You have successfully revoked the certificate " "that was located at {0}{1}{1}".format( path, os.linesep), pause=False) self.assertTrue(path in mock_util().notification.call_args[0][0]) class ValidatorTests(unittest.TestCase): """Tests for `validated_input` and `validated_directory`.""" __ERROR = "Must be non-empty" valid_input = "asdf" valid_directory = "/var/www/html" @staticmethod def __validator(m): if m == "": raise errors.PluginError(ValidatorTests.__ERROR) @test_util.patch_get_utility() def test_input_blank_with_validator(self, mock_util): mock_util().input.side_effect = [(display_util.OK, ""), (display_util.OK, ""), (display_util.OK, ""), (display_util.OK, self.valid_input)] returned = ops.validated_input(self.__validator, "message", force_interactive=True) self.assertEqual(ValidatorTests.__ERROR, mock_util().notification.call_args[0][0]) self.assertEqual(returned, (display_util.OK, self.valid_input)) @test_util.patch_get_utility() def test_input_validation_with_default(self, mock_util): mock_util().input.side_effect = [(display_util.OK, self.valid_input)] returned = ops.validated_input(self.__validator, "msg", default="other") self.assertEqual(returned, (display_util.OK, self.valid_input)) @test_util.patch_get_utility() def test_input_validation_with_bad_default(self, mock_util): mock_util().input.side_effect = [(display_util.OK, self.valid_input)] self.assertRaises(AssertionError, ops.validated_input, self.__validator, "msg", default="") @test_util.patch_get_utility() def test_input_cancel_with_validator(self, mock_util): mock_util().input.side_effect = [(display_util.CANCEL, "")] code, unused_raw = ops.validated_input(self.__validator, "message", force_interactive=True) self.assertEqual(code, display_util.CANCEL) @test_util.patch_get_utility() def test_directory_select_validation(self, mock_util): mock_util().directory_select.side_effect = [(display_util.OK, ""), (display_util.OK, self.valid_directory)] returned = ops.validated_directory(self.__validator, "msg", force_interactive=True) self.assertEqual(ValidatorTests.__ERROR, mock_util().notification.call_args[0][0]) self.assertEqual(returned, (display_util.OK, self.valid_directory)) @test_util.patch_get_utility() def test_directory_select_validation_with_default(self, mock_util): mock_util().directory_select.side_effect = [(display_util.OK, self.valid_directory)] returned = ops.validated_directory(self.__validator, "msg", default="other") self.assertEqual(returned, (display_util.OK, self.valid_directory)) @test_util.patch_get_utility() def test_directory_select_validation_with_bad_default(self, mock_util): mock_util().directory_select.side_effect = [(display_util.OK, self.valid_directory)] self.assertRaises(AssertionError, ops.validated_directory, self.__validator, "msg", default="") class ChooseValuesTest(unittest.TestCase): """Test choose_values.""" @classmethod def _call(cls, values, question): from certbot.display.ops import choose_values return choose_values(values, question) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_choose_names_success(self, mock_util): items = ["first", "second", "third"] mock_util().checklist.return_value = (display_util.OK, [items[2]]) result = self._call(items, None) self.assertEquals(result, [items[2]]) self.assertTrue(mock_util().checklist.called) self.assertEquals(mock_util().checklist.call_args[0][0], None) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_choose_names_success_question(self, mock_util): items = ["first", "second", "third"] question = "Which one?" mock_util().checklist.return_value = (display_util.OK, [items[1]]) result = self._call(items, question) self.assertEquals(result, [items[1]]) self.assertTrue(mock_util().checklist.called) self.assertEquals(mock_util().checklist.call_args[0][0], question) @test_util.patch_get_utility("certbot.display.ops.z_util") def test_choose_names_user_cancel(self, mock_util): items = ["first", "second", "third"] question = "Want to cancel?" mock_util().checklist.return_value = (display_util.CANCEL, []) result = self._call(items, question) self.assertEquals(result, []) self.assertTrue(mock_util().checklist.called) self.assertEquals(mock_util().checklist.call_args[0][0], question) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/display/completer_test.py0000644000175000017500000000644513344054434023323 0ustar ericaerica00000000000000"""Test certbot.display.completer.""" import os import readline import string import sys import unittest import mock from six.moves import reload_module # pylint: disable=import-error from acme.magic_typing import List # pylint: disable=unused-import, no-name-in-module from certbot.tests.util import TempDirTestCase class CompleterTest(TempDirTestCase): """Test certbot.display.completer.Completer.""" def setUp(self): super(CompleterTest, self).setUp() # directories must end with os.sep for completer to # search inside the directory for possible completions if self.tempdir[-1] != os.sep: self.tempdir += os.sep self.paths = [] # type: List[str] # create some files and directories in temp_dir for c in string.ascii_lowercase: path = os.path.join(self.tempdir, c) self.paths.append(path) if ord(c) % 2: os.mkdir(path) else: with open(path, 'w'): pass def test_complete(self): from certbot.display import completer my_completer = completer.Completer() num_paths = len(self.paths) for i in range(num_paths): completion = my_completer.complete(self.tempdir, i) self.assertTrue(completion in self.paths) self.paths.remove(completion) self.assertFalse(self.paths) completion = my_completer.complete(self.tempdir, num_paths) self.assertEqual(completion, None) def test_import_error(self): original_readline = sys.modules['readline'] sys.modules['readline'] = None self.test_context_manager_with_unmocked_readline() sys.modules['readline'] = original_readline def test_context_manager_with_unmocked_readline(self): from certbot.display import completer reload_module(completer) original_completer = readline.get_completer() original_delims = readline.get_completer_delims() with completer.Completer(): pass self.assertEqual(readline.get_completer(), original_completer) self.assertEqual(readline.get_completer_delims(), original_delims) @mock.patch('certbot.display.completer.readline', autospec=True) def test_context_manager_libedit(self, mock_readline): mock_readline.__doc__ = 'libedit' self._test_context_manager_with_mock_readline(mock_readline) @mock.patch('certbot.display.completer.readline', autospec=True) def test_context_manager_readline(self, mock_readline): mock_readline.__doc__ = 'GNU readline' self._test_context_manager_with_mock_readline(mock_readline) def _test_context_manager_with_mock_readline(self, mock_readline): from certbot.display import completer mock_readline.parse_and_bind.side_effect = enable_tab_completion with completer.Completer(): pass self.assertTrue(mock_readline.parse_and_bind.called) def enable_tab_completion(unused_command): """Enables readline tab completion using the system specific syntax.""" libedit = 'libedit' in readline.__doc__ command = 'bind ^I rl_complete' if libedit else 'tab: complete' readline.parse_and_bind(command) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/display/enhancements_test.py0000644000175000017500000000320713344054434023772 0ustar ericaerica00000000000000"""Module for enhancement UI.""" import logging import unittest import mock from certbot import errors from certbot.display import util as display_util class AskTest(unittest.TestCase): """Test the ask method.""" def setUp(self): logging.disable(logging.CRITICAL) def tearDown(self): logging.disable(logging.NOTSET) @classmethod def _call(cls, enhancement): from certbot.display.enhancements import ask return ask(enhancement) @mock.patch("certbot.display.enhancements.util") def test_redirect(self, mock_util): mock_util().menu.return_value = (display_util.OK, 1) self.assertTrue(self._call("redirect")) def test_key_error(self): self.assertRaises(errors.Error, self._call, "unknown_enhancement") class RedirectTest(unittest.TestCase): """Test the redirect_by_default method.""" @classmethod def _call(cls): from certbot.display.enhancements import redirect_by_default return redirect_by_default() @mock.patch("certbot.display.enhancements.util") def test_secure(self, mock_util): mock_util().menu.return_value = (display_util.OK, 1) self.assertTrue(self._call()) @mock.patch("certbot.display.enhancements.util") def test_cancel(self, mock_util): mock_util().menu.return_value = (display_util.CANCEL, 1) self.assertFalse(self._call()) @mock.patch("certbot.display.enhancements.util") def test_easy(self, mock_util): mock_util().menu.return_value = (display_util.OK, 0) self.assertFalse(self._call()) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/display/util_test.py0000644000175000017500000004024513344054434022302 0ustar ericaerica00000000000000"""Test :mod:`certbot.display.util`.""" import inspect import os import socket import tempfile import unittest import six import mock from certbot import errors from certbot import interfaces from certbot.display import util as display_util CHOICES = [("First", "Description1"), ("Second", "Description2")] TAGS = ["tag1", "tag2", "tag3"] TAGS_CHOICES = [("1", "tag1"), ("2", "tag2"), ("3", "tag3")] class InputWithTimeoutTest(unittest.TestCase): """Tests for certbot.display.util.input_with_timeout.""" @classmethod def _call(cls, *args, **kwargs): from certbot.display.util import input_with_timeout return input_with_timeout(*args, **kwargs) def test_eof(self): with tempfile.TemporaryFile("r+") as f: with mock.patch("certbot.display.util.sys.stdin", new=f): self.assertRaises(EOFError, self._call) def test_input(self, prompt=None): expected = "foo bar" stdin = six.StringIO(expected + "\n") with mock.patch("certbot.display.util.select.select") as mock_select: mock_select.return_value = ([stdin], [], [],) self.assertEqual(self._call(prompt), expected) @mock.patch("certbot.display.util.sys.stdout") def test_input_with_prompt(self, mock_stdout): prompt = "test prompt: " self.test_input(prompt) mock_stdout.write.assert_called_once_with(prompt) mock_stdout.flush.assert_called_once_with() def test_timeout(self): stdin = socket.socket(socket.AF_INET, socket.SOCK_STREAM) stdin.bind(('', 0)) stdin.listen(1) with mock.patch("certbot.display.util.sys.stdin", stdin): self.assertRaises(errors.Error, self._call, timeout=0.001) class FileOutputDisplayTest(unittest.TestCase): """Test stdout display. Most of this class has to deal with visual output. In order to test how the functions look to a user, uncomment the test_visual function. """ # pylint:disable=too-many-public-methods def setUp(self): super(FileOutputDisplayTest, self).setUp() self.mock_stdout = mock.MagicMock() self.displayer = display_util.FileDisplay(self.mock_stdout, False) def test_notification_no_pause(self): self.displayer.notification("message", False) string = self.mock_stdout.write.call_args[0][0] self.assertTrue("message" in string) def test_notification_pause(self): input_with_timeout = "certbot.display.util.input_with_timeout" with mock.patch(input_with_timeout, return_value="enter"): self.displayer.notification("message", force_interactive=True) self.assertTrue("message" in self.mock_stdout.write.call_args[0][0]) def test_notification_noninteractive(self): self._force_noninteractive(self.displayer.notification, "message") string = self.mock_stdout.write.call_args[0][0] self.assertTrue("message" in string) def test_notification_noninteractive2(self): # The main purpose of this test is to make sure we only call # logger.warning once which _force_noninteractive checks internally self._force_noninteractive(self.displayer.notification, "message") string = self.mock_stdout.write.call_args[0][0] self.assertTrue("message" in string) self.assertTrue(self.displayer.skipped_interaction) self._force_noninteractive(self.displayer.notification, "message2") string = self.mock_stdout.write.call_args[0][0] self.assertTrue("message2" in string) @mock.patch("certbot.display.util." "FileDisplay._get_valid_int_ans") def test_menu(self, mock_ans): mock_ans.return_value = (display_util.OK, 1) ret = self.displayer.menu("message", CHOICES, force_interactive=True) self.assertEqual(ret, (display_util.OK, 0)) def test_menu_noninteractive(self): default = 0 result = self._force_noninteractive( self.displayer.menu, "msg", CHOICES, default=default) self.assertEqual(result, (display_util.OK, default)) def test_input_cancel(self): input_with_timeout = "certbot.display.util.input_with_timeout" with mock.patch(input_with_timeout, return_value="c"): code, _ = self.displayer.input("message", force_interactive=True) self.assertTrue(code, display_util.CANCEL) def test_input_normal(self): input_with_timeout = "certbot.display.util.input_with_timeout" with mock.patch(input_with_timeout, return_value="domain.com"): code, input_ = self.displayer.input("message", force_interactive=True) self.assertEqual(code, display_util.OK) self.assertEqual(input_, "domain.com") def test_input_noninteractive(self): default = "foo" code, input_ = self._force_noninteractive( self.displayer.input, "message", default=default) self.assertEqual(code, display_util.OK) self.assertEqual(input_, default) def test_input_assertion_fail(self): # If the call to util.assert_valid_call is commented out, an # error.Error is raised, otherwise, an AssertionError is raised. self.assertRaises(Exception, self._force_noninteractive, self.displayer.input, "message", cli_flag="--flag") def test_input_assertion_fail2(self): with mock.patch("certbot.display.util.assert_valid_call"): self.assertRaises(errors.Error, self._force_noninteractive, self.displayer.input, "msg", cli_flag="--flag") def test_yesno(self): input_with_timeout = "certbot.display.util.input_with_timeout" with mock.patch(input_with_timeout, return_value="Yes"): self.assertTrue(self.displayer.yesno( "message", force_interactive=True)) with mock.patch(input_with_timeout, return_value="y"): self.assertTrue(self.displayer.yesno( "message", force_interactive=True)) with mock.patch(input_with_timeout, side_effect=["maybe", "y"]): self.assertTrue(self.displayer.yesno( "message", force_interactive=True)) with mock.patch(input_with_timeout, return_value="No"): self.assertFalse(self.displayer.yesno( "message", force_interactive=True)) with mock.patch(input_with_timeout, side_effect=["cancel", "n"]): self.assertFalse(self.displayer.yesno( "message", force_interactive=True)) with mock.patch(input_with_timeout, return_value="a"): self.assertTrue(self.displayer.yesno( "msg", yes_label="Agree", force_interactive=True)) def test_yesno_noninteractive(self): self.assertTrue(self._force_noninteractive( self.displayer.yesno, "message", default=True)) @mock.patch("certbot.display.util.input_with_timeout") def test_checklist_valid(self, mock_input): mock_input.return_value = "2 1" code, tag_list = self.displayer.checklist( "msg", TAGS, force_interactive=True) self.assertEqual( (code, set(tag_list)), (display_util.OK, set(["tag1", "tag2"]))) @mock.patch("certbot.display.util.input_with_timeout") def test_checklist_empty(self, mock_input): mock_input.return_value = "" code, tag_list = self.displayer.checklist("msg", TAGS, force_interactive=True) self.assertEqual( (code, set(tag_list)), (display_util.OK, set(["tag1", "tag2", "tag3"]))) @mock.patch("certbot.display.util.input_with_timeout") def test_checklist_miss_valid(self, mock_input): mock_input.side_effect = ["10", "tag1 please", "1"] ret = self.displayer.checklist("msg", TAGS, force_interactive=True) self.assertEqual(ret, (display_util.OK, ["tag1"])) @mock.patch("certbot.display.util.input_with_timeout") def test_checklist_miss_quit(self, mock_input): mock_input.side_effect = ["10", "c"] ret = self.displayer.checklist("msg", TAGS, force_interactive=True) self.assertEqual(ret, (display_util.CANCEL, [])) def test_checklist_noninteractive(self): default = TAGS code, input_ = self._force_noninteractive( self.displayer.checklist, "msg", TAGS, default=default) self.assertEqual(code, display_util.OK) self.assertEqual(input_, default) def test_scrub_checklist_input_valid(self): # pylint: disable=protected-access indices = [ ["1"], ["1", "2", "1"], ["2", "3"], ] exp = [ set(["tag1"]), set(["tag1", "tag2"]), set(["tag2", "tag3"]), ] for i, list_ in enumerate(indices): set_tags = set( self.displayer._scrub_checklist_input(list_, TAGS)) self.assertEqual(set_tags, exp[i]) @mock.patch("certbot.display.util.input_with_timeout") def test_directory_select(self, mock_input): # pylint: disable=star-args args = ["msg", "/var/www/html", "--flag", True] user_input = "/var/www/html" mock_input.return_value = user_input returned = self.displayer.directory_select(*args) self.assertEqual(returned, (display_util.OK, user_input)) def test_directory_select_noninteractive(self): default = "/var/www/html" code, input_ = self._force_noninteractive( self.displayer.directory_select, "msg", default=default) self.assertEqual(code, display_util.OK) self.assertEqual(input_, default) def _force_noninteractive(self, func, *args, **kwargs): skipped_interaction = self.displayer.skipped_interaction with mock.patch("certbot.display.util.sys.stdin") as mock_stdin: mock_stdin.isatty.return_value = False with mock.patch("certbot.display.util.logger") as mock_logger: result = func(*args, **kwargs) if skipped_interaction: self.assertFalse(mock_logger.warning.called) else: self.assertEqual(mock_logger.warning.call_count, 1) return result def test_scrub_checklist_input_invalid(self): # pylint: disable=protected-access indices = [ ["0"], ["4"], ["tag1"], ["1", "tag1"], ["2", "o"] ] for list_ in indices: self.assertEqual( self.displayer._scrub_checklist_input(list_, TAGS), []) def test_print_menu(self): # pylint: disable=protected-access # This is purely cosmetic... just make sure there aren't any exceptions self.displayer._print_menu("msg", CHOICES) self.displayer._print_menu("msg", TAGS) def test_wrap_lines(self): # pylint: disable=protected-access msg = ("This is just a weak test{0}" "This function is only meant to be for easy viewing{0}" "Test a really really really really really really really really " "really really really really long line...".format(os.linesep)) text = display_util._wrap_lines(msg) self.assertEqual(text.count(os.linesep), 3) def test_get_valid_int_ans_valid(self): # pylint: disable=protected-access input_with_timeout = "certbot.display.util.input_with_timeout" with mock.patch(input_with_timeout, return_value="1"): self.assertEqual( self.displayer._get_valid_int_ans(1), (display_util.OK, 1)) ans = "2" with mock.patch(input_with_timeout, return_value=ans): self.assertEqual( self.displayer._get_valid_int_ans(3), (display_util.OK, int(ans))) def test_get_valid_int_ans_invalid(self): # pylint: disable=protected-access answers = [ ["0", "c"], ["4", "one", "C"], ["c"], ] input_with_timeout = "certbot.display.util.input_with_timeout" for ans in answers: with mock.patch(input_with_timeout, side_effect=ans): self.assertEqual( self.displayer._get_valid_int_ans(3), (display_util.CANCEL, -1)) def test_methods_take_force_interactive(self): # Every IDisplay method implemented by FileDisplay must take # force_interactive to prevent workflow regressions. for name in interfaces.IDisplay.names(): # pylint: disable=no-member arg_spec = inspect.getargspec(getattr(self.displayer, name)) self.assertTrue("force_interactive" in arg_spec.args) class NoninteractiveDisplayTest(unittest.TestCase): """Test non-interactive display. These tests are pretty easy! """ def setUp(self): super(NoninteractiveDisplayTest, self).setUp() self.mock_stdout = mock.MagicMock() self.displayer = display_util.NoninteractiveDisplay(self.mock_stdout) def test_notification_no_pause(self): self.displayer.notification("message", 10) string = self.mock_stdout.write.call_args[0][0] self.assertTrue("message" in string) def test_input(self): d = "an incomputable value" ret = self.displayer.input("message", default=d) self.assertEqual(ret, (display_util.OK, d)) self.assertRaises(errors.MissingCommandlineFlag, self.displayer.input, "message") def test_menu(self): ret = self.displayer.menu("message", CHOICES, default=1) self.assertEqual(ret, (display_util.OK, 1)) self.assertRaises(errors.MissingCommandlineFlag, self.displayer.menu, "message", CHOICES) def test_yesno(self): d = False ret = self.displayer.yesno("message", default=d) self.assertEqual(ret, d) self.assertRaises(errors.MissingCommandlineFlag, self.displayer.yesno, "message") def test_checklist(self): d = [1, 3] ret = self.displayer.checklist("message", TAGS, default=d) self.assertEqual(ret, (display_util.OK, d)) self.assertRaises(errors.MissingCommandlineFlag, self.displayer.checklist, "message", TAGS) def test_directory_select(self): default = "/var/www/html" expected = (display_util.OK, default) actual = self.displayer.directory_select("msg", default) self.assertEqual(expected, actual) self.assertRaises( errors.MissingCommandlineFlag, self.displayer.directory_select, "msg") def test_methods_take_kwargs(self): # Every IDisplay method implemented by NoninteractiveDisplay # should take **kwargs because every method of FileDisplay must # take force_interactive which doesn't apply to # NoninteractiveDisplay. for name in interfaces.IDisplay.names(): # pylint: disable=no-member method = getattr(self.displayer, name) # asserts method accepts arbitrary keyword arguments self.assertFalse(inspect.getargspec(method).keywords is None) class SeparateListInputTest(unittest.TestCase): """Test Module functions.""" def setUp(self): self.exp = ["a", "b", "c", "test"] @classmethod def _call(cls, input_): from certbot.display.util import separate_list_input return separate_list_input(input_) def test_commas(self): self.assertEqual(self._call("a,b,c,test"), self.exp) def test_spaces(self): self.assertEqual(self._call("a b c test"), self.exp) def test_both(self): self.assertEqual(self._call("a, b, c, test"), self.exp) def test_mess(self): actual = [ self._call(" a , b c \t test"), self._call(",a, ,, , b c test "), self._call(",,,,, , a b,,, , c,test"), ] for act in actual: self.assertEqual(act, self.exp) class PlaceParensTest(unittest.TestCase): @classmethod def _call(cls, label): # pylint: disable=protected-access from certbot.display.util import _parens_around_char return _parens_around_char(label) def test_single_letter(self): self.assertEqual("(a)", self._call("a")) def test_multiple(self): self.assertEqual("(L)abel", self._call("Label")) self.assertEqual("(y)es please", self._call("yes please")) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/errors_test.py0000644000175000017500000000346713344054434021201 0ustar ericaerica00000000000000"""Tests for certbot.errors.""" import unittest import mock from acme import messages from certbot import achallenges from certbot.tests import acme_util class FailedChallengesTest(unittest.TestCase): """Tests for certbot.errors.FailedChallenges.""" def setUp(self): from certbot.errors import FailedChallenges self.error = FailedChallenges(set([achallenges.DNS( domain="example.com", challb=messages.ChallengeBody( chall=acme_util.DNS01, uri=None, error=messages.Error(typ="tls", detail="detail")))])) def test_str(self): self.assertTrue(str(self.error).startswith( "Failed authorization procedure. example.com (dns-01): tls")) def test_unicode(self): from certbot.errors import FailedChallenges arabic_detail = u'\u0639\u062f\u0627\u0644\u0629' arabic_error = FailedChallenges(set([achallenges.DNS( domain="example.com", challb=messages.ChallengeBody( chall=acme_util.DNS01, uri=None, error=messages.Error(typ="tls", detail=arabic_detail)))])) self.assertTrue(str(arabic_error).startswith( "Failed authorization procedure. example.com (dns-01): tls")) class StandaloneBindErrorTest(unittest.TestCase): """Tests for certbot.errors.StandaloneBindError.""" def setUp(self): from certbot.errors import StandaloneBindError self.error = StandaloneBindError(mock.sentinel.error, 1234) def test_instance_args(self): self.assertEqual(mock.sentinel.error, self.error.socket_error) self.assertEqual(1234, self.error.port) def test_str(self): self.assertTrue(str(self.error).startswith( "Problem binding to port 1234: ")) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/testdata/0002755000175000017500000000000013344054435020056 5ustar ericaerica00000000000000certbot-0.27.0/certbot/tests/testdata/os-release0000644000175000017500000000027613344054434022042 0ustar ericaerica00000000000000NAME="SystemdOS" VERSION="42.42.42 LTS, Unreal" ID=systemdos ID_LIKE="something nonexistent debian" VERSION_ID="42" HOME_URL="http://www.example.com/" SUPPORT_URL="http://help.example.com/" certbot-0.27.0/certbot/tests/testdata/csr-nosans_nistp256.pem0000644000175000017500000000070413344054434024317 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE REQUEST----- MIIBFDCBugIBADBYMQswCQYDVQQGEwJVUzERMA8GA1UECAwITWljaGlnYW4xEjAQ BgNVBAcMCUFubiBBcmJvcjEMMAoGA1UECgwDRUZGMRQwEgYDVQQDDAtleGFtcGxl LmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABDz5dCWrkmbpLwFFr+JeVTSw GEF4bj12EAX+HVRE97NBOavWQm0nvqTVG5KPRfkxZLnO11Y0D7H5A24dCPZw9Leg ADAKBggqhkjOPQQDAgNJADBGAiEAuoZHrYA5sy2DRTdLAxJTBNHKFFKbtaGt+QaJ A62qa8sCIQCUkSgSAiNaEnJ7r5fKphdjeORHqhpl6flYkLE3lGmGdg== -----END CERTIFICATE REQUEST----- certbot-0.27.0/certbot/tests/testdata/cli.ini0000644000175000017500000000003113344054434021315 0ustar ericaerica00000000000000agree-dev-preview = True certbot-0.27.0/certbot/tests/testdata/csr-6sans_512.conf0000644000175000017500000000076613344054434023141 0ustar ericaerica00000000000000[req] distinguished_name = req_distinguished_name req_extensions = v3_req [req_distinguished_name] C=US C_default = US ST=Michigan ST_default=Michigan L=Ann Arbor L_default=Ann Arbor O=EFF O_default=EFF OU=University of Michigan OU_default=University of Michigan CN=example.com CN_default=example.com [ v3_req ] subjectAltName = @alt_names [alt_names] DNS.1 = example.com DNS.2 = example.org DNS.3 = example.net DNS.4 = example.info DNS.5 = subdomain.example.com DNS.6 = other.subdomain.example.comcertbot-0.27.0/certbot/tests/testdata/nistp256_key.pem0000644000175000017500000000034313344054434023020 0ustar ericaerica00000000000000-----BEGIN EC PRIVATE KEY----- MHcCAQEEIOvXH384CyNNv2lfxvjc7hg2f7ScYoLvlk/VpINLJlGBoAoGCCqGSM49 AwEHoUQDQgAEPPl0JauSZukvAUWv4l5VNLAYQXhuPXYQBf4dVET3s0E5q9ZCbSe+ pNUbko9F+TFkuc7XVjQPsfkDbh0I9nD0tw== -----END EC PRIVATE KEY----- certbot-0.27.0/certbot/tests/testdata/cert_2048.pem0000644000175000017500000000226013344054434022170 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE----- MIIDSjCCAjKgAwIBAgIJAIYLtIQHBBG0MA0GCSqGSIb3DQEBCwUAMDoxCzAJBgNV BAYTAkNBMQswCQYDVQQIDAJPTjEQMA4GA1UEBwwHVG9yb250bzEMMAoGA1UECgwD RUZGMB4XDTE3MDUyOTA3NDIwMVoXDTQ4MDMzMDA3NDIwMVowOjELMAkGA1UEBhMC Q0ExCzAJBgNVBAgMAk9OMRAwDgYDVQQHDAdUb3JvbnRvMQwwCgYDVQQKDANFRkYw ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDm1WIecnHjL4FsJvxDP27G yeqnXKc41HsRP9cv4z+NDjE94mDgva5ndieiA9xZ0Sh7LXtZcGDcpGop+D7s+oh0 apV6idIJ9eEPUegYlGxOFJQnZ8re6hD7MaAlNZEVhZrwJvrGy6rTFpi3DaNokGn7 r3s2nrQ9aziljkWRp1PnTBnRNgOdi3c1IB2f4+2PdykjihxlnYUuI4Wf5QU5pFx6 0a2mdTVDC+bKAP22IvuQnnkHgJYYS/oMxFCT9QR4xQRPOx7U2RWVrFDVMJ3mIB8F OW6JXfQSmaZZr46xclbEIr4QQ6RcPWvcJ1cCV1idFjEmufi52sV7r1Bf3nCJFk1f AgMBAAGjUzBRMB0GA1UdDgQWBBSdJ++M23AW3LkFD7LKhsH7gL6/2jAfBgNVHSME GDAWgBSdJ++M23AW3LkFD7LKhsH7gL6/2jAPBgNVHRMBAf8EBTADAQH/MA0GCSqG SIb3DQEBCwUAA4IBAQCV5kSt1HTFzUPdBvxT455YrLd3jIsRt1pRNuGjVaUYIRxh vds8NN1Z8h/8Cdzz8NVkIdCuYb2lFaDjs3zNVUQxCyVcH7xVyPwFI85NR27+HPRv xzz2rwzST+NKYst6ZBg086BKjqFtxs16lpU/TD6tOJqg86TBbfP6gib/ocGeER2D HEEik69FjmUCziT6uXyYW5y1PxD15UWO3RWoTpao0vGtTPceTeeuO05PVeCUlx8X YXg9zoVWBba0GF+qQJ67zT5nvfc2KJcgnWRIRr/90YXzBf+FdFVuC4xFHINBI1OJ 5XBLJOv61Zu+Du/nmlBVcb8KL/Vd2oZyfoH+0oCN -----END CERTIFICATE----- certbot-0.27.0/certbot/tests/testdata/cert-san_512.pem0000644000175000017500000000142213344054434022660 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE----- MIICFjCCAcCgAwIBAgICBTkwDQYJKoZIhvcNAQELBQAwdzELMAkGA1UEBhMCVVMx ETAPBgNVBAgMCE1pY2hpZ2FuMRIwEAYDVQQHDAlBbm4gQXJib3IxKzApBgNVBAoM IlVuaXZlcnNpdHkgb2YgTWljaGlnYW4gYW5kIHRoZSBFRkYxFDASBgNVBAMMC2V4 YW1wbGUuY29tMB4XDTE0MTIxMTIyMzQ0NVoXDTE0MTIxODIyMzQ0NVowdzELMAkG A1UEBhMCVVMxETAPBgNVBAgMCE1pY2hpZ2FuMRIwEAYDVQQHDAlBbm4gQXJib3Ix KzApBgNVBAoMIlVuaXZlcnNpdHkgb2YgTWljaGlnYW4gYW5kIHRoZSBFRkYxFDAS BgNVBAMMC2V4YW1wbGUuY29tMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKx1c7RR 7R/drnBSQ/zfx1vQLHUbFLh1AQQQ5R8DZUXd36efNK79vukFhN9HFoHZiUvOjm0c +pVE6K+EdE/twuUCAwEAAaM2MDQwCQYDVR0TBAIwADAnBgNVHREEIDAeggtleGFt cGxlLmNvbYIPd3d3LmV4YW1wbGUuY29tMA0GCSqGSIb3DQEBCwUAA0EASuvNKFTF nTJsvnSXn52f4BMZJJ2id/kW7+r+FJRm+L20gKQ1aqq8d3e/lzRUrv5SMf1TAOe7 RDjyGMKy5ZgM2w== -----END CERTIFICATE----- certbot-0.27.0/certbot/tests/testdata/csr-san_512.pem0000644000175000017500000000107613344054434022517 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE REQUEST----- MIIBbjCCARgCAQAweTELMAkGA1UEBhMCVVMxETAPBgNVBAgMCE1pY2hpZ2FuMRIw EAYDVQQHDAlBbm4gQXJib3IxDDAKBgNVBAoMA0VGRjEfMB0GA1UECwwWVW5pdmVy c2l0eSBvZiBNaWNoaWdhbjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wXDANBgkqhkiG 9w0BAQEFAANLADBIAkEArHVztFHtH92ucFJD/N/HW9AsdRsUuHUBBBDlHwNlRd3f p580rv2+6QWE30cWgdmJS86ObRz6lUTor4R0T+3C5QIDAQABoDowOAYJKoZIhvcN AQkOMSswKTAnBgNVHREEIDAeggtleGFtcGxlLmNvbYIPd3d3LmV4YW1wbGUuY29t MA0GCSqGSIb3DQEBCwUAA0EAZGBM8J1rRs7onFgtc76mOeoT1c3v0ZsEmxQfb2Wy tmReY6X1N4cs38D9VSow+VMRu2LWkKvzS7RUFSaTaeQz1A== -----END CERTIFICATE REQUEST----- certbot-0.27.0/certbot/tests/testdata/rsa512_key.pem0000644000175000017500000000075513344054434022452 0ustar ericaerica00000000000000-----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAKx1c7RR7R/drnBSQ/zfx1vQLHUbFLh1AQQQ5R8DZUXd36efNK79 vukFhN9HFoHZiUvOjm0c+pVE6K+EdE/twuUCAwEAAQJAMbrEnJCrQe8YqAbw1/Bn elAzIamndfE3U8bTavf9sgFpS4HL83rhd6PDbvx81ucaJAT/5x048fM/nFl4fzAc mQIhAOF/a9o3EIsDKEmUl+Z1OaOiUxDF3kqWSmALEsmvDhwXAiEAw8ljV5RO/rUp Zu2YMDFq3MKpyyMgBIJ8CxmGRc6gCmMCIGRQzkcmhfqBrhOFwkmozrqIBRIKJIjj 8TRm2LXWZZ2DAiAqVO7PztdNpynugUy4jtbGKKjBrTSNBRGA7OHlUgm0dQIhALQq 6oGU29Vxlvt3k0vmiRKU4AVfLyNXIGtcWcNG46h/ -----END RSA PRIVATE KEY----- certbot-0.27.0/certbot/tests/testdata/cert-5sans_512.pem0000644000175000017500000000167013344054434023135 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE----- MIICkTCCAjugAwIBAgIJAJNbfABWQ8bbMA0GCSqGSIb3DQEBCwUAMHkxCzAJBgNV BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNp c2NvMScwJQYDVQQKDB5FbGVjdHJvbmljIEZyb250aWVyIEZvdW5kYXRpb24xFDAS BgNVBAMMC2V4YW1wbGUuY29tMB4XDTE2MDYwOTIzMDEzNloXDTE2MDcwOTIzMDEz NloweTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcM DVNhbiBGcmFuY2lzY28xJzAlBgNVBAoMHkVsZWN0cm9uaWMgRnJvbnRpZXIgRm91 bmRhdGlvbjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wXDANBgkqhkiG9w0BAQEFAANL ADBIAkEArHVztFHtH92ucFJD/N/HW9AsdRsUuHUBBBDlHwNlRd3fp580rv2+6QWE 30cWgdmJS86ObRz6lUTor4R0T+3C5QIDAQABo4GlMIGiMB0GA1UdDgQWBBQmz8jt S9eUsuQlA1gkjwTAdNWXijAfBgNVHSMEGDAWgBQmz8jtS9eUsuQlA1gkjwTAdNWX ijAMBgNVHRMEBTADAQH/MFIGA1UdEQRLMEmCDWEuZXhhbXBsZS5jb22CDWIuZXhh bXBsZS5jb22CDWMuZXhhbXBsZS5jb22CDWQuZXhhbXBsZS5jb22CC2V4YW1wbGUu Y29tMA0GCSqGSIb3DQEBCwUAA0EAVXmZxB+IJdgFvY2InOYeytTD1QmouDZRtj/T H/HIpSdsfO7qr4d/ZprI2IhLRxp2S4BiU5Qc5HUkeADcpNd06A== -----END CERTIFICATE----- certbot-0.27.0/certbot/tests/testdata/webrootconftest.ini0000644000175000017500000000006613344054434024005 0ustar ericaerica00000000000000webroot webroot-path = /tmp domains = eg.com, eg2.com certbot-0.27.0/certbot/tests/testdata/rsa2048_key.pem0000644000175000017500000000325413344054434022535 0ustar ericaerica00000000000000-----BEGIN PRIVATE KEY----- MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDm1WIecnHjL4Fs JvxDP27GyeqnXKc41HsRP9cv4z+NDjE94mDgva5ndieiA9xZ0Sh7LXtZcGDcpGop +D7s+oh0apV6idIJ9eEPUegYlGxOFJQnZ8re6hD7MaAlNZEVhZrwJvrGy6rTFpi3 DaNokGn7r3s2nrQ9aziljkWRp1PnTBnRNgOdi3c1IB2f4+2PdykjihxlnYUuI4Wf 5QU5pFx60a2mdTVDC+bKAP22IvuQnnkHgJYYS/oMxFCT9QR4xQRPOx7U2RWVrFDV MJ3mIB8FOW6JXfQSmaZZr46xclbEIr4QQ6RcPWvcJ1cCV1idFjEmufi52sV7r1Bf 3nCJFk1fAgMBAAECggEAJkhbVntagfgd+cbZbXm2sIdKQGlwXk92/Zxd3tZMcuNY rU+/C2bJ5uTEm+0R/V9f3FXlsCagGde2t7ExFnJScSRAGCuFRxudMMI/wNvUvnpR O9vN3HxrRo2rZqBkqHIZCR0d2Bxs/0cvGqTLZgsVWKV4xM07TThcE7DtvsNGegRn WFxfsRcRypkIvZoba1HagvCituRBEa07R7mQp8kRhP9ZeRq3bZws9qBmqzj1cylG q8QA4Foq7sK8P78bpIhrcOFBDAr+Vr1ZGY6u01J0w13MUtl6iIx4VCjQKt4NkzsK dj2q+GAMwhReR2ZS42o8LiyGpwusj+dKIFfFekgK2QKBgQD4wwmRDgvt85brQTNF Tkhui0eToz5oXt8mVDb58nwkpojFQOv87ZyNsEqm7S0t/3RtEViVio2aymTMsrz4 21vRq46dvhINQ3DoMok6xIchEOEgMeonOilkURWtrMjD/Kn297Asv7zOqI5BCNiP 3FFcRqf+CaqbhnOgMkcI5z6b7QKBgQDtjM1otFFHyS7ctyLRuMeFyxWUSbWHvi8U xjUW256c6wpQ2DBLSVB61VQjfrSjkZ5DJVFGnbw42HxSDafL11mzTbY1vDbgtgLK YiuVHG7OYZJTLaZoM68BseX4xHN8FztnvvP1ttuk5oFb+vD8q6ODZSEawRd3PvtX D7RtNouc+wKBgQDiwBWGTUF+gt18T5BGilbnvLlf0Btg06mgrH74UpnqZoqhEs6J XKWpWZqSkfruxL4BdSBEH2l4QSiklgA+7uTBOBnlm42k3WaboQUJtn5eG5651AXV /+Qe9vJFvwu56iObZKcIAzY9QdN5YHDWoULgU99pZrJG1cWrrmilqvOc+QKBgQCB iOslslY0N+926eJxzDn4qkJtJzh2+e1AfcjLWx0F4mEwroK/Ow5IvPVxmZE1NJ3B baMBR9gwg1RfhhS+4gKG9NRsPuMJ7BZfd+LeH7AImEorU1RPtAc1fGW0HqP+wchi DU2I6pqhNBTMLG2myo2Sg93mce6y1sRFuEmh2EGPawKBgQC3uUEdjQekXaxXfYHi 1Dk3Ht1a9t8XxwoCVRqicE7lqlwDtS2y9lHAeUP7JNy8ZGNjx8srRZpkYVMztugo Ecw26UA7FbNqJP5OPkGjfiFqtOq70h9vlfLdiAPmoqyOx//RkgiNXt9m5xcDzzdB 7EtBK59KSiQkB8fHtooy7Ipiiw== -----END PRIVATE KEY----- certbot-0.27.0/certbot/tests/testdata/README0000644000175000017500000000071613344054434020737 0ustar ericaerica00000000000000The following command has been used to generate test keys: for x in 256 512 2048; do openssl genrsa -out rsa${k}_key.pem $k; done and for the CSR PEM (Certificate Signing Request): openssl req -new -out csr-Xsans_X.pem -key rsa512_key.pem [-config csr-Xsans_X.conf | -subj '/CN=example.com'] [-outform DER > csr_X.der] and for the certificate: openssl req -new -out cert_X.pem -key rsaX_key.pem -subj '/CN=example.com' -x509 [-outform DER > cert_X.der]certbot-0.27.0/certbot/tests/testdata/sample-renewal.conf0000644000175000017500000000365113344054434023643 0ustar ericaerica00000000000000cert = MAGICDIR/live/sample-renewal/cert.pem privkey = MAGICDIR/live/sample-renewal/privkey.pem chain = MAGICDIR/live/sample-renewal/chain.pem fullchain = MAGICDIR/live/sample-renewal/fullchain.pem renew_before_expiry = 4 years # Options and defaults used in the renewal process [renewalparams] no_self_upgrade = False apache_enmod = a2enmod no_verify_ssl = False ifaces = None apache_dismod = a2dismod register_unsafely_without_email = False apache_handle_modules = True uir = None installer = None nginx_ctl = nginx config_dir = MAGICDIR text_mode = False func = staging = True prepare = False work_dir = /var/lib/letsencrypt tos = False init = False http01_port = 80 duplicate = False noninteractive_mode = True key_path = None nginx = False nginx_server_root = /etc/nginx fullchain_path = /home/ubuntu/letsencrypt/chain.pem email = None csr = None agree_dev_preview = None redirect = None verb = certonly verbose_count = -3 config_file = None renew_by_default = False hsts = False apache_handle_sites = True authenticator = standalone domains = isnot.org, rsa_key_size = 2048 apache_challenge_location = /etc/apache2 checkpoints = 1 manual_test_mode = False apache = False cert_path = /home/ubuntu/letsencrypt/cert.pem webroot_path = None reinstall = False expand = False strict_permissions = False apache_server_root = /etc/apache2 account = None dry_run = False manual_public_ip_logging_ok = False chain_path = /home/ubuntu/letsencrypt/chain.pem break_my_certs = False standalone = True manual = False server = https://acme-staging-v02.api.letsencrypt.org/directory standalone_supported_challenges = "tls-sni-01,http-01" webroot = False os_packages_only = False apache_init_script = None user_agent = None apache_le_vhost_ext = -le-ssl.conf debug = False tls_sni_01_port = 443 logs_dir = /var/log/letsencrypt apache_vhost_root = /etc/apache2/sites-available configurator = None must_staple = True [[webroot_map]] certbot-0.27.0/certbot/tests/testdata/sample-renewal-ancient.conf0000644000175000017500000000364213344054434025262 0ustar ericaerica00000000000000cert = MAGICDIR/live/sample-renewal-ancient/cert.pem privkey = MAGICDIR/live/sample-renewal-ancient/privkey.pem chain = MAGICDIR/live/sample-renewal-ancient/chain.pem fullchain = MAGICDIR/live/sample-renewal-ancient/fullchain.pem renew_before_expiry = 1 year # Options and defaults used in the renewal process [renewalparams] no_self_upgrade = False apache_enmod = a2enmod no_verify_ssl = False ifaces = None apache_dismod = a2dismod register_unsafely_without_email = False apache_handle_modules = True uir = None installer = None nginx_ctl = nginx config_dir = MAGICDIR text_mode = False func = staging = True prepare = False work_dir = /var/lib/letsencrypt tos = False init = False http01_port = 80 duplicate = False noninteractive_mode = True key_path = None nginx = False nginx_server_root = /etc/nginx fullchain_path = /home/ubuntu/letsencrypt/chain.pem email = None csr = None agree_dev_preview = None redirect = None verb = certonly verbose_count = -3 config_file = None renew_by_default = False hsts = False apache_handle_sites = True authenticator = webroot domains = isnot.org, rsa_key_size = 2048 apache_challenge_location = /etc/apache2 checkpoints = 1 manual_test_mode = False apache = False cert_path = /home/ubuntu/letsencrypt/cert.pem webroot_path = /var/www/ reinstall = False expand = False strict_permissions = False apache_server_root = /etc/apache2 account = None dry_run = False manual_public_ip_logging_ok = False chain_path = /home/ubuntu/letsencrypt/chain.pem break_my_certs = False standalone = True manual = False server = https://acme-staging.api.letsencrypt.org/directory standalone_supported_challenges = "tls-sni-01,http-01" webroot = True os_packages_only = False apache_init_script = None user_agent = None apache_le_vhost_ext = -le-ssl.conf debug = False tls_sni_01_port = 443 logs_dir = /var/log/letsencrypt apache_vhost_root = /etc/apache2/sites-available configurator = None certbot-0.27.0/certbot/tests/testdata/csr-nosans_512.pem0000644000175000017500000000075513344054434023242 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE REQUEST----- MIIBMzCB3gIBADB5MQswCQYDVQQGEwJVUzERMA8GA1UECAwITWljaGlnYW4xEjAQ BgNVBAcMCUFubiBBcmJvcjEMMAoGA1UECgwDRUZGMR8wHQYDVQQLDBZVbml2ZXJz aXR5IHBmIE1pY2hpZ2FuMRQwEgYDVQQDDAtleGFtcGxlLmNvbTBcMA0GCSqGSIb3 DQEBAQUAA0sAMEgCQQCsdXO0Ue0f3a5wUkP838db0Cx1GxS4dQEEEOUfA2VF3d+n nzSu/b7pBYTfRxaB2YlLzo5tHPqVROivhHRP7cLlAgMBAAGgADANBgkqhkiG9w0B AQsFAANBAG06jIPvSC6wiGLy7sUTaEX4UCE6Cztp3vh/uXN7Q++CGn6KiXNs/BRW eFlcFPbvxbVG/ZZFR5aPs+Oy6RhqOjg= -----END CERTIFICATE REQUEST----- certbot-0.27.0/certbot/tests/testdata/sample-archive/0002755000175000017500000000000013344054435022756 5ustar ericaerica00000000000000certbot-0.27.0/certbot/tests/testdata/sample-archive/chain1.pem0000644000175000017500000000214313344054434024621 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE----- MIIDETCCAfmgAwIBAgIJAJzxkS6o1QkIMA0GCSqGSIb3DQEBCwUAMB8xHTAbBgNV BAMMFGhhcHB5IGhhY2tlciBmYWtlIENBMB4XDTE1MDQwNzIzNTAzOFoXDTI1MDQw NDIzNTAzOFowHzEdMBsGA1UEAwwUaGFwcHkgaGFja2VyIGZha2UgQ0EwggEiMA0G CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDCCkd5mgXFErJ3F2M0E9dw+Ta/md5i 8TDId01HberAApqmydG7UZYF3zLTSzNjlNSOmtybvrSGUnZ9r9tSQcL8VM6WUOM8 tnIpiIjEA2QkBycMwvRmZ/B2ltPdYs/R9BqNwO1g18GDZrHSzUYtNKNeFI6Glamj 7GK2Vr0SmiEamlNIR5ktAFsEErzf/d4jCF7sosMsJpMCm1p58QkP4LHLShVLXDa8 BMfVoI+ipYcA08iNUFkgW8VWDclIDxcysa0psDDtMjX3+4aPkE/cefmP+1xOfUuD HOGV8XFynsP4EpTfVOZr0/g9gYQ7ZArqXX7GTQkFqduwPm/w5qxSPTarAgMBAAGj UDBOMB0GA1UdDgQWBBT7eE8S+WAVgyyfF380GbMuNupBiTAfBgNVHSMEGDAWgBT7 eE8S+WAVgyyfF380GbMuNupBiTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUA A4IBAQAd9Da+Zv+TjMv7NTAmliqnWHY6d3UxEZN3hFEJ58IQVHbBZVZdW7zhRktB vR05Kweac0HJeK91TKmzvXl21IXLvh0gcNLU/uweD3no/snfdB4OoFompljThmgl zBqiqWoKBJQrLCA8w5UB+ReomRYd/EYXF/6TAfzm6hr//Xt5mPiUHPdvYt75lMAo vRxLSbF8TSQ6b7BYxISWjPgFASNNqJNHEItWsmQMtAjjwzb9cs01XH9pChVAWn9L oeMKa+SlHSYrWG93+EcrIH/dGU76uNOiaDzBSKvaehG53h25MHuO1anNICJvZovW rFo4Uv1EnkKJm3vJFe50eJGhEKlx -----END CERTIFICATE----- certbot-0.27.0/certbot/tests/testdata/sample-archive/fullchain1.pem0000644000175000017500000000545313344054434025513 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE----- MIIE1DCCA7ygAwIBAgITAPoz/CBluNQV/Eh9F+CS6dSxEDANBgkqhkiG9w0BAQsF ADAfMR0wGwYDVQQDDBRoYXBweSBoYWNrZXIgZmFrZSBDQTAeFw0xNjAyMDIyMzQ5 MDBaFw0xNjA1MDIyMzQ5MDBaMBQxEjAQBgNVBAMTCWlzbm90Lm9yZzCCASIwDQYJ KoZIhvcNAQEBBQADggEPADCCAQoCggEBALyudqLKcIdWZ5VaK1fuhlEDbZtvs2E+ slm4dmSS1nFve7MdlZ69K0gdtnhkiPQ0wGQTligeDZ8fY8iL87GZO0tp5f7S+QJN NYCiYw6j4qp5JBy/zG22kJz1Quu7/vXMYLzLvK6x6YixiWAWyqqvlUVBLS1r4W3h A5Z+F1EIsXeyz7TJe3lAzIWAAxpfH9OviIz2rEDotuCdU771USLLNSw4qJojNlTx UpZG6lGFs8KGb8tqROXknaMKE4PvN3SITixSUTFbktt1Wz60moWbNdLMKvgkzuUP r4viO2P4SO5slNAY0ZeEssPpVAelN3EvrAcEZtoKmG5fnQDVo8uVag0CAwEAAaOC AhIwggIOMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB BQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUqhI4u6aaPrcYQnmypxV8Tap8 L54wHwYDVR0jBBgwFoAU+3hPEvlgFYMsnxd/NBmzLjbqQYkweAYIKwYBBQUHAQEE bDBqMDMGCCsGAQUFBzABhidodHRwOi8vb2NzcC5zdGFnaW5nLXgxLmxldHNlbmNy eXB0Lm9yZy8wMwYIKwYBBQUHMAKGJ2h0dHA6Ly9jZXJ0LnN0YWdpbmcteDEubGV0 c2VuY3J5cHQub3JnLzAUBgNVHREEDTALgglpc25vdC5vcmcwgf4GA1UdIASB9jCB 8zAIBgZngQwBAgEwgeYGCysGAQQBgt8TAQEBMIHWMCYGCCsGAQUFBwIBFhpodHRw Oi8vY3BzLmxldHNlbmNyeXB0Lm9yZzCBqwYIKwYBBQUHAgIwgZ4MgZtUaGlzIENl cnRpZmljYXRlIG1heSBvbmx5IGJlIHJlbGllZCB1cG9uIGJ5IFJlbHlpbmcgUGFy dGllcyBhbmQgb25seSBpbiBhY2NvcmRhbmNlIHdpdGggdGhlIENlcnRpZmljYXRl IFBvbGljeSBmb3VuZCBhdCBodHRwczovL2xldHNlbmNyeXB0Lm9yZy9yZXBvc2l0 b3J5LzANBgkqhkiG9w0BAQsFAAOCAQEAbAhX6FfQwELayneY4l5RvYSdw/Jj5CRy KzrM7ISld7x9YPpxX6Pmht/YyMhLWrtxvFUR2+RNhSIYB8IjQEjmKjvR7UNeiUve jzPEAuTg/9m3i0FJpPHc2aKGzlLFQCMm5/RrvnXI6ljIcyhocLvMiN46iexcExI2 Ese3w8GoH6wARYKxU/QBexfoXQLgtAbYzNRE6EgKWtB+txV+7+d2MgbhCEit5VwU +ydT8inp9URsA7iKM03hDdGOBysddkrm1/yEhVy/Oo6bT9WMAUHVvz61hHekWcSf rAQ6BayubvWOUx06eTowXr1gln/rl+WXOxcsJeag127NuhmHOCXZxQ== -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIDETCCAfmgAwIBAgIJAJzxkS6o1QkIMA0GCSqGSIb3DQEBCwUAMB8xHTAbBgNV BAMMFGhhcHB5IGhhY2tlciBmYWtlIENBMB4XDTE1MDQwNzIzNTAzOFoXDTI1MDQw NDIzNTAzOFowHzEdMBsGA1UEAwwUaGFwcHkgaGFja2VyIGZha2UgQ0EwggEiMA0G CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDCCkd5mgXFErJ3F2M0E9dw+Ta/md5i 8TDId01HberAApqmydG7UZYF3zLTSzNjlNSOmtybvrSGUnZ9r9tSQcL8VM6WUOM8 tnIpiIjEA2QkBycMwvRmZ/B2ltPdYs/R9BqNwO1g18GDZrHSzUYtNKNeFI6Glamj 7GK2Vr0SmiEamlNIR5ktAFsEErzf/d4jCF7sosMsJpMCm1p58QkP4LHLShVLXDa8 BMfVoI+ipYcA08iNUFkgW8VWDclIDxcysa0psDDtMjX3+4aPkE/cefmP+1xOfUuD HOGV8XFynsP4EpTfVOZr0/g9gYQ7ZArqXX7GTQkFqduwPm/w5qxSPTarAgMBAAGj UDBOMB0GA1UdDgQWBBT7eE8S+WAVgyyfF380GbMuNupBiTAfBgNVHSMEGDAWgBT7 eE8S+WAVgyyfF380GbMuNupBiTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUA A4IBAQAd9Da+Zv+TjMv7NTAmliqnWHY6d3UxEZN3hFEJ58IQVHbBZVZdW7zhRktB vR05Kweac0HJeK91TKmzvXl21IXLvh0gcNLU/uweD3no/snfdB4OoFompljThmgl zBqiqWoKBJQrLCA8w5UB+ReomRYd/EYXF/6TAfzm6hr//Xt5mPiUHPdvYt75lMAo vRxLSbF8TSQ6b7BYxISWjPgFASNNqJNHEItWsmQMtAjjwzb9cs01XH9pChVAWn9L oeMKa+SlHSYrWG93+EcrIH/dGU76uNOiaDzBSKvaehG53h25MHuO1anNICJvZovW rFo4Uv1EnkKJm3vJFe50eJGhEKlx -----END CERTIFICATE----- certbot-0.27.0/certbot/tests/testdata/sample-archive/cert1.pem0000644000175000017500000000331013344054434024471 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE----- MIIE1DCCA7ygAwIBAgITAPoz/CBluNQV/Eh9F+CS6dSxEDANBgkqhkiG9w0BAQsF ADAfMR0wGwYDVQQDDBRoYXBweSBoYWNrZXIgZmFrZSBDQTAeFw0xNjAyMDIyMzQ5 MDBaFw0xNjA1MDIyMzQ5MDBaMBQxEjAQBgNVBAMTCWlzbm90Lm9yZzCCASIwDQYJ KoZIhvcNAQEBBQADggEPADCCAQoCggEBALyudqLKcIdWZ5VaK1fuhlEDbZtvs2E+ slm4dmSS1nFve7MdlZ69K0gdtnhkiPQ0wGQTligeDZ8fY8iL87GZO0tp5f7S+QJN NYCiYw6j4qp5JBy/zG22kJz1Quu7/vXMYLzLvK6x6YixiWAWyqqvlUVBLS1r4W3h A5Z+F1EIsXeyz7TJe3lAzIWAAxpfH9OviIz2rEDotuCdU771USLLNSw4qJojNlTx UpZG6lGFs8KGb8tqROXknaMKE4PvN3SITixSUTFbktt1Wz60moWbNdLMKvgkzuUP r4viO2P4SO5slNAY0ZeEssPpVAelN3EvrAcEZtoKmG5fnQDVo8uVag0CAwEAAaOC AhIwggIOMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB BQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUqhI4u6aaPrcYQnmypxV8Tap8 L54wHwYDVR0jBBgwFoAU+3hPEvlgFYMsnxd/NBmzLjbqQYkweAYIKwYBBQUHAQEE bDBqMDMGCCsGAQUFBzABhidodHRwOi8vb2NzcC5zdGFnaW5nLXgxLmxldHNlbmNy eXB0Lm9yZy8wMwYIKwYBBQUHMAKGJ2h0dHA6Ly9jZXJ0LnN0YWdpbmcteDEubGV0 c2VuY3J5cHQub3JnLzAUBgNVHREEDTALgglpc25vdC5vcmcwgf4GA1UdIASB9jCB 8zAIBgZngQwBAgEwgeYGCysGAQQBgt8TAQEBMIHWMCYGCCsGAQUFBwIBFhpodHRw Oi8vY3BzLmxldHNlbmNyeXB0Lm9yZzCBqwYIKwYBBQUHAgIwgZ4MgZtUaGlzIENl cnRpZmljYXRlIG1heSBvbmx5IGJlIHJlbGllZCB1cG9uIGJ5IFJlbHlpbmcgUGFy dGllcyBhbmQgb25seSBpbiBhY2NvcmRhbmNlIHdpdGggdGhlIENlcnRpZmljYXRl IFBvbGljeSBmb3VuZCBhdCBodHRwczovL2xldHNlbmNyeXB0Lm9yZy9yZXBvc2l0 b3J5LzANBgkqhkiG9w0BAQsFAAOCAQEAbAhX6FfQwELayneY4l5RvYSdw/Jj5CRy KzrM7ISld7x9YPpxX6Pmht/YyMhLWrtxvFUR2+RNhSIYB8IjQEjmKjvR7UNeiUve jzPEAuTg/9m3i0FJpPHc2aKGzlLFQCMm5/RrvnXI6ljIcyhocLvMiN46iexcExI2 Ese3w8GoH6wARYKxU/QBexfoXQLgtAbYzNRE6EgKWtB+txV+7+d2MgbhCEit5VwU +ydT8inp9URsA7iKM03hDdGOBysddkrm1/yEhVy/Oo6bT9WMAUHVvz61hHekWcSf rAQ6BayubvWOUx06eTowXr1gln/rl+WXOxcsJeag127NuhmHOCXZxQ== -----END CERTIFICATE----- certbot-0.27.0/certbot/tests/testdata/sample-archive/privkey1.pem0000644000175000017500000000325013344054434025230 0ustar ericaerica00000000000000-----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC8rnaiynCHVmeV WitX7oZRA22bb7NhPrJZuHZkktZxb3uzHZWevStIHbZ4ZIj0NMBkE5YoHg2fH2PI i/OxmTtLaeX+0vkCTTWAomMOo+KqeSQcv8xttpCc9ULru/71zGC8y7yusemIsYlg Fsqqr5VFQS0ta+Ft4QOWfhdRCLF3ss+0yXt5QMyFgAMaXx/Tr4iM9qxA6LbgnVO+ 9VEiyzUsOKiaIzZU8VKWRupRhbPChm/LakTl5J2jChOD7zd0iE4sUlExW5LbdVs+ tJqFmzXSzCr4JM7lD6+L4jtj+EjubJTQGNGXhLLD6VQHpTdxL6wHBGbaCphuX50A 1aPLlWoNAgMBAAECggEAfKKWFWS6PnwSAnNErFoQeZVVItb/XB5JO8EA2+CvLNFi mefR/MCixYlzDkYCvaXW7ISPrMJlZxYaGNBx0oAQzfkPB2wfNqj/zY/29SXGxast 8puzk0mEb1oHsaZGfeFaiXvfkFpPlI8J2uJTT7qaVNv/1sArciSv9QonpsyiRhlB yqT49juNVoR1tJHyXzkkRfHKTG8OlJd4kuFOl3fM9dTFPQ/ft0kTNAQ/B4SFvSwF RJsbLbsbFGsUdV9ekE6UX6oWD/Ah707rvgtCyS0Bc+0O3t2EKwmm3RXPRUMHCVxE bKdTxRB4etbjMVXMuVhB8Y4GbfrtMCy+qxZQ6znCAQKBgQDr7bcYAZVZp/nBMVB+ lBO9w73J6lnEWm6bZ9728KlGAKETaRhxZQSi6TN6MWwNwnk6rinyz4uVwVr9ZRCs WkB1TbvW0JNcWdr3YClwsKXAt8X22bjGe0LagDJHG6r1TPS+MdovOS2M6IMaxlbT rzFhSJ8ojLX3tqnOsmc7YAFLjQKBgQDMu8E9hoJt82lQzOGrjHmGzGEu2GLx9WKO e4nkj335kX6fIhMMqSXBFbTJZwXoYvk5J8ZnaARbYG0m5nxDCwRjX5HWa8q0B2Po ta53w01sKKznzlPjUhsdhEthun7MCFfLZpgvcZ9xVzOXo3/Zfn2+RrsPSjrVDqBy hj+k5mW4gQKBgHFWKf3LTO7cBdvsD8ou4mjn7nVgMi1kb/wR4wdnxzmMtdR4STi4 GYkVVBhgQ5M8mDY7UoWFdH3FfCt8cI0Lcimn5ROl8RSNSeZKeL3c7lNtNRmHr/8R WaVTrlOAlBjxFiWEF1dWNW6ah9jF7RIV+DfOxj6ZkhTk2CAmjfb1AMpFAoGABf96 KdNG/vGipDtcYSo8ZTaXoke0nmISARqdb5TEnAsnKoJVDInoEUARi9T411YO9x2z MlRZzFOG3xzhhxVLi53BKAcAaUXOJ4MrGVcfbYvDhQcGbiJ5qOO3UaWlEVUtPUhE LR+nDCsB1+9yT2zlQi3QTSJflt5W1QQZ2TrmwAECgYEAvQ7+sTcHs1K9yKj7koEu A19FbMA0IwvrVRcV/VqmlsoW6e6wW2YND+GtaDbKdD0aBPivqLJwpNFrsRA+W0iB vzmML6sKhhL+j7tjSgq+iQdBkKz0j9PyReuhe9CRnljMmyun+4qKEk0KUvxBrjPY Skn+ML18qyUoEPnmbpfHxCs= -----END PRIVATE KEY----- certbot-0.27.0/certbot/tests/testdata/cert_512.pem0000644000175000017500000000130513344054434022101 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE----- MIIB3jCCAYigAwIBAgICBTkwDQYJKoZIhvcNAQELBQAwdzELMAkGA1UEBhMCVVMx ETAPBgNVBAgMCE1pY2hpZ2FuMRIwEAYDVQQHDAlBbm4gQXJib3IxKzApBgNVBAoM IlVuaXZlcnNpdHkgb2YgTWljaGlnYW4gYW5kIHRoZSBFRkYxFDASBgNVBAMMC2V4 YW1wbGUuY29tMB4XDTE0MTIxMTIyMzQ0NVoXDTE0MTIxODIyMzQ0NVowdzELMAkG A1UEBhMCVVMxETAPBgNVBAgMCE1pY2hpZ2FuMRIwEAYDVQQHDAlBbm4gQXJib3Ix KzApBgNVBAoMIlVuaXZlcnNpdHkgb2YgTWljaGlnYW4gYW5kIHRoZSBFRkYxFDAS BgNVBAMMC2V4YW1wbGUuY29tMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKx1c7RR 7R/drnBSQ/zfx1vQLHUbFLh1AQQQ5R8DZUXd36efNK79vukFhN9HFoHZiUvOjm0c +pVE6K+EdE/twuUCAwEAATANBgkqhkiG9w0BAQsFAANBAC24z0IdwIVKSlntksll vr6zJepBH5fMndfk3XJp10jT6VE+14KNtjh02a56GoraAvJAT5/H67E8GvJ/ocNn B/o= -----END CERTIFICATE----- certbot-0.27.0/certbot/tests/testdata/cert-nosans_nistp256.pem0000644000175000017500000000115713344054434024470 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE----- MIIBoDCCAUYCCQDCnzfUZ7TQdDAKBggqhkjOPQQDAjBYMQswCQYDVQQGEwJVUzER MA8GA1UECAwITWljaGlnYW4xEjAQBgNVBAcMCUFubiBBcmJvcjEMMAoGA1UECgwD RUZGMRQwEgYDVQQDDAtleGFtcGxlLmNvbTAeFw0xODA1MTUxNzIyMzlaFw0xODA2 MTQxNzIyMzlaMFgxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNaWNoaWdhbjESMBAG A1UEBwwJQW5uIEFyYm9yMQwwCgYDVQQKDANFRkYxFDASBgNVBAMMC2V4YW1wbGUu Y29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEPPl0JauSZukvAUWv4l5VNLAY QXhuPXYQBf4dVET3s0E5q9ZCbSe+pNUbko9F+TFkuc7XVjQPsfkDbh0I9nD0tzAK BggqhkjOPQQDAgNIADBFAiEAv8S2GXmWJqZ+j3DBfm72E1YK+HkOf+TOUHsbVR+O Z1oCIFWNt1SPdIgRp4QAyzVk2pcTF8jDNajEMLWETDtxgRvM -----END CERTIFICATE----- certbot-0.27.0/certbot/tests/testdata/csr-nosans_512.conf0000644000175000017500000000042513344054434023400 0ustar ericaerica00000000000000[req] distinguished_name = req_distinguished_name [req_distinguished_name] C=US C_default = US ST=Michigan ST_default=Michigan L=Ann Arbor L_default=Ann Arbor O=EFF O_default=EFF OU=University of Michigan OU_default=University of Michigan CN=example.com CN_default=example.comcertbot-0.27.0/certbot/tests/testdata/csr-nonames_512.pem0000644000175000017500000000064413344054434023376 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE REQUEST----- MIH/MIGqAgEAMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwXDANBgkqhkiG9w0BAQEF AANLADBIAkEArHVztFHtH92ucFJD/N/HW9AsdRsUuHUBBBDlHwNlRd3fp580rv2+ 6QWE30cWgdmJS86ObRz6lUTor4R0T+3C5QIDAQABoAAwDQYJKoZIhvcNAQELBQAD QQBt9XLSZ9DGfWcGGaBUTCiSY7lWBegpNlCeo8pK3ydWmKpjcza+j7lF5paph2LH lKWVQ8+xwYMscGWK0NApHGco -----END CERTIFICATE REQUEST----- certbot-0.27.0/certbot/tests/testdata/cert_512_bad.pem0000644000175000017500000000156713344054434022721 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE----- MIICYzCCAg2gAwIBAgIJAPvqv4TcAtuFMA0GCSqGSIb3DQEBCwUAMIGMMQswCQYD VQQGEwJDQTEQMA4GA1UECAwHT250YXJpbzEQMA4GA1UEBwwHVG9yb250bzEMMAoG A1UECgwDRUZGMRYwFAYDVQQLDA1UZWNoIFByb2plY3RzMQ4wDAYDVQQDDAVZb21u YTEjMCEGCSqGSIb3DQEJARYUeW9tbmEubmFzc2VyQGVmZi5vcmcwHhcNMTcwMzI0 MjIzMjUxWhcNNDgwMTI0MjIzMjUxWjCBjDELMAkGA1UEBhMCQ0ExEDAOBgNVBAgM B09udGFyaW8xEDAOBgNVBAcMB1Rvcm9udG8xDDAKBgNVBAoMA0VGRjEWMBQGA1UE CwwNVGVjaCBQcm9qZWN0czEOMAwGA1UEAwwFWW9tbmExIzAhBgkqhkiG9w0BCQEW FHlvbW5hLm5hc3NlckBlZmYub3JnMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKx1 c7RR7R/drnBSQ/zfx1vQLHUbFLh1AQQQ5R8DZUXd36efNK79vukFhN9HFoHZiUvO jm0c+pVE6K+EdE/twuUCAwEAAaNQME4wHQYDVR0OBBYEFCbPyO1L15Sy5CUDWCSP BMB01ZeKMB8GA1UdIwQYMBaAFCbPyO1L15Sy5CUDWCSPBMB01ZeKMAwGA1UdEwQF MAMBAf8wDQYJKoZIhvcNAQELBQADQQAeWDdcrJOolFHr3m8TrlDJ/Ca4SfJya2jb K1wahbX83sC42834HbDOQASGBhoLYDhC1cMPbKDDjMbR9rjYuf7T -----END CERTIFICATE----- certbot-0.27.0/certbot/tests/testdata/cert_fullchain_2048.pem0000644000175000017500000000454013344054434024220 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE----- MIIDSjCCAjKgAwIBAgIJAIYLtIQHBBG0MA0GCSqGSIb3DQEBCwUAMDoxCzAJBgNV BAYTAkNBMQswCQYDVQQIDAJPTjEQMA4GA1UEBwwHVG9yb250bzEMMAoGA1UECgwD RUZGMB4XDTE3MDUyOTA3NDIwMVoXDTQ4MDMzMDA3NDIwMVowOjELMAkGA1UEBhMC Q0ExCzAJBgNVBAgMAk9OMRAwDgYDVQQHDAdUb3JvbnRvMQwwCgYDVQQKDANFRkYw ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDm1WIecnHjL4FsJvxDP27G yeqnXKc41HsRP9cv4z+NDjE94mDgva5ndieiA9xZ0Sh7LXtZcGDcpGop+D7s+oh0 apV6idIJ9eEPUegYlGxOFJQnZ8re6hD7MaAlNZEVhZrwJvrGy6rTFpi3DaNokGn7 r3s2nrQ9aziljkWRp1PnTBnRNgOdi3c1IB2f4+2PdykjihxlnYUuI4Wf5QU5pFx6 0a2mdTVDC+bKAP22IvuQnnkHgJYYS/oMxFCT9QR4xQRPOx7U2RWVrFDVMJ3mIB8F OW6JXfQSmaZZr46xclbEIr4QQ6RcPWvcJ1cCV1idFjEmufi52sV7r1Bf3nCJFk1f AgMBAAGjUzBRMB0GA1UdDgQWBBSdJ++M23AW3LkFD7LKhsH7gL6/2jAfBgNVHSME GDAWgBSdJ++M23AW3LkFD7LKhsH7gL6/2jAPBgNVHRMBAf8EBTADAQH/MA0GCSqG SIb3DQEBCwUAA4IBAQCV5kSt1HTFzUPdBvxT455YrLd3jIsRt1pRNuGjVaUYIRxh vds8NN1Z8h/8Cdzz8NVkIdCuYb2lFaDjs3zNVUQxCyVcH7xVyPwFI85NR27+HPRv xzz2rwzST+NKYst6ZBg086BKjqFtxs16lpU/TD6tOJqg86TBbfP6gib/ocGeER2D HEEik69FjmUCziT6uXyYW5y1PxD15UWO3RWoTpao0vGtTPceTeeuO05PVeCUlx8X YXg9zoVWBba0GF+qQJ67zT5nvfc2KJcgnWRIRr/90YXzBf+FdFVuC4xFHINBI1OJ 5XBLJOv61Zu+Du/nmlBVcb8KL/Vd2oZyfoH+0oCN -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIDSjCCAjKgAwIBAgIJAIYLtIQHBBG0MA0GCSqGSIb3DQEBCwUAMDoxCzAJBgNV BAYTAkNBMQswCQYDVQQIDAJPTjEQMA4GA1UEBwwHVG9yb250bzEMMAoGA1UECgwD RUZGMB4XDTE3MDUyOTA3NDIwMVoXDTQ4MDMzMDA3NDIwMVowOjELMAkGA1UEBhMC Q0ExCzAJBgNVBAgMAk9OMRAwDgYDVQQHDAdUb3JvbnRvMQwwCgYDVQQKDANFRkYw ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDm1WIecnHjL4FsJvxDP27G yeqnXKc41HsRP9cv4z+NDjE94mDgva5ndieiA9xZ0Sh7LXtZcGDcpGop+D7s+oh0 apV6idIJ9eEPUegYlGxOFJQnZ8re6hD7MaAlNZEVhZrwJvrGy6rTFpi3DaNokGn7 r3s2nrQ9aziljkWRp1PnTBnRNgOdi3c1IB2f4+2PdykjihxlnYUuI4Wf5QU5pFx6 0a2mdTVDC+bKAP22IvuQnnkHgJYYS/oMxFCT9QR4xQRPOx7U2RWVrFDVMJ3mIB8F OW6JXfQSmaZZr46xclbEIr4QQ6RcPWvcJ1cCV1idFjEmufi52sV7r1Bf3nCJFk1f AgMBAAGjUzBRMB0GA1UdDgQWBBSdJ++M23AW3LkFD7LKhsH7gL6/2jAfBgNVHSME GDAWgBSdJ++M23AW3LkFD7LKhsH7gL6/2jAPBgNVHRMBAf8EBTADAQH/MA0GCSqG SIb3DQEBCwUAA4IBAQCV5kSt1HTFzUPdBvxT455YrLd3jIsRt1pRNuGjVaUYIRxh vds8NN1Z8h/8Cdzz8NVkIdCuYb2lFaDjs3zNVUQxCyVcH7xVyPwFI85NR27+HPRv xzz2rwzST+NKYst6ZBg086BKjqFtxs16lpU/TD6tOJqg86TBbfP6gib/ocGeER2D HEEik69FjmUCziT6uXyYW5y1PxD15UWO3RWoTpao0vGtTPceTeeuO05PVeCUlx8X YXg9zoVWBba0GF+qQJ67zT5nvfc2KJcgnWRIRr/90YXzBf+FdFVuC4xFHINBI1OJ 5XBLJOv61Zu+Du/nmlBVcb8KL/Vd2oZyfoH+0oCN -----END CERTIFICATE----- certbot-0.27.0/certbot/tests/testdata/csr_512.pem0000644000175000017500000000070413344054434021735 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE REQUEST----- MIIBFTCBwAIBADBbMQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEh MB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMRQwEgYDVQQDDAtFeGFt cGxlLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCsdXO0Ue0f3a5wUkP838db 0Cx1GxS4dQEEEOUfA2VF3d+nnzSu/b7pBYTfRxaB2YlLzo5tHPqVROivhHRP7cLl AgMBAAGgADANBgkqhkiG9w0BAQsFAANBAAceUlq4La8qaiK0DeDP3M19BIVzMmz2 oemG2fOvPiwNCB90ctSWQ6bMpUMV85ShcFi31C5vlntPfztehhq6YuE= -----END CERTIFICATE REQUEST----- certbot-0.27.0/certbot/tests/testdata/csr_512.der0000644000175000017500000000043113344054434021723 0ustar ericaerica00000000000000000[1 0 UAU10U Some-State1!0U Internet Widgits Pty Ltd10U Example.com0\0  *H K0HAusQݮpRC[,uueEߧ4GىKΎmD评tO0  *H  ARZ-*j" }s2l>, trԖC̥CpX.o{O;^bcertbot-0.27.0/certbot/tests/testdata/rsa256_key.pem0000644000175000017500000000045213344054434022451 0ustar ericaerica00000000000000-----BEGIN RSA PRIVATE KEY----- MIGrAgEAAiEAm2Fylv+Uz7trgTW8EBHP3FQSMeZs2GNQ6VRo1sIVJEkCAwEAAQIh AJT0BA/xD01dFCAXzSNyj9nfSZa3NpqzJZZn/eOm7vghAhEAzUVNZn4lLLBD1R6N E8TKNQIRAMHHyn3O5JeY36lwKwkUlEUCEAliRauN0L0+QZuYjfJ9aJECEGx4dru3 rTPCyighdqWNlHUCEQCiLjlwSRtWgmMBudCkVjzt -----END RSA PRIVATE KEY----- certbot-0.27.0/certbot/tests/testdata/csr-6sans_512.pem0000644000175000017500000000124413344054434022765 0ustar ericaerica00000000000000-----BEGIN CERTIFICATE REQUEST----- MIIBuzCCAWUCAQAweTELMAkGA1UEBhMCVVMxETAPBgNVBAgMCE1pY2hpZ2FuMRIw EAYDVQQHDAlBbm4gQXJib3IxDDAKBgNVBAoMA0VGRjEfMB0GA1UECwwWVW5pdmVy c2l0eSBvZiBNaWNoaWdhbjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wXDANBgkqhkiG 9w0BAQEFAANLADBIAkEArHVztFHtH92ucFJD/N/HW9AsdRsUuHUBBBDlHwNlRd3f p580rv2+6QWE30cWgdmJS86ObRz6lUTor4R0T+3C5QIDAQABoIGGMIGDBgkqhkiG 9w0BCQ4xdjB0MHIGA1UdEQRrMGmCC2V4YW1wbGUuY29tggtleGFtcGxlLm9yZ4IL ZXhhbXBsZS5uZXSCDGV4YW1wbGUuaW5mb4IVc3ViZG9tYWluLmV4YW1wbGUuY29t ghtvdGhlci5zdWJkb21haW4uZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADQQA+ sU6T30n3SsdnHlj0Va8eECOWK7Lf8nUfxxgjPMQ7BoU8gbAnGfDmOlwDronTRqf1 Me+nlYJU4TX1OiX10DYu -----END CERTIFICATE REQUEST----- certbot-0.27.0/certbot/tests/eff_test.py0000644000175000017500000001370113344054434020415 0ustar ericaerica00000000000000"""Tests for certbot.eff.""" import requests import unittest import mock from certbot import constants import certbot.tests.util as test_util class HandleSubscriptionTest(test_util.ConfigTestCase): """Tests for certbot.eff.handle_subscription.""" def setUp(self): super(HandleSubscriptionTest, self).setUp() self.email = 'certbot@example.org' self.config.email = self.email self.config.eff_email = None def _call(self): from certbot.eff import handle_subscription return handle_subscription(self.config) @test_util.patch_get_utility() @mock.patch('certbot.eff.subscribe') def test_failure(self, mock_subscribe, mock_get_utility): self.config.email = None self.config.eff_email = True self._call() self.assertFalse(mock_subscribe.called) self.assertFalse(mock_get_utility().yesno.called) actual = mock_get_utility().add_message.call_args[0][0] expected_part = "because you didn't provide an e-mail address" self.assertTrue(expected_part in actual) @mock.patch('certbot.eff.subscribe') def test_no_subscribe_with_no_prompt(self, mock_subscribe): self.config.eff_email = False with test_util.patch_get_utility() as mock_get_utility: self._call() self.assertFalse(mock_subscribe.called) self._assert_no_get_utility_calls(mock_get_utility) @test_util.patch_get_utility() @mock.patch('certbot.eff.subscribe') def test_subscribe_with_no_prompt(self, mock_subscribe, mock_get_utility): self.config.eff_email = True self._call() self._assert_subscribed(mock_subscribe) self._assert_no_get_utility_calls(mock_get_utility) def _assert_no_get_utility_calls(self, mock_get_utility): self.assertFalse(mock_get_utility().yesno.called) self.assertFalse(mock_get_utility().add_message.called) @test_util.patch_get_utility() @mock.patch('certbot.eff.subscribe') def test_subscribe_with_prompt(self, mock_subscribe, mock_get_utility): mock_get_utility().yesno.return_value = True self._call() self._assert_subscribed(mock_subscribe) self.assertFalse(mock_get_utility().add_message.called) self._assert_correct_yesno_call(mock_get_utility) def _assert_subscribed(self, mock_subscribe): self.assertTrue(mock_subscribe.called) self.assertEqual(mock_subscribe.call_args[0][0], self.email) @test_util.patch_get_utility() @mock.patch('certbot.eff.subscribe') def test_no_subscribe_with_prompt(self, mock_subscribe, mock_get_utility): mock_get_utility().yesno.return_value = False self._call() self.assertFalse(mock_subscribe.called) self.assertFalse(mock_get_utility().add_message.called) self._assert_correct_yesno_call(mock_get_utility) def _assert_correct_yesno_call(self, mock_get_utility): self.assertTrue(mock_get_utility().yesno.called) call_args, call_kwargs = mock_get_utility().yesno.call_args actual = call_args[0] expected_part = 'Electronic Frontier Foundation' self.assertTrue(expected_part in actual) self.assertFalse(call_kwargs.get('default', True)) class SubscribeTest(unittest.TestCase): """Tests for certbot.eff.subscribe.""" def setUp(self): self.email = 'certbot@example.org' self.json = {'status': True} self.response = mock.Mock(ok=True) self.response.json.return_value = self.json @mock.patch('certbot.eff.requests.post') def _call(self, mock_post): mock_post.return_value = self.response from certbot.eff import subscribe subscribe(self.email) self._check_post_call(mock_post) def _check_post_call(self, mock_post): self.assertEqual(mock_post.call_count, 1) call_args, call_kwargs = mock_post.call_args self.assertEqual(call_args[0], constants.EFF_SUBSCRIBE_URI) data = call_kwargs.get('data') self.assertFalse(data is None) self.assertEqual(data.get('email'), self.email) @test_util.patch_get_utility() def test_bad_status(self, mock_get_utility): self.json['status'] = False self._call() # pylint: disable=no-value-for-parameter actual = self._get_reported_message(mock_get_utility) expected_part = 'because your e-mail address appears to be invalid.' self.assertTrue(expected_part in actual) @test_util.patch_get_utility() def test_not_ok(self, mock_get_utility): self.response.ok = False self.response.raise_for_status.side_effect = requests.exceptions.HTTPError self._call() # pylint: disable=no-value-for-parameter actual = self._get_reported_message(mock_get_utility) unexpected_part = 'because' self.assertFalse(unexpected_part in actual) @test_util.patch_get_utility() def test_response_not_json(self, mock_get_utility): self.response.json.side_effect = ValueError() self._call() # pylint: disable=no-value-for-parameter actual = self._get_reported_message(mock_get_utility) expected_part = 'problem' self.assertTrue(expected_part in actual) @test_util.patch_get_utility() def test_response_json_missing_status_element(self, mock_get_utility): self.json.clear() self._call() # pylint: disable=no-value-for-parameter actual = self._get_reported_message(mock_get_utility) expected_part = 'problem' self.assertTrue(expected_part in actual) def _get_reported_message(self, mock_get_utility): self.assertTrue(mock_get_utility().add_message.called) return mock_get_utility().add_message.call_args[0][0] @test_util.patch_get_utility() def test_subscribe(self, mock_get_utility): self._call() # pylint: disable=no-value-for-parameter self.assertFalse(mock_get_utility.called) if __name__ == '__main__': unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/crypto_util_test.py0000644000175000017500000003307513344054434022240 0ustar ericaerica00000000000000"""Tests for certbot.crypto_util.""" import logging import os import unittest import OpenSSL import mock import zope.component from certbot import errors from certbot import interfaces from certbot import util import certbot.tests.util as test_util RSA256_KEY = test_util.load_vector('rsa256_key.pem') RSA256_KEY_PATH = test_util.vector_path('rsa256_key.pem') RSA512_KEY = test_util.load_vector('rsa512_key.pem') RSA2048_KEY_PATH = test_util.vector_path('rsa2048_key.pem') CERT_PATH = test_util.vector_path('cert_512.pem') CERT = test_util.load_vector('cert_512.pem') SS_CERT_PATH = test_util.vector_path('cert_2048.pem') SS_CERT = test_util.load_vector('cert_2048.pem') P256_KEY = test_util.load_vector('nistp256_key.pem') P256_CERT_PATH = test_util.vector_path('cert-nosans_nistp256.pem') P256_CERT = test_util.load_vector('cert-nosans_nistp256.pem') class InitSaveKeyTest(test_util.TempDirTestCase): """Tests for certbot.crypto_util.init_save_key.""" def setUp(self): super(InitSaveKeyTest, self).setUp() logging.disable(logging.CRITICAL) zope.component.provideUtility( mock.Mock(strict_permissions=True), interfaces.IConfig) def tearDown(self): super(InitSaveKeyTest, self).tearDown() logging.disable(logging.NOTSET) @classmethod def _call(cls, key_size, key_dir): from certbot.crypto_util import init_save_key return init_save_key(key_size, key_dir, 'key-certbot.pem') @mock.patch('certbot.crypto_util.make_key') def test_success(self, mock_make): mock_make.return_value = b'key_pem' key = self._call(1024, self.tempdir) self.assertEqual(key.pem, b'key_pem') self.assertTrue('key-certbot.pem' in key.file) self.assertTrue(os.path.exists(os.path.join(self.tempdir, key.file))) @mock.patch('certbot.crypto_util.make_key') def test_key_failure(self, mock_make): mock_make.side_effect = ValueError self.assertRaises(ValueError, self._call, 431, self.tempdir) class InitSaveCSRTest(test_util.TempDirTestCase): """Tests for certbot.crypto_util.init_save_csr.""" def setUp(self): super(InitSaveCSRTest, self).setUp() zope.component.provideUtility( mock.Mock(strict_permissions=True), interfaces.IConfig) @mock.patch('acme.crypto_util.make_csr') @mock.patch('certbot.crypto_util.util.make_or_verify_dir') def test_it(self, unused_mock_verify, mock_csr): from certbot.crypto_util import init_save_csr mock_csr.return_value = b'csr_pem' csr = init_save_csr( mock.Mock(pem='dummy_key'), 'example.com', self.tempdir) self.assertEqual(csr.data, b'csr_pem') self.assertTrue('csr-certbot.pem' in csr.file) class ValidCSRTest(unittest.TestCase): """Tests for certbot.crypto_util.valid_csr.""" @classmethod def _call(cls, csr): from certbot.crypto_util import valid_csr return valid_csr(csr) def test_valid_pem_true(self): self.assertTrue(self._call(test_util.load_vector('csr_512.pem'))) def test_valid_pem_san_true(self): self.assertTrue(self._call(test_util.load_vector('csr-san_512.pem'))) def test_valid_der_false(self): self.assertFalse(self._call(test_util.load_vector('csr_512.der'))) def test_empty_false(self): self.assertFalse(self._call('')) def test_random_false(self): self.assertFalse(self._call('foo bar')) class CSRMatchesPubkeyTest(unittest.TestCase): """Tests for certbot.crypto_util.csr_matches_pubkey.""" @classmethod def _call(cls, *args, **kwargs): from certbot.crypto_util import csr_matches_pubkey return csr_matches_pubkey(*args, **kwargs) def test_valid_true(self): self.assertTrue(self._call( test_util.load_vector('csr_512.pem'), RSA512_KEY)) def test_invalid_false(self): self.assertFalse(self._call( test_util.load_vector('csr_512.pem'), RSA256_KEY)) class ImportCSRFileTest(unittest.TestCase): """Tests for certbot.certbot_util.import_csr_file.""" @classmethod def _call(cls, *args, **kwargs): from certbot.crypto_util import import_csr_file return import_csr_file(*args, **kwargs) def test_der_csr(self): csrfile = test_util.vector_path('csr_512.der') data = test_util.load_vector('csr_512.der') data_pem = test_util.load_vector('csr_512.pem') self.assertEqual( (OpenSSL.crypto.FILETYPE_PEM, util.CSR(file=csrfile, data=data_pem, form="pem"), ["Example.com"],), self._call(csrfile, data)) def test_pem_csr(self): csrfile = test_util.vector_path('csr_512.pem') data = test_util.load_vector('csr_512.pem') self.assertEqual( (OpenSSL.crypto.FILETYPE_PEM, util.CSR(file=csrfile, data=data, form="pem"), ["Example.com"],), self._call(csrfile, data)) def test_bad_csr(self): self.assertRaises(errors.Error, self._call, test_util.vector_path('cert_512.pem'), test_util.load_vector('cert_512.pem')) class MakeKeyTest(unittest.TestCase): # pylint: disable=too-few-public-methods """Tests for certbot.crypto_util.make_key.""" def test_it(self): # pylint: disable=no-self-use from certbot.crypto_util import make_key # Do not test larger keys as it takes too long. OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, make_key(1024)) class VerifyCertSetup(unittest.TestCase): """Refactoring for verification tests.""" def setUp(self): super(VerifyCertSetup, self).setUp() self.renewable_cert = mock.MagicMock() self.renewable_cert.cert = SS_CERT_PATH self.renewable_cert.chain = SS_CERT_PATH self.renewable_cert.privkey = RSA2048_KEY_PATH self.renewable_cert.fullchain = test_util.vector_path('cert_fullchain_2048.pem') self.bad_renewable_cert = mock.MagicMock() self.bad_renewable_cert.chain = SS_CERT_PATH self.bad_renewable_cert.cert = SS_CERT_PATH self.bad_renewable_cert.fullchain = SS_CERT_PATH class VerifyRenewableCertTest(VerifyCertSetup): """Tests for certbot.crypto_util.verify_renewable_cert.""" def setUp(self): super(VerifyRenewableCertTest, self).setUp() def _call(self, renewable_cert): from certbot.crypto_util import verify_renewable_cert return verify_renewable_cert(renewable_cert) def test_verify_renewable_cert(self): self.assertEqual(None, self._call(self.renewable_cert)) @mock.patch('certbot.crypto_util.verify_renewable_cert_sig', side_effect=errors.Error("")) def test_verify_renewable_cert_failure(self, unused_verify_renewable_cert_sign): self.assertRaises(errors.Error, self._call, self.bad_renewable_cert) class VerifyRenewableCertSigTest(VerifyCertSetup): """Tests for certbot.crypto_util.verify_renewable_cert.""" def setUp(self): super(VerifyRenewableCertSigTest, self).setUp() def _call(self, renewable_cert): from certbot.crypto_util import verify_renewable_cert_sig return verify_renewable_cert_sig(renewable_cert) def test_cert_sig_match(self): self.assertEqual(None, self._call(self.renewable_cert)) def test_cert_sig_match_ec(self): renewable_cert = mock.MagicMock() renewable_cert.cert = P256_CERT_PATH renewable_cert.chain = P256_CERT_PATH renewable_cert.privkey = P256_KEY self.assertEqual(None, self._call(renewable_cert)) def test_cert_sig_mismatch(self): self.bad_renewable_cert.cert = test_util.vector_path('cert_512_bad.pem') self.assertRaises(errors.Error, self._call, self.bad_renewable_cert) class VerifyFullchainTest(VerifyCertSetup): """Tests for certbot.crypto_util.verify_fullchain.""" def setUp(self): super(VerifyFullchainTest, self).setUp() def _call(self, renewable_cert): from certbot.crypto_util import verify_fullchain return verify_fullchain(renewable_cert) def test_fullchain_matches(self): self.assertEqual(None, self._call(self.renewable_cert)) def test_fullchain_mismatch(self): self.assertRaises(errors.Error, self._call, self.bad_renewable_cert) def test_fullchain_ioerror(self): self.bad_renewable_cert.chain = "dog" self.assertRaises(errors.Error, self._call, self.bad_renewable_cert) class VerifyCertMatchesPrivKeyTest(VerifyCertSetup): """Tests for certbot.crypto_util.verify_cert_matches_priv_key.""" def setUp(self): super(VerifyCertMatchesPrivKeyTest, self).setUp() def _call(self, renewable_cert): from certbot.crypto_util import verify_cert_matches_priv_key return verify_cert_matches_priv_key(renewable_cert.cert, renewable_cert.privkey) def test_cert_priv_key_match(self): self.renewable_cert.cert = SS_CERT_PATH self.renewable_cert.privkey = RSA2048_KEY_PATH self.assertEqual(None, self._call(self.renewable_cert)) def test_cert_priv_key_mismatch(self): self.bad_renewable_cert.privkey = RSA256_KEY_PATH self.bad_renewable_cert.cert = SS_CERT_PATH self.assertRaises(errors.Error, self._call, self.bad_renewable_cert) class ValidPrivkeyTest(unittest.TestCase): """Tests for certbot.crypto_util.valid_privkey.""" @classmethod def _call(cls, privkey): from certbot.crypto_util import valid_privkey return valid_privkey(privkey) def test_valid_true(self): self.assertTrue(self._call(RSA512_KEY)) def test_empty_false(self): self.assertFalse(self._call('')) def test_random_false(self): self.assertFalse(self._call('foo bar')) class GetSANsFromCertTest(unittest.TestCase): """Tests for certbot.crypto_util.get_sans_from_cert.""" @classmethod def _call(cls, *args, **kwargs): from certbot.crypto_util import get_sans_from_cert return get_sans_from_cert(*args, **kwargs) def test_single(self): self.assertEqual([], self._call(test_util.load_vector('cert_512.pem'))) def test_san(self): self.assertEqual( ['example.com', 'www.example.com'], self._call(test_util.load_vector('cert-san_512.pem'))) class GetNamesFromCertTest(unittest.TestCase): """Tests for certbot.crypto_util.get_names_from_cert.""" @classmethod def _call(cls, *args, **kwargs): from certbot.crypto_util import get_names_from_cert return get_names_from_cert(*args, **kwargs) def test_single(self): self.assertEqual( ['example.com'], self._call(test_util.load_vector('cert_512.pem'))) def test_san(self): self.assertEqual( ['example.com', 'www.example.com'], self._call(test_util.load_vector('cert-san_512.pem'))) def test_common_name_sans_order(self): # Tests that the common name comes first # followed by the SANS in alphabetical order self.assertEqual( ['example.com'] + ['{0}.example.com'.format(c) for c in 'abcd'], self._call(test_util.load_vector('cert-5sans_512.pem'))) def test_parse_non_cert(self): self.assertRaises(OpenSSL.crypto.Error, self._call, "hello there") class CertLoaderTest(unittest.TestCase): """Tests for certbot.crypto_util.pyopenssl_load_certificate""" def test_load_valid_cert(self): from certbot.crypto_util import pyopenssl_load_certificate cert, file_type = pyopenssl_load_certificate(CERT) self.assertEqual(cert.digest('sha256'), OpenSSL.crypto.load_certificate(file_type, CERT).digest('sha256')) def test_load_invalid_cert(self): from certbot.crypto_util import pyopenssl_load_certificate bad_cert_data = CERT.replace(b"BEGIN CERTIFICATE", b"ASDFASDFASDF!!!") self.assertRaises( errors.Error, pyopenssl_load_certificate, bad_cert_data) class NotBeforeTest(unittest.TestCase): """Tests for certbot.crypto_util.notBefore""" def test_notBefore(self): from certbot.crypto_util import notBefore self.assertEqual(notBefore(CERT_PATH).isoformat(), '2014-12-11T22:34:45+00:00') class NotAfterTest(unittest.TestCase): """Tests for certbot.crypto_util.notAfter""" def test_notAfter(self): from certbot.crypto_util import notAfter self.assertEqual(notAfter(CERT_PATH).isoformat(), '2014-12-18T22:34:45+00:00') class Sha256sumTest(unittest.TestCase): """Tests for certbot.crypto_util.notAfter""" def test_sha256sum(self): from certbot.crypto_util import sha256sum self.assertEqual(sha256sum(CERT_PATH), '914ffed8daf9e2c99d90ac95c77d54f32cbd556672facac380f0c063498df84e') class CertAndChainFromFullchainTest(unittest.TestCase): """Tests for certbot.crypto_util.cert_and_chain_from_fullchain""" def test_cert_and_chain_from_fullchain(self): cert_pem = CERT.decode() chain_pem = cert_pem + SS_CERT.decode() fullchain_pem = cert_pem + chain_pem spacey_fullchain_pem = cert_pem + u'\n' + chain_pem from certbot.crypto_util import cert_and_chain_from_fullchain for fullchain in (fullchain_pem, spacey_fullchain_pem): cert_out, chain_out = cert_and_chain_from_fullchain(fullchain) self.assertEqual(cert_out, cert_pem) self.assertEqual(chain_out, chain_pem) if __name__ == '__main__': unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/renewal_test.py0000644000175000017500000000735413344054434021321 0ustar ericaerica00000000000000"""Tests for certbot.renewal""" import mock import unittest from acme import challenges from certbot import configuration from certbot import errors from certbot import storage import certbot.tests.util as test_util class RenewalTest(test_util.ConfigTestCase): def setUp(self): super(RenewalTest, self).setUp() @mock.patch('certbot.cli.set_by_cli') def test_ancient_webroot_renewal_conf(self, mock_set_by_cli): mock_set_by_cli.return_value = False rc_path = test_util.make_lineage( self.config.config_dir, 'sample-renewal-ancient.conf') self.config.account = None self.config.email = None self.config.webroot_path = None config = configuration.NamespaceConfig(self.config) lineage = storage.RenewableCert(rc_path, config) renewalparams = lineage.configuration['renewalparams'] # pylint: disable=protected-access from certbot import renewal renewal._restore_webroot_config(config, renewalparams) self.assertEqual(config.webroot_path, ['/var/www/']) class RestoreRequiredConfigElementsTest(test_util.ConfigTestCase): """Tests for certbot.renewal.restore_required_config_elements.""" def setUp(self): super(RestoreRequiredConfigElementsTest, self).setUp() @classmethod def _call(cls, *args, **kwargs): from certbot.renewal import restore_required_config_elements return restore_required_config_elements(*args, **kwargs) @mock.patch('certbot.renewal.cli.set_by_cli') def test_allow_subset_of_names_success(self, mock_set_by_cli): mock_set_by_cli.return_value = False self._call(self.config, {'allow_subset_of_names': 'True'}) self.assertTrue(self.config.allow_subset_of_names is True) @mock.patch('certbot.renewal.cli.set_by_cli') def test_allow_subset_of_names_failure(self, mock_set_by_cli): mock_set_by_cli.return_value = False renewalparams = {'allow_subset_of_names': 'maybe'} self.assertRaises( errors.Error, self._call, self.config, renewalparams) @mock.patch('certbot.renewal.cli.set_by_cli') def test_pref_challs_list(self, mock_set_by_cli): mock_set_by_cli.return_value = False renewalparams = {'pref_challs': 'tls-sni, http-01, dns'.split(',')} self._call(self.config, renewalparams) expected = [challenges.TLSSNI01.typ, challenges.HTTP01.typ, challenges.DNS01.typ] self.assertEqual(self.config.pref_challs, expected) @mock.patch('certbot.renewal.cli.set_by_cli') def test_pref_challs_str(self, mock_set_by_cli): mock_set_by_cli.return_value = False renewalparams = {'pref_challs': 'dns'} self._call(self.config, renewalparams) expected = [challenges.DNS01.typ] self.assertEqual(self.config.pref_challs, expected) @mock.patch('certbot.renewal.cli.set_by_cli') def test_pref_challs_failure(self, mock_set_by_cli): mock_set_by_cli.return_value = False renewalparams = {'pref_challs': 'finding-a-shrubbery'} self.assertRaises(errors.Error, self._call, self.config, renewalparams) @mock.patch('certbot.renewal.cli.set_by_cli') def test_must_staple_success(self, mock_set_by_cli): mock_set_by_cli.return_value = False self._call(self.config, {'must_staple': 'True'}) self.assertTrue(self.config.must_staple is True) @mock.patch('certbot.renewal.cli.set_by_cli') def test_must_staple_failure(self, mock_set_by_cli): mock_set_by_cli.return_value = False renewalparams = {'must_staple': 'maybe'} self.assertRaises( errors.Error, self._call, self.config, renewalparams) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/account_test.py0000644000175000017500000003405013344054434021311 0ustar ericaerica00000000000000"""Tests for certbot.account.""" import datetime import json import os import shutil import stat import unittest import josepy as jose import mock import pytz from acme import messages from certbot import errors import certbot.tests.util as test_util KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem")) class AccountTest(unittest.TestCase): """Tests for certbot.account.Account.""" def setUp(self): from certbot.account import Account self.regr = mock.MagicMock() self.meta = Account.Meta( creation_host="test.certbot.org", creation_dt=datetime.datetime( 2015, 7, 4, 14, 4, 10, tzinfo=pytz.UTC)) self.acc = Account(self.regr, KEY, self.meta) self.regr.__repr__ = mock.MagicMock(return_value="i_am_a_regr") with mock.patch("certbot.account.socket") as mock_socket: mock_socket.getfqdn.return_value = "test.certbot.org" with mock.patch("certbot.account.datetime") as mock_dt: mock_dt.datetime.now.return_value = self.meta.creation_dt self.acc_no_meta = Account(self.regr, KEY) def test_init(self): self.assertEqual(self.regr, self.acc.regr) self.assertEqual(KEY, self.acc.key) self.assertEqual(self.meta, self.acc_no_meta.meta) def test_id(self): self.assertEqual( self.acc.id, "7adac10320f585ddf118429c0c4af2cd") def test_slug(self): self.assertEqual( self.acc.slug, "test.certbot.org@2015-07-04T14:04:10Z (7ada)") def test_repr(self): self.assertTrue(repr(self.acc).startswith( "= 0.12.0. """ self._test_constant_common(tuple) def _test_constant_common(self, typ): with mock.patch("certbot.util.configargparse") as mock_configargparse: mock_configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE = typ() self._call("--old-option", 1) self._call("--old-option2", 2) self.assertEqual( len(mock_configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE), 1) class EnforceLeValidity(unittest.TestCase): """Test enforce_le_validity.""" def _call(self, domain): from certbot.util import enforce_le_validity return enforce_le_validity(domain) def test_sanity(self): self.assertRaises(errors.ConfigurationError, self._call, u"..") def test_invalid_chars(self): self.assertRaises( errors.ConfigurationError, self._call, u"hello_world.example.com") def test_leading_hyphen(self): self.assertRaises( errors.ConfigurationError, self._call, u"-a.example.com") def test_trailing_hyphen(self): self.assertRaises( errors.ConfigurationError, self._call, u"a-.example.com") def test_one_label(self): self.assertRaises(errors.ConfigurationError, self._call, u"com") def test_valid_domain(self): self.assertEqual(self._call(u"example.com"), u"example.com") def test_input_with_scheme(self): self.assertRaises(errors.ConfigurationError, self._call, u"http://example.com") self.assertRaises(errors.ConfigurationError, self._call, u"https://example.com") def test_valid_input_with_scheme_name(self): self.assertEqual(self._call(u"http.example.com"), u"http.example.com") class EnforceDomainSanityTest(unittest.TestCase): """Test enforce_domain_sanity.""" def _call(self, domain): from certbot.util import enforce_domain_sanity return enforce_domain_sanity(domain) def test_nonascii_str(self): self.assertRaises(errors.ConfigurationError, self._call, u"eichh\u00f6rnchen.example.com".encode("utf-8")) def test_nonascii_unicode(self): self.assertRaises(errors.ConfigurationError, self._call, u"eichh\u00f6rnchen.example.com") def test_too_long(self): long_domain = u"a"*256 self.assertRaises(errors.ConfigurationError, self._call, long_domain) def test_not_too_long(self): not_too_long_domain = u"{0}.{1}.{2}.{3}".format("a"*63, "b"*63, "c"*63, "d"*63) self._call(not_too_long_domain) def test_empty_label(self): empty_label_domain = u"fizz..example.com" self.assertRaises(errors.ConfigurationError, self._call, empty_label_domain) def test_empty_trailing_label(self): empty_trailing_label_domain = u"example.com.." self.assertRaises(errors.ConfigurationError, self._call, empty_trailing_label_domain) def test_long_label_1(self): long_label_domain = u"a"*64 self.assertRaises(errors.ConfigurationError, self._call, long_label_domain) def test_long_label_2(self): long_label_domain = u"{0}.{1}.com".format(u"a"*64, u"b"*63) self.assertRaises(errors.ConfigurationError, self._call, long_label_domain) def test_not_long_label(self): not_too_long_label_domain = u"{0}.{1}.com".format(u"a"*63, u"b"*63) self._call(not_too_long_label_domain) def test_empty_domain(self): empty_domain = u"" self.assertRaises(errors.ConfigurationError, self._call, empty_domain) def test_punycode_ok(self): # Punycode is now legal, so no longer an error; instead check # that it's _not_ an error (at the initial sanity check stage) self._call('this.is.xn--ls8h.tld') class IsWildcardDomainTest(unittest.TestCase): """Tests for is_wildcard_domain.""" def setUp(self): self.wildcard = u"*.example.org" self.no_wildcard = u"example.org" def _call(self, domain): from certbot.util import is_wildcard_domain return is_wildcard_domain(domain) def test_no_wildcard(self): self.assertFalse(self._call(self.no_wildcard)) self.assertFalse(self._call(self.no_wildcard.encode())) def test_wildcard(self): self.assertTrue(self._call(self.wildcard)) self.assertTrue(self._call(self.wildcard.encode())) class OsInfoTest(unittest.TestCase): """Test OS / distribution detection""" def test_systemd_os_release(self): from certbot.util import (get_os_info, get_systemd_os_info, get_os_info_ua) with mock.patch('os.path.isfile', return_value=True): self.assertEqual(get_os_info( test_util.vector_path("os-release"))[0], 'systemdos') self.assertEqual(get_os_info( test_util.vector_path("os-release"))[1], '42') self.assertEqual(get_systemd_os_info("/dev/null"), ("", "")) self.assertEqual(get_os_info_ua( test_util.vector_path("os-release")), "SystemdOS") with mock.patch('os.path.isfile', return_value=False): self.assertEqual(get_systemd_os_info(), ("", "")) def test_systemd_os_release_like(self): from certbot.util import get_systemd_os_like with mock.patch('os.path.isfile', return_value=True): id_likes = get_systemd_os_like(test_util.vector_path( "os-release")) self.assertEqual(len(id_likes), 3) self.assertTrue("debian" in id_likes) @mock.patch("certbot.util.subprocess.Popen") def test_non_systemd_os_info(self, popen_mock): from certbot.util import (get_os_info, get_python_os_info, get_os_info_ua) with mock.patch('os.path.isfile', return_value=False): with mock.patch('platform.system_alias', return_value=('NonSystemD', '42', '42')): self.assertEqual(get_os_info()[0], 'nonsystemd') self.assertEqual(get_os_info_ua(), " ".join(get_python_os_info())) with mock.patch('platform.system_alias', return_value=('darwin', '', '')): comm_mock = mock.Mock() comm_attrs = {'communicate.return_value': ('42.42.42', 'error')} comm_mock.configure_mock(**comm_attrs) # pylint: disable=star-args popen_mock.return_value = comm_mock self.assertEqual(get_os_info()[0], 'darwin') self.assertEqual(get_os_info()[1], '42.42.42') with mock.patch('platform.system_alias', return_value=('linux', '', '')): with mock.patch('platform.linux_distribution', return_value=('', '', '')): self.assertEqual(get_python_os_info(), ("linux", "")) with mock.patch('platform.linux_distribution', return_value=('testdist', '42', '')): self.assertEqual(get_python_os_info(), ("testdist", "42")) with mock.patch('platform.system_alias', return_value=('freebsd', '9.3-RC3-p1', '')): self.assertEqual(get_python_os_info(), ("freebsd", "9")) with mock.patch('platform.system_alias', return_value=('windows', '', '')): with mock.patch('platform.win32_ver', return_value=('4242', '95', '2', '')): self.assertEqual(get_python_os_info(), ("windows", "95")) class AtexitRegisterTest(unittest.TestCase): """Tests for certbot.util.atexit_register.""" def setUp(self): self.func = mock.MagicMock() self.args = ('hi',) self.kwargs = {'answer': 42} @classmethod def _call(cls, *args, **kwargs): from certbot.util import atexit_register return atexit_register(*args, **kwargs) def test_called(self): self._test_common(os.getpid()) self.func.assert_called_with(*self.args, **self.kwargs) def test_not_called(self): self._test_common(initial_pid=-1) self.assertFalse(self.func.called) def _test_common(self, initial_pid): with mock.patch('certbot.util._INITIAL_PID', initial_pid): with mock.patch('certbot.util.atexit') as mock_atexit: self._call(self.func, *self.args, **self.kwargs) # _INITAL_PID must be mocked when calling atexit_func self.assertTrue(mock_atexit.register.called) args, kwargs = mock_atexit.register.call_args atexit_func = args[0] atexit_func(*args[1:], **kwargs) # pylint: disable=star-args if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/auth_handler_test.py0000644000175000017500000005564213344054434022325 0ustar ericaerica00000000000000"""Tests for certbot.auth_handler.""" import functools import logging import unittest import mock import six import zope.component from acme import challenges from acme import client as acme_client from acme import messages from acme.magic_typing import Dict # pylint: disable=unused-import, no-name-in-module from certbot import achallenges from certbot import errors from certbot import interfaces from certbot import util from certbot.tests import acme_util from certbot.tests import util as test_util class ChallengeFactoryTest(unittest.TestCase): # pylint: disable=protected-access def setUp(self): from certbot.auth_handler import AuthHandler # Account is mocked... self.handler = AuthHandler(None, None, mock.Mock(key="mock_key"), []) self.authzr = acme_util.gen_authzr( messages.STATUS_PENDING, "test", acme_util.CHALLENGES, [messages.STATUS_PENDING] * 6, False) def test_all(self): achalls = self.handler._challenge_factory( self.authzr, range(0, len(acme_util.CHALLENGES))) self.assertEqual( [achall.chall for achall in achalls], acme_util.CHALLENGES) def test_one_tls_sni(self): achalls = self.handler._challenge_factory(self.authzr, [1]) self.assertEqual( [achall.chall for achall in achalls], [acme_util.TLSSNI01]) def test_unrecognized(self): authzr = acme_util.gen_authzr( messages.STATUS_PENDING, "test", [mock.Mock(chall="chall", typ="unrecognized")], [messages.STATUS_PENDING]) self.assertRaises( errors.Error, self.handler._challenge_factory, authzr, [0]) class HandleAuthorizationsTest(unittest.TestCase): """handle_authorizations test. This tests everything except for all functions under _poll_challenges. """ def setUp(self): from certbot.auth_handler import AuthHandler self.mock_display = mock.Mock() zope.component.provideUtility( self.mock_display, interfaces.IDisplay) zope.component.provideUtility( mock.Mock(debug_challenges=False), interfaces.IConfig) self.mock_auth = mock.MagicMock(name="ApacheConfigurator") self.mock_auth.get_chall_pref.return_value = [challenges.TLSSNI01] self.mock_auth.perform.side_effect = gen_auth_resp self.mock_account = mock.Mock(key=util.Key("file_path", "PEM")) self.mock_net = mock.MagicMock(spec=acme_client.Client) self.mock_net.acme_version = 1 self.handler = AuthHandler( self.mock_auth, self.mock_net, self.mock_account, []) logging.disable(logging.CRITICAL) def tearDown(self): logging.disable(logging.NOTSET) def _test_name1_tls_sni_01_1_common(self, combos): authzr = gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES, combos=combos) mock_order = mock.MagicMock(authorizations=[authzr]) with mock.patch("certbot.auth_handler.AuthHandler._poll_challenges") as mock_poll: mock_poll.side_effect = self._validate_all authzr = self.handler.handle_authorizations(mock_order) self.assertEqual(self.mock_net.answer_challenge.call_count, 1) self.assertEqual(mock_poll.call_count, 1) chall_update = mock_poll.call_args[0][1] self.assertEqual(list(six.iterkeys(chall_update)), [0]) self.assertEqual(len(chall_update.values()), 1) self.assertEqual(self.mock_auth.cleanup.call_count, 1) # Test if list first element is TLSSNI01, use typ because it is an achall self.assertEqual( self.mock_auth.cleanup.call_args[0][0][0].typ, "tls-sni-01") self.assertEqual(len(authzr), 1) def test_name1_tls_sni_01_1_acme_1(self): self._test_name1_tls_sni_01_1_common(combos=True) def test_name1_tls_sni_01_1_acme_2(self): self.mock_net.acme_version = 2 self._test_name1_tls_sni_01_1_common(combos=False) @mock.patch("certbot.auth_handler.AuthHandler._poll_challenges") def test_name1_tls_sni_01_1_http_01_1_dns_1_acme_1(self, mock_poll): mock_poll.side_effect = self._validate_all self.mock_auth.get_chall_pref.return_value.append(challenges.HTTP01) self.mock_auth.get_chall_pref.return_value.append(challenges.DNS01) authzr = gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES, combos=False) mock_order = mock.MagicMock(authorizations=[authzr]) authzr = self.handler.handle_authorizations(mock_order) self.assertEqual(self.mock_net.answer_challenge.call_count, 3) self.assertEqual(mock_poll.call_count, 1) chall_update = mock_poll.call_args[0][1] self.assertEqual(list(six.iterkeys(chall_update)), [0]) self.assertEqual(len(chall_update.values()), 1) self.assertEqual(self.mock_auth.cleanup.call_count, 1) # Test if list first element is TLSSNI01, use typ because it is an achall for achall in self.mock_auth.cleanup.call_args[0][0]: self.assertTrue(achall.typ in ["tls-sni-01", "http-01", "dns-01"]) # Length of authorizations list self.assertEqual(len(authzr), 1) @mock.patch("certbot.auth_handler.AuthHandler._poll_challenges") def test_name1_tls_sni_01_1_http_01_1_dns_1_acme_2(self, mock_poll): self.mock_net.acme_version = 2 mock_poll.side_effect = self._validate_all self.mock_auth.get_chall_pref.return_value.append(challenges.HTTP01) self.mock_auth.get_chall_pref.return_value.append(challenges.DNS01) authzr = gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES, combos=False) mock_order = mock.MagicMock(authorizations=[authzr]) authzr = self.handler.handle_authorizations(mock_order) self.assertEqual(self.mock_net.answer_challenge.call_count, 1) self.assertEqual(mock_poll.call_count, 1) chall_update = mock_poll.call_args[0][1] self.assertEqual(list(six.iterkeys(chall_update)), [0]) self.assertEqual(len(chall_update.values()), 1) self.assertEqual(self.mock_auth.cleanup.call_count, 1) cleaned_up_achalls = self.mock_auth.cleanup.call_args[0][0] self.assertEqual(len(cleaned_up_achalls), 1) self.assertEqual(cleaned_up_achalls[0].typ, "tls-sni-01") # Length of authorizations list self.assertEqual(len(authzr), 1) def _test_name3_tls_sni_01_3_common(self, combos): self.mock_net.request_domain_challenges.side_effect = functools.partial( gen_dom_authzr, challs=acme_util.CHALLENGES, combos=combos) authzrs = [gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES), gen_dom_authzr(domain="1", challs=acme_util.CHALLENGES), gen_dom_authzr(domain="2", challs=acme_util.CHALLENGES)] mock_order = mock.MagicMock(authorizations=authzrs) with mock.patch("certbot.auth_handler.AuthHandler._poll_challenges") as mock_poll: mock_poll.side_effect = self._validate_all authzr = self.handler.handle_authorizations(mock_order) self.assertEqual(self.mock_net.answer_challenge.call_count, 3) # Check poll call self.assertEqual(mock_poll.call_count, 1) chall_update = mock_poll.call_args[0][1] self.assertEqual(len(list(six.iterkeys(chall_update))), 3) self.assertTrue(0 in list(six.iterkeys(chall_update))) self.assertEqual(len(chall_update[0]), 1) self.assertTrue(1 in list(six.iterkeys(chall_update))) self.assertEqual(len(chall_update[1]), 1) self.assertTrue(2 in list(six.iterkeys(chall_update))) self.assertEqual(len(chall_update[2]), 1) self.assertEqual(self.mock_auth.cleanup.call_count, 1) self.assertEqual(len(authzr), 3) def test_name3_tls_sni_01_3_common_acme_1(self): self._test_name3_tls_sni_01_3_common(combos=True) def test_name3_tls_sni_01_3_common_acme_2(self): self.mock_net.acme_version = 2 self._test_name3_tls_sni_01_3_common(combos=False) @mock.patch("certbot.auth_handler.AuthHandler._poll_challenges") def test_debug_challenges(self, mock_poll): zope.component.provideUtility( mock.Mock(debug_challenges=True), interfaces.IConfig) authzrs = [gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES)] mock_order = mock.MagicMock(authorizations=authzrs) mock_poll.side_effect = self._validate_all self.handler.handle_authorizations(mock_order) self.assertEqual(self.mock_net.answer_challenge.call_count, 1) self.assertEqual(self.mock_display.notification.call_count, 1) def test_perform_failure(self): authzrs = [gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES)] mock_order = mock.MagicMock(authorizations=authzrs) self.mock_auth.perform.side_effect = errors.AuthorizationError self.assertRaises( errors.AuthorizationError, self.handler.handle_authorizations, mock_order) def test_no_domains(self): mock_order = mock.MagicMock(authorizations=[]) self.assertRaises(errors.AuthorizationError, self.handler.handle_authorizations, mock_order) def _test_preferred_challenge_choice_common(self, combos): authzrs = [gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES, combos=combos)] mock_order = mock.MagicMock(authorizations=authzrs) self.mock_auth.get_chall_pref.return_value.append(challenges.HTTP01) self.handler.pref_challs.extend((challenges.HTTP01.typ, challenges.DNS01.typ,)) with mock.patch("certbot.auth_handler.AuthHandler._poll_challenges") as mock_poll: mock_poll.side_effect = self._validate_all self.handler.handle_authorizations(mock_order) self.assertEqual(self.mock_auth.cleanup.call_count, 1) self.assertEqual( self.mock_auth.cleanup.call_args[0][0][0].typ, "http-01") def test_preferred_challenge_choice_common_acme_1(self): self._test_preferred_challenge_choice_common(combos=True) def test_preferred_challenge_choice_common_acme_2(self): self.mock_net.acme_version = 2 self._test_preferred_challenge_choice_common(combos=False) def _test_preferred_challenges_not_supported_common(self, combos): authzrs = [gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES, combos=combos)] mock_order = mock.MagicMock(authorizations=authzrs) self.handler.pref_challs.append(challenges.HTTP01.typ) self.assertRaises( errors.AuthorizationError, self.handler.handle_authorizations, mock_order) def test_preferred_challenges_not_supported_acme_1(self): self._test_preferred_challenges_not_supported_common(combos=True) def test_preferred_challenges_not_supported_acme_2(self): self.mock_net.acme_version = 2 self._test_preferred_challenges_not_supported_common(combos=False) def test_dns_only_challenge_not_supported(self): authzrs = [gen_dom_authzr(domain="0", challs=[acme_util.DNS01])] mock_order = mock.MagicMock(authorizations=authzrs) self.assertRaises( errors.AuthorizationError, self.handler.handle_authorizations, mock_order) def test_perform_error(self): self.mock_auth.perform.side_effect = errors.AuthorizationError authzr = gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES, combos=True) mock_order = mock.MagicMock(authorizations=[authzr]) self.assertRaises(errors.AuthorizationError, self.handler.handle_authorizations, mock_order) self.assertEqual(self.mock_auth.cleanup.call_count, 1) self.assertEqual( self.mock_auth.cleanup.call_args[0][0][0].typ, "tls-sni-01") @mock.patch("certbot.auth_handler.AuthHandler._respond") def test_respond_error(self, mock_respond): authzrs = [gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES)] mock_order = mock.MagicMock(authorizations=authzrs) mock_respond.side_effect = errors.AuthorizationError self.assertRaises( errors.AuthorizationError, self.handler.handle_authorizations, mock_order) self.assertEqual(self.mock_auth.cleanup.call_count, 1) self.assertEqual( self.mock_auth.cleanup.call_args[0][0][0].typ, "tls-sni-01") @mock.patch("certbot.auth_handler.AuthHandler._poll_challenges") @mock.patch("certbot.auth_handler.AuthHandler.verify_authzr_complete") def test_incomplete_authzr_error(self, mock_verify, mock_poll): authzrs = [gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES)] mock_order = mock.MagicMock(authorizations=authzrs) mock_verify.side_effect = errors.AuthorizationError mock_poll.side_effect = self._validate_all self.assertRaises( errors.AuthorizationError, self.handler.handle_authorizations, mock_order) self.assertEqual(self.mock_auth.cleanup.call_count, 1) self.assertEqual( self.mock_auth.cleanup.call_args[0][0][0].typ, "tls-sni-01") def _validate_all(self, aauthzrs, unused_1, unused_2): for i, aauthzr in enumerate(aauthzrs): azr = aauthzr.authzr updated_azr = acme_util.gen_authzr( messages.STATUS_VALID, azr.body.identifier.value, [challb.chall for challb in azr.body.challenges], [messages.STATUS_VALID] * len(azr.body.challenges), azr.body.combinations) aauthzrs[i] = type(aauthzr)(updated_azr, aauthzr.achalls) class PollChallengesTest(unittest.TestCase): # pylint: disable=protected-access """Test poll challenges.""" def setUp(self): from certbot.auth_handler import challb_to_achall from certbot.auth_handler import AuthHandler, AnnotatedAuthzr # Account and network are mocked... self.mock_net = mock.MagicMock() self.handler = AuthHandler( None, self.mock_net, mock.Mock(key="mock_key"), []) self.doms = ["0", "1", "2"] self.aauthzrs = [ AnnotatedAuthzr(acme_util.gen_authzr( messages.STATUS_PENDING, self.doms[0], [acme_util.HTTP01, acme_util.TLSSNI01], [messages.STATUS_PENDING] * 2, False), []), AnnotatedAuthzr(acme_util.gen_authzr( messages.STATUS_PENDING, self.doms[1], acme_util.CHALLENGES, [messages.STATUS_PENDING] * 3, False), []), AnnotatedAuthzr(acme_util.gen_authzr( messages.STATUS_PENDING, self.doms[2], acme_util.CHALLENGES, [messages.STATUS_PENDING] * 3, False), []) ] self.chall_update = {} # type: Dict[int, achallenges.KeyAuthorizationAnnotatedChallenge] for i, aauthzr in enumerate(self.aauthzrs): self.chall_update[i] = [ challb_to_achall(challb, mock.Mock(key="dummy_key"), self.doms[i]) for challb in aauthzr.authzr.body.challenges] @mock.patch("certbot.auth_handler.time") def test_poll_challenges(self, unused_mock_time): self.mock_net.poll.side_effect = self._mock_poll_solve_one_valid self.handler._poll_challenges(self.aauthzrs, self.chall_update, False) for aauthzr in self.aauthzrs: self.assertEqual(aauthzr.authzr.body.status, messages.STATUS_VALID) @mock.patch("certbot.auth_handler.time") def test_poll_challenges_failure_best_effort(self, unused_mock_time): self.mock_net.poll.side_effect = self._mock_poll_solve_one_invalid self.handler._poll_challenges(self.aauthzrs, self.chall_update, True) for aauthzr in self.aauthzrs: self.assertEqual(aauthzr.authzr.body.status, messages.STATUS_PENDING) @mock.patch("certbot.auth_handler.time") @test_util.patch_get_utility() def test_poll_challenges_failure(self, unused_mock_time, unused_mock_zope): self.mock_net.poll.side_effect = self._mock_poll_solve_one_invalid self.assertRaises( errors.AuthorizationError, self.handler._poll_challenges, self.aauthzrs, self.chall_update, False) @mock.patch("certbot.auth_handler.time") def test_unable_to_find_challenge_status(self, unused_mock_time): from certbot.auth_handler import challb_to_achall self.mock_net.poll.side_effect = self._mock_poll_solve_one_valid self.chall_update[0].append( challb_to_achall(acme_util.DNS01_P, "key", self.doms[0])) self.assertRaises( errors.AuthorizationError, self.handler._poll_challenges, self.aauthzrs, self.chall_update, False) def test_verify_authzr_failure(self): self.assertRaises(errors.AuthorizationError, self.handler.verify_authzr_complete, self.aauthzrs) def _mock_poll_solve_one_valid(self, authzr): # Pending here because my dummy script won't change the full status. # Basically it didn't raise an error and it stopped earlier than # Making all challenges invalid which would make mock_poll_solve_one # change authzr to invalid return self._mock_poll_solve_one_chall(authzr, messages.STATUS_VALID) def _mock_poll_solve_one_invalid(self, authzr): return self._mock_poll_solve_one_chall(authzr, messages.STATUS_INVALID) def _mock_poll_solve_one_chall(self, authzr, desired_status): # pylint: disable=no-self-use """Dummy method that solves one chall at a time to desired_status. When all are solved.. it changes authzr.status to desired_status """ new_challbs = authzr.body.challenges for challb in authzr.body.challenges: if challb.status != desired_status: new_challbs = tuple( challb_temp if challb_temp != challb else acme_util.chall_to_challb(challb.chall, desired_status) for challb_temp in authzr.body.challenges ) break if all(test_challb.status == desired_status for test_challb in new_challbs): status_ = desired_status else: status_ = authzr.body.status new_authzr = messages.AuthorizationResource( uri=authzr.uri, body=messages.Authorization( identifier=authzr.body.identifier, challenges=new_challbs, combinations=authzr.body.combinations, status=status_, ), ) return (new_authzr, "response") class ChallbToAchallTest(unittest.TestCase): """Tests for certbot.auth_handler.challb_to_achall.""" def _call(self, challb): from certbot.auth_handler import challb_to_achall return challb_to_achall(challb, "account_key", "domain") def test_it(self): self.assertEqual( self._call(acme_util.HTTP01_P), achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.HTTP01_P, account_key="account_key", domain="domain"), ) class GenChallengePathTest(unittest.TestCase): """Tests for certbot.auth_handler.gen_challenge_path. .. todo:: Add more tests for dumb_path... depending on what we want to do. """ def setUp(self): logging.disable(logging.FATAL) def tearDown(self): logging.disable(logging.NOTSET) @classmethod def _call(cls, challbs, preferences, combinations): from certbot.auth_handler import gen_challenge_path return gen_challenge_path(challbs, preferences, combinations) def test_common_case(self): """Given TLSSNI01 and HTTP01 with appropriate combos.""" challbs = (acme_util.TLSSNI01_P, acme_util.HTTP01_P) prefs = [challenges.TLSSNI01, challenges.HTTP01] combos = ((0,), (1,)) # Smart then trivial dumb path test self.assertEqual(self._call(challbs, prefs, combos), (0,)) self.assertTrue(self._call(challbs, prefs, None)) # Rearrange order... self.assertEqual(self._call(challbs[::-1], prefs, combos), (1,)) self.assertTrue(self._call(challbs[::-1], prefs, None)) def test_not_supported(self): challbs = (acme_util.DNS01_P, acme_util.TLSSNI01_P) prefs = [challenges.TLSSNI01] combos = ((0, 1),) # smart path fails because no challs in perfs satisfies combos self.assertRaises( errors.AuthorizationError, self._call, challbs, prefs, combos) # dumb path fails because all challbs are not supported self.assertRaises( errors.AuthorizationError, self._call, challbs, prefs, None) class ReportFailedChallsTest(unittest.TestCase): """Tests for certbot.auth_handler._report_failed_challs.""" # pylint: disable=protected-access def setUp(self): kwargs = { "chall": acme_util.HTTP01, "uri": "uri", "status": messages.STATUS_INVALID, "error": messages.Error.with_code("tls", detail="detail"), } # Prevent future regressions if the error type changes self.assertTrue(kwargs["error"].description is not None) self.http01 = achallenges.KeyAuthorizationAnnotatedChallenge( # pylint: disable=star-args challb=messages.ChallengeBody(**kwargs), domain="example.com", account_key="key") kwargs["chall"] = acme_util.TLSSNI01 self.tls_sni_same = achallenges.KeyAuthorizationAnnotatedChallenge( # pylint: disable=star-args challb=messages.ChallengeBody(**kwargs), domain="example.com", account_key="key") kwargs["error"] = messages.Error(typ="dnssec", detail="detail") self.tls_sni_diff = achallenges.KeyAuthorizationAnnotatedChallenge( # pylint: disable=star-args challb=messages.ChallengeBody(**kwargs), domain="foo.bar", account_key="key") @test_util.patch_get_utility() def test_same_error_and_domain(self, mock_zope): from certbot import auth_handler auth_handler._report_failed_challs([self.http01, self.tls_sni_same]) call_list = mock_zope().add_message.call_args_list self.assertTrue(len(call_list) == 1) self.assertTrue("Domain: example.com\nType: tls\nDetail: detail" in call_list[0][0][0]) @test_util.patch_get_utility() def test_different_errors_and_domains(self, mock_zope): from certbot import auth_handler auth_handler._report_failed_challs([self.http01, self.tls_sni_diff]) self.assertTrue(mock_zope().add_message.call_count == 2) def gen_auth_resp(chall_list): """Generate a dummy authorization response.""" return ["%s%s" % (chall.__class__.__name__, chall.domain) for chall in chall_list] def gen_dom_authzr(domain, challs, combos=True): """Generates new authzr for domains.""" return acme_util.gen_authzr( messages.STATUS_PENDING, domain, challs, [messages.STATUS_PENDING] * len(challs), combos) if __name__ == "__main__": unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/configuration_test.py0000644000175000017500000001472113344054434022527 0ustar ericaerica00000000000000"""Tests for certbot.configuration.""" import os import unittest import mock from certbot import constants from certbot import errors from certbot.tests import util as test_util class NamespaceConfigTest(test_util.ConfigTestCase): """Tests for certbot.configuration.NamespaceConfig.""" def setUp(self): super(NamespaceConfigTest, self).setUp() self.config.foo = 'bar' self.config.server = 'https://acme-server.org:443/new' self.config.tls_sni_01_port = 1234 self.config.http01_port = 4321 def test_init_same_ports(self): self.config.namespace.tls_sni_01_port = 4321 from certbot.configuration import NamespaceConfig self.assertRaises(errors.Error, NamespaceConfig, self.config.namespace) def test_proxy_getattr(self): self.assertEqual(self.config.foo, 'bar') self.assertEqual(self.config.work_dir, os.path.join(self.tempdir, 'work')) def test_server_path(self): self.assertEqual(['acme-server.org:443', 'new'], self.config.server_path.split(os.path.sep)) self.config.namespace.server = ('http://user:pass@acme.server:443' '/p/a/t/h;parameters?query#fragment') self.assertEqual(['user:pass@acme.server:443', 'p', 'a', 't', 'h'], self.config.server_path.split(os.path.sep)) @mock.patch('certbot.configuration.constants') def test_dynamic_dirs(self, mock_constants): mock_constants.ACCOUNTS_DIR = 'acc' mock_constants.BACKUP_DIR = 'backups' mock_constants.CSR_DIR = 'csr' mock_constants.IN_PROGRESS_DIR = '../p' mock_constants.KEY_DIR = 'keys' mock_constants.TEMP_CHECKPOINT_DIR = 't' self.assertEqual( self.config.accounts_dir, os.path.join( self.config.config_dir, 'acc/acme-server.org:443/new')) self.assertEqual( self.config.backup_dir, os.path.join(self.config.work_dir, 'backups')) self.assertEqual( self.config.csr_dir, os.path.join(self.config.config_dir, 'csr')) self.assertEqual( self.config.in_progress_dir, os.path.join(self.config.work_dir, '../p')) self.assertEqual( self.config.key_dir, os.path.join(self.config.config_dir, 'keys')) self.assertEqual( self.config.temp_checkpoint_dir, os.path.join(self.config.work_dir, 't')) def test_absolute_paths(self): from certbot.configuration import NamespaceConfig config_base = "foo" work_base = "bar" logs_base = "baz" server = "mock.server" mock_namespace = mock.MagicMock(spec=['config_dir', 'work_dir', 'logs_dir', 'http01_port', 'tls_sni_01_port', 'domains', 'server']) mock_namespace.config_dir = config_base mock_namespace.work_dir = work_base mock_namespace.logs_dir = logs_base mock_namespace.server = server config = NamespaceConfig(mock_namespace) self.assertTrue(os.path.isabs(config.config_dir)) self.assertEqual(config.config_dir, os.path.join(os.getcwd(), config_base)) self.assertTrue(os.path.isabs(config.work_dir)) self.assertEqual(config.work_dir, os.path.join(os.getcwd(), work_base)) self.assertTrue(os.path.isabs(config.logs_dir)) self.assertEqual(config.logs_dir, os.path.join(os.getcwd(), logs_base)) self.assertTrue(os.path.isabs(config.accounts_dir)) self.assertTrue(os.path.isabs(config.backup_dir)) self.assertTrue(os.path.isabs(config.csr_dir)) self.assertTrue(os.path.isabs(config.in_progress_dir)) self.assertTrue(os.path.isabs(config.key_dir)) self.assertTrue(os.path.isabs(config.temp_checkpoint_dir)) @mock.patch('certbot.configuration.constants') def test_renewal_dynamic_dirs(self, mock_constants): mock_constants.ARCHIVE_DIR = 'a' mock_constants.LIVE_DIR = 'l' mock_constants.RENEWAL_CONFIGS_DIR = 'renewal_configs' self.assertEqual( self.config.default_archive_dir, os.path.join(self.config.config_dir, 'a')) self.assertEqual( self.config.live_dir, os.path.join(self.config.config_dir, 'l')) self.assertEqual( self.config.renewal_configs_dir, os.path.join( self.config.config_dir, 'renewal_configs')) def test_renewal_absolute_paths(self): from certbot.configuration import NamespaceConfig config_base = "foo" work_base = "bar" logs_base = "baz" mock_namespace = mock.MagicMock(spec=['config_dir', 'work_dir', 'logs_dir', 'http01_port', 'tls_sni_01_port', 'domains', 'server']) mock_namespace.config_dir = config_base mock_namespace.work_dir = work_base mock_namespace.logs_dir = logs_base config = NamespaceConfig(mock_namespace) self.assertTrue(os.path.isabs(config.default_archive_dir)) self.assertTrue(os.path.isabs(config.live_dir)) self.assertTrue(os.path.isabs(config.renewal_configs_dir)) def test_get_and_set_attr(self): self.config.foo = 42 self.assertEqual(self.config.namespace.foo, 42) self.config.namespace.bar = 1337 self.assertEqual(self.config.bar, 1337) def test_hook_directories(self): self.assertEqual(self.config.renewal_hooks_dir, os.path.join(self.config.config_dir, constants.RENEWAL_HOOKS_DIR)) self.assertEqual(self.config.renewal_pre_hooks_dir, os.path.join(self.config.renewal_hooks_dir, constants.RENEWAL_PRE_HOOKS_DIR)) self.assertEqual(self.config.renewal_deploy_hooks_dir, os.path.join(self.config.renewal_hooks_dir, constants.RENEWAL_DEPLOY_HOOKS_DIR)) self.assertEqual(self.config.renewal_post_hooks_dir, os.path.join(self.config.renewal_hooks_dir, constants.RENEWAL_POST_HOOKS_DIR)) if __name__ == '__main__': unittest.main() # pragma: no cover certbot-0.27.0/certbot/tests/renewupdater_test.py0000644000175000017500000001251513344054434022364 0ustar ericaerica00000000000000"""Tests for renewal updater interfaces""" import unittest import mock from certbot import interfaces from certbot import main from certbot import updater from certbot.plugins import enhancements import certbot.tests.util as test_util class RenewUpdaterTest(test_util.ConfigTestCase): """Tests for interfaces.RenewDeployer and interfaces.GenericUpdater""" def setUp(self): super(RenewUpdaterTest, self).setUp() self.generic_updater = mock.MagicMock(spec=interfaces.GenericUpdater) self.generic_updater.restart = mock.MagicMock() self.renew_deployer = mock.MagicMock(spec=interfaces.RenewDeployer) self.mockinstaller = mock.MagicMock(spec=enhancements.AutoHSTSEnhancement) @mock.patch('certbot.main._get_and_save_cert') @mock.patch('certbot.plugins.selection.choose_configurator_plugins') @mock.patch('certbot.plugins.selection.get_unprepared_installer') @test_util.patch_get_utility() def test_server_updates(self, _, mock_geti, mock_select, mock_getsave): mock_getsave.return_value = mock.MagicMock() mock_generic_updater = self.generic_updater # Generic Updater mock_select.return_value = (mock_generic_updater, None) mock_geti.return_value = mock_generic_updater with mock.patch('certbot.main._init_le_client'): main.renew_cert(self.config, None, mock.MagicMock()) self.assertTrue(mock_generic_updater.restart.called) mock_generic_updater.restart.reset_mock() mock_generic_updater.generic_updates.reset_mock() updater.run_generic_updaters(self.config, mock.MagicMock(), None) self.assertEqual(mock_generic_updater.generic_updates.call_count, 1) self.assertFalse(mock_generic_updater.restart.called) def test_renew_deployer(self): lineage = mock.MagicMock() mock_deployer = self.renew_deployer updater.run_renewal_deployer(self.config, lineage, mock_deployer) self.assertTrue(mock_deployer.renew_deploy.called_with(lineage)) @mock.patch("certbot.updater.logger.debug") def test_updater_skip_dry_run(self, mock_log): self.config.dry_run = True updater.run_generic_updaters(self.config, None, None) self.assertTrue(mock_log.called) self.assertEquals(mock_log.call_args[0][0], "Skipping updaters in dry-run mode.") @mock.patch("certbot.updater.logger.debug") def test_deployer_skip_dry_run(self, mock_log): self.config.dry_run = True updater.run_renewal_deployer(self.config, None, None) self.assertTrue(mock_log.called) self.assertEquals(mock_log.call_args[0][0], "Skipping renewal deployer in dry-run mode.") @mock.patch('certbot.plugins.selection.get_unprepared_installer') def test_enhancement_updates(self, mock_geti): mock_geti.return_value = self.mockinstaller updater.run_generic_updaters(self.config, mock.MagicMock(), None) self.assertTrue(self.mockinstaller.update_autohsts.called) self.assertEqual(self.mockinstaller.update_autohsts.call_count, 1) def test_enhancement_deployer(self): updater.run_renewal_deployer(self.config, mock.MagicMock(), self.mockinstaller) self.assertTrue(self.mockinstaller.deploy_autohsts.called) @mock.patch('certbot.plugins.selection.get_unprepared_installer') def test_enhancement_updates_not_called(self, mock_geti): self.config.disable_renew_updates = True mock_geti.return_value = self.mockinstaller updater.run_generic_updaters(self.config, mock.MagicMock(), None) self.assertFalse(self.mockinstaller.update_autohsts.called) def test_enhancement_deployer_not_called(self): self.config.disable_renew_updates = True updater.run_renewal_deployer(self.config, mock.MagicMock(), self.mockinstaller) self.assertFalse(self.mockinstaller.deploy_autohsts.called) @mock.patch('certbot.plugins.selection.get_unprepared_installer') def test_enhancement_no_updater(self, mock_geti): FAKEINDEX = [ { "name": "Test", "class": enhancements.AutoHSTSEnhancement, "updater_function": None, "deployer_function": "deploy_autohsts", "enable_function": "enable_autohsts" } ] mock_geti.return_value = self.mockinstaller with mock.patch("certbot.plugins.enhancements._INDEX", FAKEINDEX): updater.run_generic_updaters(self.config, mock.MagicMock(), None) self.assertFalse(self.mockinstaller.update_autohsts.called) def test_enhancement_no_deployer(self): FAKEINDEX = [ { "name": "Test", "class": enhancements.AutoHSTSEnhancement, "updater_function": "deploy_autohsts", "deployer_function": None, "enable_function": "enable_autohsts" } ] with mock.patch("certbot.plugins.enhancements._INDEX", FAKEINDEX): updater.run_renewal_deployer(self.config, mock.MagicMock(), self.mockinstaller) self.assertFalse(self.mockinstaller.deploy_autohsts.called) if __name__ == '__main__': unittest.main() # pragma: no cover certbot-0.27.0/certbot/configuration.py0000644000175000017500000001305713344054434020327 0ustar ericaerica00000000000000"""Certbot user-supplied configuration.""" import copy import os from six.moves.urllib import parse # pylint: disable=import-error import zope.interface from certbot import constants from certbot import errors from certbot import interfaces from certbot import util @zope.interface.implementer(interfaces.IConfig) class NamespaceConfig(object): """Configuration wrapper around :class:`argparse.Namespace`. For more documentation, including available attributes, please see :class:`certbot.interfaces.IConfig`. However, note that the following attributes are dynamically resolved using :attr:`~certbot.interfaces.IConfig.work_dir` and relative paths defined in :py:mod:`certbot.constants`: - `accounts_dir` - `csr_dir` - `in_progress_dir` - `key_dir` - `temp_checkpoint_dir` And the following paths are dynamically resolved using :attr:`~certbot.interfaces.IConfig.config_dir` and relative paths defined in :py:mod:`certbot.constants`: - `default_archive_dir` - `live_dir` - `renewal_configs_dir` :ivar namespace: Namespace typically produced by :meth:`argparse.ArgumentParser.parse_args`. :type namespace: :class:`argparse.Namespace` """ def __init__(self, namespace): object.__setattr__(self, 'namespace', namespace) self.namespace.config_dir = os.path.abspath(self.namespace.config_dir) self.namespace.work_dir = os.path.abspath(self.namespace.work_dir) self.namespace.logs_dir = os.path.abspath(self.namespace.logs_dir) # Check command line parameters sanity, and error out in case of problem. check_config_sanity(self) def __getattr__(self, name): return getattr(self.namespace, name) def __setattr__(self, name, value): setattr(self.namespace, name, value) @property def server_path(self): """File path based on ``server``.""" parsed = parse.urlparse(self.namespace.server) return (parsed.netloc + parsed.path).replace('/', os.path.sep) @property def accounts_dir(self): # pylint: disable=missing-docstring return self.accounts_dir_for_server_path(self.server_path) def accounts_dir_for_server_path(self, server_path): """Path to accounts directory based on server_path""" return os.path.join( self.namespace.config_dir, constants.ACCOUNTS_DIR, server_path) @property def backup_dir(self): # pylint: disable=missing-docstring return os.path.join(self.namespace.work_dir, constants.BACKUP_DIR) @property def csr_dir(self): # pylint: disable=missing-docstring return os.path.join(self.namespace.config_dir, constants.CSR_DIR) @property def in_progress_dir(self): # pylint: disable=missing-docstring return os.path.join(self.namespace.work_dir, constants.IN_PROGRESS_DIR) @property def key_dir(self): # pylint: disable=missing-docstring return os.path.join(self.namespace.config_dir, constants.KEY_DIR) @property def temp_checkpoint_dir(self): # pylint: disable=missing-docstring return os.path.join( self.namespace.work_dir, constants.TEMP_CHECKPOINT_DIR) def __deepcopy__(self, _memo): # Work around https://bugs.python.org/issue1515 for py26 tests :( :( # https://travis-ci.org/letsencrypt/letsencrypt/jobs/106900743#L3276 new_ns = copy.deepcopy(self.namespace) return type(self)(new_ns) @property def default_archive_dir(self): # pylint: disable=missing-docstring return os.path.join(self.namespace.config_dir, constants.ARCHIVE_DIR) @property def live_dir(self): # pylint: disable=missing-docstring return os.path.join(self.namespace.config_dir, constants.LIVE_DIR) @property def renewal_configs_dir(self): # pylint: disable=missing-docstring return os.path.join( self.namespace.config_dir, constants.RENEWAL_CONFIGS_DIR) @property def renewal_hooks_dir(self): """Path to directory with hooks to run with the renew subcommand.""" return os.path.join(self.namespace.config_dir, constants.RENEWAL_HOOKS_DIR) @property def renewal_pre_hooks_dir(self): """Path to the pre-hook directory for the renew subcommand.""" return os.path.join(self.renewal_hooks_dir, constants.RENEWAL_PRE_HOOKS_DIR) @property def renewal_deploy_hooks_dir(self): """Path to the deploy-hook directory for the renew subcommand.""" return os.path.join(self.renewal_hooks_dir, constants.RENEWAL_DEPLOY_HOOKS_DIR) @property def renewal_post_hooks_dir(self): """Path to the post-hook directory for the renew subcommand.""" return os.path.join(self.renewal_hooks_dir, constants.RENEWAL_POST_HOOKS_DIR) def check_config_sanity(config): """Validate command line options and display error message if requirements are not met. :param config: IConfig instance holding user configuration :type args: :class:`certbot.interfaces.IConfig` """ # Port check if config.http01_port == config.tls_sni_01_port: raise errors.ConfigurationError( "Trying to run http-01 and tls-sni-01 " "on the same port ({0})".format(config.tls_sni_01_port)) # Domain checks if config.namespace.domains is not None: for domain in config.namespace.domains: # This may be redundant, but let's be paranoid util.enforce_domain_sanity(domain) certbot-0.27.0/certbot/interfaces.py0000644000175000017500000005646313344054434017613 0ustar ericaerica00000000000000"""Certbot client interfaces.""" import abc import six import zope.interface # pylint: disable=no-self-argument,no-method-argument,no-init,inherit-non-class # pylint: disable=too-few-public-methods @six.add_metaclass(abc.ABCMeta) class AccountStorage(object): """Accounts storage interface.""" @abc.abstractmethod def find_all(self): # pragma: no cover """Find all accounts. :returns: All found accounts. :rtype: list """ raise NotImplementedError() @abc.abstractmethod def load(self, account_id): # pragma: no cover """Load an account by its id. :raises .AccountNotFound: if account could not be found :raises .AccountStorageError: if account could not be loaded """ raise NotImplementedError() @abc.abstractmethod def save(self, account, client): # pragma: no cover """Save account. :raises .AccountStorageError: if account could not be saved """ raise NotImplementedError() class IPluginFactory(zope.interface.Interface): """IPlugin factory. Objects providing this interface will be called without satisfying any entry point "extras" (extra dependencies) you might have defined for your plugin, e.g (excerpt from ``setup.py`` script):: setup( ... entry_points={ 'certbot.plugins': [ 'name=example_project.plugin[plugin_deps]', ], }, extras_require={ 'plugin_deps': ['dep1', 'dep2'], } ) Therefore, make sure such objects are importable and usable without extras. This is necessary, because CLI does the following operations (in order): - loads an entry point, - calls `inject_parser_options`, - requires an entry point, - creates plugin instance (`__call__`). """ description = zope.interface.Attribute("Short plugin description") def __call__(config, name): """Create new `IPlugin`. :param IConfig config: Configuration. :param str name: Unique plugin name. """ def inject_parser_options(parser, name): """Inject argument parser options (flags). 1. Be nice and prepend all options and destinations with `~.common.option_namespace` and `~common.dest_namespace`. 2. Inject options (flags) only. Positional arguments are not allowed, as this would break the CLI. :param ArgumentParser parser: (Almost) top-level CLI parser. :param str name: Unique plugin name. """ class IPlugin(zope.interface.Interface): """Certbot plugin.""" def prepare(): # type: ignore """Prepare the plugin. Finish up any additional initialization. :raises .PluginError: when full initialization cannot be completed. :raises .MisconfigurationError: when full initialization cannot be completed. Plugin will be displayed on a list of available plugins. :raises .NoInstallationError: when the necessary programs/files cannot be located. Plugin will NOT be displayed on a list of available plugins. :raises .NotSupportedError: when the installation is recognized, but the version is not currently supported. """ def more_info(): # type: ignore """Human-readable string to help the user. Should describe the steps taken and any relevant info to help the user decide which plugin to use. :rtype str: """ class IAuthenticator(IPlugin): """Generic Certbot Authenticator. Class represents all possible tools processes that have the ability to perform challenges and attain a certificate. """ def get_chall_pref(domain): """Return `collections.Iterable` of challenge preferences. :param str domain: Domain for which challenge preferences are sought. :returns: `collections.Iterable` of challenge types (subclasses of :class:`acme.challenges.Challenge`) with the most preferred challenges first. If a type is not specified, it means the Authenticator cannot perform the challenge. :rtype: `collections.Iterable` """ def perform(achalls): """Perform the given challenge. :param list achalls: Non-empty (guaranteed) list of :class:`~certbot.achallenges.AnnotatedChallenge` instances, such that it contains types found within :func:`get_chall_pref` only. :returns: `collections.Iterable` of ACME :class:`~acme.challenges.ChallengeResponse` instances or if the :class:`~acme.challenges.Challenge` cannot be fulfilled then: ``None`` Authenticator can perform challenge, but not at this time. ``False`` Authenticator will never be able to perform (error). :rtype: :class:`collections.Iterable` of :class:`acme.challenges.ChallengeResponse`, where responses are required to be returned in the same order as corresponding input challenges :raises .PluginError: If challenges cannot be performed """ def cleanup(achalls): """Revert changes and shutdown after challenges complete. This method should be able to revert all changes made by perform, even if perform exited abnormally. :param list achalls: Non-empty (guaranteed) list of :class:`~certbot.achallenges.AnnotatedChallenge` instances, a subset of those previously passed to :func:`perform`. :raises PluginError: if original configuration cannot be restored """ class IConfig(zope.interface.Interface): """Certbot user-supplied configuration. .. warning:: The values stored in the configuration have not been filtered, stripped or sanitized. """ server = zope.interface.Attribute("ACME Directory Resource URI.") email = zope.interface.Attribute( "Email used for registration and recovery contact. Use comma to " "register multiple emails, ex: u1@example.com,u2@example.com. " "(default: Ask).") rsa_key_size = zope.interface.Attribute("Size of the RSA key.") must_staple = zope.interface.Attribute( "Adds the OCSP Must Staple extension to the certificate. " "Autoconfigures OCSP Stapling for supported setups " "(Apache version >= 2.3.3 ).") config_dir = zope.interface.Attribute("Configuration directory.") work_dir = zope.interface.Attribute("Working directory.") accounts_dir = zope.interface.Attribute( "Directory where all account information is stored.") backup_dir = zope.interface.Attribute("Configuration backups directory.") csr_dir = zope.interface.Attribute( "Directory where newly generated Certificate Signing Requests " "(CSRs) are saved.") in_progress_dir = zope.interface.Attribute( "Directory used before a permanent checkpoint is finalized.") key_dir = zope.interface.Attribute("Keys storage.") temp_checkpoint_dir = zope.interface.Attribute( "Temporary checkpoint directory.") no_verify_ssl = zope.interface.Attribute( "Disable verification of the ACME server's certificate.") tls_sni_01_port = zope.interface.Attribute( "Port used during tls-sni-01 challenge. " "This only affects the port Certbot listens on. " "A conforming ACME server will still attempt to connect on port 443.") tls_sni_01_address = zope.interface.Attribute( "The address the server listens to during tls-sni-01 challenge.") http01_port = zope.interface.Attribute( "Port used in the http-01 challenge. " "This only affects the port Certbot listens on. " "A conforming ACME server will still attempt to connect on port 80.") http01_address = zope.interface.Attribute( "The address the server listens to during http-01 challenge.") pref_challs = zope.interface.Attribute( "Sorted user specified preferred challenges" "type strings with the most preferred challenge listed first") allow_subset_of_names = zope.interface.Attribute( "When performing domain validation, do not consider it a failure " "if authorizations can not be obtained for a strict subset of " "the requested domains. This may be useful for allowing renewals for " "multiple domains to succeed even if some domains no longer point " "at this system. This is a boolean") strict_permissions = zope.interface.Attribute( "Require that all configuration files are owned by the current " "user; only needed if your config is somewhere unsafe like /tmp/." "This is a boolean") disable_renew_updates = zope.interface.Attribute( "If updates provided by installer enhancements when Certbot is being run" " with \"renew\" verb should be disabled.") class IInstaller(IPlugin): """Generic Certbot Installer Interface. Represents any server that an X509 certificate can be placed. It is assumed that :func:`save` is the only method that finalizes a checkpoint. This is important to ensure that checkpoints are restored in a consistent manner if requested by the user or in case of an error. Using :class:`certbot.reverter.Reverter` to implement checkpoints, rollback, and recovery can dramatically simplify plugin development. """ def get_all_names(): # type: ignore """Returns all names that may be authenticated. :rtype: `collections.Iterable` of `str` """ def deploy_cert(domain, cert_path, key_path, chain_path, fullchain_path): """Deploy certificate. :param str domain: domain to deploy certificate file :param str cert_path: absolute path to the certificate file :param str key_path: absolute path to the private key file :param str chain_path: absolute path to the certificate chain file :param str fullchain_path: absolute path to the certificate fullchain file (cert plus chain) :raises .PluginError: when cert cannot be deployed """ def enhance(domain, enhancement, options=None): """Perform a configuration enhancement. :param str domain: domain for which to provide enhancement :param str enhancement: An enhancement as defined in :const:`~certbot.constants.ENHANCEMENTS` :param options: Flexible options parameter for enhancement. Check documentation of :const:`~certbot.constants.ENHANCEMENTS` for expected options for each enhancement. :raises .PluginError: If Enhancement is not supported, or if an error occurs during the enhancement. """ def supported_enhancements(): # type: ignore """Returns a `collections.Iterable` of supported enhancements. :returns: supported enhancements which should be a subset of :const:`~certbot.constants.ENHANCEMENTS` :rtype: :class:`collections.Iterable` of :class:`str` """ def save(title=None, temporary=False): """Saves all changes to the configuration files. Both title and temporary are needed because a save may be intended to be permanent, but the save is not ready to be a full checkpoint. It is assumed that at most one checkpoint is finalized by this method. Additionally, if an exception is raised, it is assumed a new checkpoint was not finalized. :param str title: The title of the save. If a title is given, the configuration will be saved as a new checkpoint and put in a timestamped directory. `title` has no effect if temporary is true. :param bool temporary: Indicates whether the changes made will be quickly reversed in the future (challenges) :raises .PluginError: when save is unsuccessful """ def rollback_checkpoints(rollback=1): """Revert `rollback` number of configuration checkpoints. :raises .PluginError: when configuration cannot be fully reverted """ def recovery_routine(): # type: ignore """Revert configuration to most recent finalized checkpoint. Remove all changes (temporary and permanent) that have not been finalized. This is useful to protect against crashes and other execution interruptions. :raises .errors.PluginError: If unable to recover the configuration """ def view_config_changes(): # type: ignore """Display all of the LE config changes. :raises .PluginError: when config changes cannot be parsed """ def config_test(): # type: ignore """Make sure the configuration is valid. :raises .MisconfigurationError: when the config is not in a usable state """ def restart(): # type: ignore """Restart or refresh the server content. :raises .PluginError: when server cannot be restarted """ class IDisplay(zope.interface.Interface): """Generic display.""" # pylint: disable=too-many-arguments # see https://github.com/certbot/certbot/issues/3915 def notification(message, pause, wrap=True, force_interactive=False): """Displays a string message :param str message: Message to display :param bool pause: Whether or not the application should pause for confirmation (if available) :param bool wrap: Whether or not the application should wrap text :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions """ def menu(message, choices, ok_label=None, cancel_label=None, help_label=None, default=None, cli_flag=None, force_interactive=False): """Displays a generic menu. When not setting force_interactive=True, you must provide a default value. :param str message: message to display :param choices: choices :type choices: :class:`list` of :func:`tuple` or :class:`str` :param str ok_label: label for OK button (UNUSED) :param str cancel_label: label for Cancel button (UNUSED) :param str help_label: label for Help button (UNUSED) :param int default: default (non-interactive) choice from the menu :param str cli_flag: to automate choice from the menu, eg "--keep" :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions :returns: tuple of (`code`, `index`) where `code` - str display exit code `index` - int index of the user's selection :raises errors.MissingCommandlineFlag: if called in non-interactive mode without a default set """ def input(message, default=None, cli_args=None, force_interactive=False): """Accept input from the user. When not setting force_interactive=True, you must provide a default value. :param str message: message to display to the user :param str default: default (non-interactive) response to prompt :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions :returns: tuple of (`code`, `input`) where `code` - str display exit code `input` - str of the user's input :rtype: tuple :raises errors.MissingCommandlineFlag: if called in non-interactive mode without a default set """ def yesno(message, yes_label="Yes", no_label="No", default=None, cli_args=None, force_interactive=False): """Query the user with a yes/no question. Yes and No label must begin with different letters. When not setting force_interactive=True, you must provide a default value. :param str message: question for the user :param str default: default (non-interactive) choice from the menu :param str cli_flag: to automate choice from the menu, eg "--redirect / --no-redirect" :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions :returns: True for "Yes", False for "No" :rtype: bool :raises errors.MissingCommandlineFlag: if called in non-interactive mode without a default set """ def checklist(message, tags, default=None, cli_args=None, force_interactive=False): """Allow for multiple selections from a menu. When not setting force_interactive=True, you must provide a default value. :param str message: message to display to the user :param list tags: where each is of type :class:`str` len(tags) > 0 :param str default: default (non-interactive) state of the checklist :param str cli_flag: to automate choice from the menu, eg "--domains" :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions :returns: tuple of the form (code, list_tags) where `code` - int display exit code `list_tags` - list of str tags selected by the user :rtype: tuple :raises errors.MissingCommandlineFlag: if called in non-interactive mode without a default set """ def directory_select(self, message, default=None, cli_flag=None, force_interactive=False): """Display a directory selection screen. When not setting force_interactive=True, you must provide a default value. :param str message: prompt to give the user :param default: the default value to return, if one exists, when using the NoninteractiveDisplay :param str cli_flag: option used to set this value with the CLI, if one exists, to be included in error messages given by NoninteractiveDisplay :param bool force_interactive: True if it's safe to prompt the user because it won't cause any workflow regressions :returns: tuple of the form (`code`, `string`) where `code` - int display exit code `string` - input entered by the user """ class IValidator(zope.interface.Interface): """Configuration validator.""" def certificate(cert, name, alt_host=None, port=443): """Verifies the certificate presented at name is cert :param OpenSSL.crypto.X509 cert: Expected certificate :param str name: Server's domain name :param bytes alt_host: Host to connect to instead of the IP address of host :param int port: Port to connect to :returns: True if the certificate was verified successfully :rtype: bool """ def redirect(name, port=80, headers=None): """Verify redirect to HTTPS :param str name: Server's domain name :param int port: Port to connect to :param dict headers: HTTP headers to include in request :returns: True if redirect is successfully enabled :rtype: bool """ def hsts(name): """Verify HSTS header is enabled :param str name: Server's domain name :returns: True if HSTS header is successfully enabled :rtype: bool """ def ocsp_stapling(name): """Verify ocsp stapling for domain :param str name: Server's domain name :returns: True if ocsp stapling is successfully enabled :rtype: bool """ class IReporter(zope.interface.Interface): """Interface to collect and display information to the user.""" HIGH_PRIORITY = zope.interface.Attribute( "Used to denote high priority messages") MEDIUM_PRIORITY = zope.interface.Attribute( "Used to denote medium priority messages") LOW_PRIORITY = zope.interface.Attribute( "Used to denote low priority messages") def add_message(self, msg, priority, on_crash=True): """Adds msg to the list of messages to be printed. :param str msg: Message to be displayed to the user. :param int priority: One of HIGH_PRIORITY, MEDIUM_PRIORITY, or LOW_PRIORITY. :param bool on_crash: Whether or not the message should be printed if the program exits abnormally. """ def print_messages(self): """Prints messages to the user and clears the message queue.""" # Updater interfaces # # When "certbot renew" is run, Certbot will iterate over each lineage and check # if the selected installer for that lineage is a subclass of each updater # class. If it is and the update of that type is configured to be run for that # lineage, the relevant update function will be called for it. These functions # are never called for other subcommands, so if an installer wants to perform # an update during the run or install subcommand, it should do so when # :func:`IInstaller.deploy_cert` is called. @six.add_metaclass(abc.ABCMeta) class GenericUpdater(object): """Interface for update types not currently specified by Certbot. This class allows plugins to perform types of updates that Certbot hasn't defined (yet). To make use of this interface, the installer should implement the interface methods, and interfaces.GenericUpdater.register(InstallerClass) should be called from the installer code. The plugins implementing this enhancement are responsible of handling the saving of configuration checkpoints as well as other calls to interface methods of `interfaces.IInstaller` such as prepare() and restart() """ @abc.abstractmethod def generic_updates(self, lineage, *args, **kwargs): """Perform any update types defined by the installer. If an installer is a subclass of the class containing this method, this function will always be called when "certbot renew" is run. If the update defined by the installer should be run conditionally, the installer needs to handle checking the conditions itself. This method is called once for each lineage. :param lineage: Certificate lineage object :type lineage: storage.RenewableCert """ @six.add_metaclass(abc.ABCMeta) class RenewDeployer(object): """Interface for update types run when a lineage is renewed This class allows plugins to perform types of updates that need to run at lineage renewal that Certbot hasn't defined (yet). To make use of this interface, the installer should implement the interface methods, and interfaces.RenewDeployer.register(InstallerClass) should be called from the installer code. """ @abc.abstractmethod def renew_deploy(self, lineage, *args, **kwargs): """Perform updates defined by installer when a certificate has been renewed If an installer is a subclass of the class containing this method, this function will always be called when a certficate has been renewed by running "certbot renew". For example if a plugin needs to copy a certificate over, or change configuration based on the new certificate. This method is called once for each lineage renewed :param lineage: Certificate lineage object :type lineage: storage.RenewableCert """ certbot-0.27.0/certbot/eff.py0000644000175000017500000000610713344054434016216 0ustar ericaerica00000000000000"""Subscribes users to the EFF newsletter.""" import logging import requests import zope.component from certbot import constants from certbot import interfaces logger = logging.getLogger(__name__) def handle_subscription(config): """High level function to take care of EFF newsletter subscriptions. The user may be asked if they want to sign up for the newsletter if they have not already specified. :param .IConfig config: Client configuration. """ if config.email is None: if config.eff_email: _report_failure("you didn't provide an e-mail address") return if config.eff_email is None: config.eff_email = _want_subscription() if config.eff_email: subscribe(config.email) def _want_subscription(): """Does the user want to be subscribed to the EFF newsletter? :returns: True if we should subscribe the user, otherwise, False :rtype: bool """ prompt = ( 'Would you be willing to share your email address with the ' "Electronic Frontier Foundation, a founding partner of the Let's " 'Encrypt project and the non-profit organization that develops ' "Certbot? We'd like to send you email about our work encrypting " "the web, EFF news, campaigns, and ways to support digital freedom. ") display = zope.component.getUtility(interfaces.IDisplay) return display.yesno(prompt, default=False) def subscribe(email): """Subscribe the user to the EFF mailing list. :param str email: the e-mail address to subscribe """ url = constants.EFF_SUBSCRIBE_URI data = {'data_type': 'json', 'email': email, 'form_id': 'eff_supporters_library_subscribe_form'} logger.debug('Sending POST request to %s:\n%s', url, data) _check_response(requests.post(url, data=data)) def _check_response(response): """Check for errors in the server's response. If an error occurred, it will be reported to the user. :param requests.Response response: the server's response to the subscription request """ logger.debug('Received response:\n%s', response.content) try: response.raise_for_status() if response.json()['status'] == False: _report_failure('your e-mail address appears to be invalid') except requests.exceptions.HTTPError: _report_failure() except (ValueError, KeyError): _report_failure('there was a problem with the server response') def _report_failure(reason=None): """Notify the user of failing to sign them up for the newsletter. :param reason: a phrase describing what the problem was beginning with a lowercase letter and no closing punctuation :type reason: `str` or `None` """ msg = ['We were unable to subscribe you the EFF mailing list'] if reason is not None: msg.append(' because ') msg.append(reason) msg.append('. You can try again later by visiting https://act.eff.org.') reporter = zope.component.getUtility(interfaces.IReporter) reporter.add_message(''.join(msg), reporter.LOW_PRIORITY) certbot-0.27.0/certbot/renewal.py0000644000175000017500000004605413344054434017120 0ustar ericaerica00000000000000"""Functionality for autorenewal and associated juggling of configurations""" from __future__ import print_function import copy import itertools import logging import os import traceback import six import zope.component import OpenSSL from acme.magic_typing import List # pylint: disable=unused-import, no-name-in-module from certbot import cli from certbot import crypto_util from certbot import errors from certbot import interfaces from certbot import util from certbot import hooks from certbot import storage from certbot import updater from certbot.plugins import disco as plugins_disco logger = logging.getLogger(__name__) # These are the items which get pulled out of a renewal configuration # file's renewalparams and actually used in the client configuration # during the renewal process. We have to record their types here because # the renewal configuration process loses this information. STR_CONFIG_ITEMS = ["config_dir", "logs_dir", "work_dir", "user_agent", "server", "account", "authenticator", "installer", "standalone_supported_challenges", "renew_hook", "pre_hook", "post_hook", "tls_sni_01_address", "http01_address"] INT_CONFIG_ITEMS = ["rsa_key_size", "tls_sni_01_port", "http01_port"] BOOL_CONFIG_ITEMS = ["must_staple", "allow_subset_of_names", "reuse_key", "autorenew"] CONFIG_ITEMS = set(itertools.chain( BOOL_CONFIG_ITEMS, INT_CONFIG_ITEMS, STR_CONFIG_ITEMS, ('pref_challs',))) def _reconstitute(config, full_path): """Try to instantiate a RenewableCert, updating config with relevant items. This is specifically for use in renewal and enforces several checks and policies to ensure that we can try to proceed with the renewal request. The config argument is modified by including relevant options read from the renewal configuration file. :param configuration.NamespaceConfig config: configuration for the current lineage :param str full_path: Absolute path to the configuration file that defines this lineage :returns: the RenewableCert object or None if a fatal error occurred :rtype: `storage.RenewableCert` or NoneType """ try: renewal_candidate = storage.RenewableCert(full_path, config) except (errors.CertStorageError, IOError): logger.warning("", exc_info=True) logger.warning("Renewal configuration file %s is broken. Skipping.", full_path) logger.debug("Traceback was:\n%s", traceback.format_exc()) return None if "renewalparams" not in renewal_candidate.configuration: logger.warning("Renewal configuration file %s lacks " "renewalparams. Skipping.", full_path) return None renewalparams = renewal_candidate.configuration["renewalparams"] if "authenticator" not in renewalparams: logger.warning("Renewal configuration file %s does not specify " "an authenticator. Skipping.", full_path) return None # Now restore specific values along with their data types, if # those elements are present. try: restore_required_config_elements(config, renewalparams) _restore_plugin_configs(config, renewalparams) except (ValueError, errors.Error) as error: logger.warning( "An error occurred while parsing %s. The error was %s. " "Skipping the file.", full_path, str(error)) logger.debug("Traceback was:\n%s", traceback.format_exc()) return None try: config.domains = [util.enforce_domain_sanity(d) for d in renewal_candidate.names()] except errors.ConfigurationError as error: logger.warning("Renewal configuration file %s references a cert " "that contains an invalid domain name. The problem " "was: %s. Skipping.", full_path, error) return None return renewal_candidate def _restore_webroot_config(config, renewalparams): """ webroot_map is, uniquely, a dict, and the general-purpose configuration restoring logic is not able to correctly parse it from the serialized form. """ if "webroot_map" in renewalparams: if not cli.set_by_cli("webroot_map"): config.webroot_map = renewalparams["webroot_map"] elif "webroot_path" in renewalparams: logger.debug("Ancient renewal conf file without webroot-map, restoring webroot-path") wp = renewalparams["webroot_path"] if isinstance(wp, six.string_types): # prior to 0.1.0, webroot_path was a string wp = [wp] config.webroot_path = wp def _restore_plugin_configs(config, renewalparams): """Sets plugin specific values in config from renewalparams :param configuration.NamespaceConfig config: configuration for the current lineage :param configobj.Section renewalparams: Parameters from the renewal configuration file that defines this lineage """ # Now use parser to get plugin-prefixed items with correct types # XXX: the current approach of extracting only prefixed items # related to the actually-used installer and authenticator # works as long as plugins don't need to read plugin-specific # variables set by someone else (e.g., assuming Apache # configurator doesn't need to read webroot_ variables). # Note: if a parameter that used to be defined in the parser is no # longer defined, stored copies of that parameter will be # deserialized as strings by this logic even if they were # originally meant to be some other type. plugin_prefixes = [] # type: List[str] if renewalparams["authenticator"] == "webroot": _restore_webroot_config(config, renewalparams) else: plugin_prefixes.append(renewalparams["authenticator"]) if renewalparams.get("installer") is not None: plugin_prefixes.append(renewalparams["installer"]) for plugin_prefix in set(plugin_prefixes): plugin_prefix = plugin_prefix.replace('-', '_') for config_item, config_value in six.iteritems(renewalparams): if config_item.startswith(plugin_prefix + "_") and not cli.set_by_cli(config_item): # Values None, True, and False need to be treated specially, # As their types aren't handled correctly by configobj if config_value in ("None", "True", "False"): # bool("False") == True # pylint: disable=eval-used setattr(config, config_item, eval(config_value)) else: cast = cli.argparse_type(config_item) setattr(config, config_item, cast(config_value)) def restore_required_config_elements(config, renewalparams): """Sets non-plugin specific values in config from renewalparams :param configuration.NamespaceConfig config: configuration for the current lineage :param configobj.Section renewalparams: parameters from the renewal configuration file that defines this lineage """ required_items = itertools.chain( (("pref_challs", _restore_pref_challs),), six.moves.zip(BOOL_CONFIG_ITEMS, itertools.repeat(_restore_bool)), six.moves.zip(INT_CONFIG_ITEMS, itertools.repeat(_restore_int)), six.moves.zip(STR_CONFIG_ITEMS, itertools.repeat(_restore_str))) for item_name, restore_func in required_items: if item_name in renewalparams and not cli.set_by_cli(item_name): value = restore_func(item_name, renewalparams[item_name]) setattr(config, item_name, value) def _restore_pref_challs(unused_name, value): """Restores preferred challenges from a renewal config file. If value is a `str`, it should be a single challenge type. :param str unused_name: option name :param value: option value :type value: `list` of `str` or `str` :returns: converted option value to be stored in the runtime config :rtype: `list` of `str` :raises errors.Error: if value can't be converted to an bool """ # If pref_challs has only one element, configobj saves the value # with a trailing comma so it's parsed as a list. If this comma is # removed by the user, the value is parsed as a str. value = [value] if isinstance(value, six.string_types) else value return cli.parse_preferred_challenges(value) def _restore_bool(name, value): """Restores an boolean key-value pair from a renewal config file. :param str name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: bool :raises errors.Error: if value can't be converted to an bool """ lowercase_value = value.lower() if lowercase_value not in ("true", "false"): raise errors.Error( "Expected True or False for {0} but found {1}".format(name, value)) return lowercase_value == "true" def _restore_int(name, value): """Restores an integer key-value pair from a renewal config file. :param str name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: int :raises errors.Error: if value can't be converted to an int """ if name == "http01_port" and value == "None": logger.info("updating legacy http01_port value") return cli.flag_default("http01_port") try: return int(value) except ValueError: raise errors.Error("Expected a numeric value for {0}".format(name)) def _restore_str(unused_name, value): """Restores an string key-value pair from a renewal config file. :param str unused_name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: str or None """ return None if value == "None" else value def should_renew(config, lineage): "Return true if any of the circumstances for automatic renewal apply." if config.renew_by_default: logger.debug("Auto-renewal forced with --force-renewal...") return True if lineage.should_autorenew(): logger.info("Cert is due for renewal, auto-renewing...") return True if config.dry_run: logger.info("Cert not due for renewal, but simulating renewal for dry run") return True logger.info("Cert not yet due for renewal") return False def _avoid_invalidating_lineage(config, lineage, original_server): "Do not renew a valid cert with one from a staging server!" # Some lineages may have begun with --staging, but then had production certs # added to them latest_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, open(lineage.cert).read()) # all our test certs are from happy hacker fake CA, though maybe one day # we should test more methodically now_valid = "fake" not in repr(latest_cert.get_issuer()).lower() if util.is_staging(config.server): if not util.is_staging(original_server) or now_valid: if not config.break_my_certs: names = ", ".join(lineage.names()) raise errors.Error( "You've asked to renew/replace a seemingly valid certificate with " "a test certificate (domains: {0}). We will not do that " "unless you use the --break-my-certs flag!".format(names)) def renew_cert(config, domains, le_client, lineage): "Renew a certificate lineage." renewal_params = lineage.configuration["renewalparams"] original_server = renewal_params.get("server", cli.flag_default("server")) _avoid_invalidating_lineage(config, lineage, original_server) if not domains: domains = lineage.names() # The private key is the existing lineage private key if reuse_key is set. # Otherwise, generate a fresh private key by passing None. new_key = lineage.privkey if config.reuse_key else None new_cert, new_chain, new_key, _ = le_client.obtain_certificate(domains, new_key) if config.dry_run: logger.debug("Dry run: skipping updating lineage at %s", os.path.dirname(lineage.cert)) else: prior_version = lineage.latest_common_version() # TODO: Check return value of save_successor lineage.save_successor(prior_version, new_cert, new_key.pem, new_chain, config) lineage.update_all_links_to(lineage.latest_common_version()) hooks.renew_hook(config, domains, lineage.live_dir) def report(msgs, category): "Format a results report for a category of renewal outcomes" lines = ("%s (%s)" % (m, category) for m in msgs) return " " + "\n ".join(lines) def _renew_describe_results(config, renew_successes, renew_failures, renew_skipped, parse_failures): out = [] # type: List[str] notify = out.append disp = zope.component.getUtility(interfaces.IDisplay) def notify_error(err): """Notify and log errors.""" notify(str(err)) logger.error(err) if config.dry_run: notify("** DRY RUN: simulating 'certbot renew' close to cert expiry") notify("** (The test certificates below have not been saved.)") notify("") if renew_skipped: notify("The following certs are not due for renewal yet:") notify(report(renew_skipped, "skipped")) if not renew_successes and not renew_failures: notify("No renewals were attempted.") if (config.pre_hook is not None or config.renew_hook is not None or config.post_hook is not None): notify("No hooks were run.") elif renew_successes and not renew_failures: notify("Congratulations, all renewals succeeded. The following certs " "have been renewed:") notify(report(renew_successes, "success")) elif renew_failures and not renew_successes: notify_error("All renewal attempts failed. The following certs could " "not be renewed:") notify_error(report(renew_failures, "failure")) elif renew_failures and renew_successes: notify("The following certs were successfully renewed:") notify(report(renew_successes, "success") + "\n") notify_error("The following certs could not be renewed:") notify_error(report(renew_failures, "failure")) if parse_failures: notify("\nAdditionally, the following renewal configurations " "were invalid: ") notify(report(parse_failures, "parsefail")) if config.dry_run: notify("** DRY RUN: simulating 'certbot renew' close to cert expiry") notify("** (The test certificates above have not been saved.)") disp.notification("\n".join(out), wrap=False) def handle_renewal_request(config): """Examine each lineage; renew if due and report results""" # This is trivially False if config.domains is empty if any(domain not in config.webroot_map for domain in config.domains): # If more plugins start using cli.add_domains, # we may want to only log a warning here raise errors.Error("Currently, the renew verb is capable of either " "renewing all installed certificates that are due " "to be renewed or renewing a single certificate specified " "by its name. If you would like to renew specific " "certificates by their domains, use the certonly command " "instead. The renew verb may provide other options " "for selecting certificates to renew in the future.") if config.certname: conf_files = [storage.renewal_file_for_certname(config, config.certname)] else: conf_files = storage.renewal_conf_files(config) renew_successes = [] renew_failures = [] renew_skipped = [] parse_failures = [] for renewal_file in conf_files: disp = zope.component.getUtility(interfaces.IDisplay) disp.notification("Processing " + renewal_file, pause=False) lineage_config = copy.deepcopy(config) lineagename = storage.lineagename_for_filename(renewal_file) # Note that this modifies config (to add back the configuration # elements from within the renewal configuration file). try: renewal_candidate = _reconstitute(lineage_config, renewal_file) except Exception as e: # pylint: disable=broad-except logger.warning("Renewal configuration file %s (cert: %s) " "produced an unexpected error: %s. Skipping.", renewal_file, lineagename, e) logger.debug("Traceback was:\n%s", traceback.format_exc()) parse_failures.append(renewal_file) continue try: if renewal_candidate is None: parse_failures.append(renewal_file) else: # XXX: ensure that each call here replaces the previous one zope.component.provideUtility(lineage_config) renewal_candidate.ensure_deployed() from certbot import main plugins = plugins_disco.PluginsRegistry.find_all() if should_renew(lineage_config, renewal_candidate): # domains have been restored into lineage_config by reconstitute # but they're unnecessary anyway because renew_cert here # will just grab them from the certificate # we already know it's time to renew based on should_renew # and we have a lineage in renewal_candidate main.renew_cert(lineage_config, plugins, renewal_candidate) renew_successes.append(renewal_candidate.fullchain) else: expiry = crypto_util.notAfter(renewal_candidate.version( "cert", renewal_candidate.latest_common_version())) renew_skipped.append("%s expires on %s" % (renewal_candidate.fullchain, expiry.strftime("%Y-%m-%d"))) # Run updater interface methods updater.run_generic_updaters(lineage_config, renewal_candidate, plugins) except Exception as e: # pylint: disable=broad-except # obtain_cert (presumably) encountered an unanticipated problem. logger.warning("Attempting to renew cert (%s) from %s produced an " "unexpected error: %s. Skipping.", lineagename, renewal_file, e) logger.debug("Traceback was:\n%s", traceback.format_exc()) renew_failures.append(renewal_candidate.fullchain) # Describe all the results _renew_describe_results(config, renew_successes, renew_failures, renew_skipped, parse_failures) if renew_failures or parse_failures: raise errors.Error("{0} renew failure(s), {1} parse failure(s)".format( len(renew_failures), len(parse_failures))) else: logger.debug("no renewal failures") certbot-0.27.0/certbot/account.py0000644000175000017500000003371113344054434017113 0ustar ericaerica00000000000000"""Creates ACME accounts for server.""" import datetime import functools import hashlib import logging import os import shutil import socket from cryptography.hazmat.primitives import serialization import josepy as jose import pyrfc3339 import pytz import six import zope.component from acme import fields as acme_fields from acme import messages from certbot import constants from certbot import errors from certbot import interfaces from certbot import util logger = logging.getLogger(__name__) class Account(object): # pylint: disable=too-few-public-methods """ACME protocol registration. :ivar .RegistrationResource regr: Registration Resource :ivar .JWK key: Authorized Account Key :ivar .Meta: Account metadata :ivar str id: Globally unique account identifier. """ class Meta(jose.JSONObjectWithFields): """Account metadata :ivar datetime.datetime creation_dt: Creation date and time (UTC). :ivar str creation_host: FQDN of host, where account has been created. .. note:: ``creation_dt`` and ``creation_host`` are useful in cross-machine migration scenarios. """ creation_dt = acme_fields.RFC3339Field("creation_dt") creation_host = jose.Field("creation_host") def __init__(self, regr, key, meta=None): self.key = key self.regr = regr self.meta = self.Meta( # pyrfc3339 drops microseconds, make sure __eq__ is sane creation_dt=datetime.datetime.now( tz=pytz.UTC).replace(microsecond=0), creation_host=socket.getfqdn()) if meta is None else meta self.id = hashlib.md5( self.key.key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) ).hexdigest() # Implementation note: Email? Multiple accounts can have the # same email address. Registration URI? Assigned by the # server, not guaranteed to be stable over time, nor # canonical URI can be generated. ACME protocol doesn't allow # account key (and thus its fingerprint) to be updated... @property def slug(self): """Short account identification string, useful for UI.""" return "{1}@{0} ({2})".format(pyrfc3339.generate( self.meta.creation_dt), self.meta.creation_host, self.id[:4]) def __repr__(self): return "<{0}({1}, {2}, {3})>".format( self.__class__.__name__, self.regr, self.id, self.meta) def __eq__(self, other): return (isinstance(other, self.__class__) and self.key == other.key and self.regr == other.regr and self.meta == other.meta) def report_new_account(config): """Informs the user about their new ACME account.""" reporter = zope.component.queryUtility(interfaces.IReporter) if reporter is None: return reporter.add_message( "Your account credentials have been saved in your Certbot " "configuration directory at {0}. You should make a secure backup " "of this folder now. This configuration directory will also " "contain certificates and private keys obtained by Certbot " "so making regular backups of this folder is ideal.".format( config.config_dir), reporter.MEDIUM_PRIORITY) class AccountMemoryStorage(interfaces.AccountStorage): """In-memory account storage.""" def __init__(self, initial_accounts=None): self.accounts = initial_accounts if initial_accounts is not None else {} def find_all(self): return list(six.itervalues(self.accounts)) def save(self, account, acme): # pylint: disable=unused-argument if account.id in self.accounts: logger.debug("Overwriting account: %s", account.id) self.accounts[account.id] = account def load(self, account_id): try: return self.accounts[account_id] except KeyError: raise errors.AccountNotFound(account_id) class RegistrationResourceWithNewAuthzrURI(messages.RegistrationResource): """A backwards-compatible RegistrationResource with a new-authz URI. Hack: Certbot versions pre-0.11.1 expect to load new_authzr_uri as part of the account. Because people sometimes switch between old and new versions, we will continue to write out this field for some time so older clients don't crash in that scenario. """ new_authzr_uri = jose.Field('new_authzr_uri') class AccountFileStorage(interfaces.AccountStorage): """Accounts file storage. :ivar .IConfig config: Client configuration """ def __init__(self, config): self.config = config util.make_or_verify_dir(config.accounts_dir, 0o700, os.geteuid(), self.config.strict_permissions) def _account_dir_path(self, account_id): return self._account_dir_path_for_server_path(account_id, self.config.server_path) def _account_dir_path_for_server_path(self, account_id, server_path): accounts_dir = self.config.accounts_dir_for_server_path(server_path) return os.path.join(accounts_dir, account_id) @classmethod def _regr_path(cls, account_dir_path): return os.path.join(account_dir_path, "regr.json") @classmethod def _key_path(cls, account_dir_path): return os.path.join(account_dir_path, "private_key.json") @classmethod def _metadata_path(cls, account_dir_path): return os.path.join(account_dir_path, "meta.json") def _find_all_for_server_path(self, server_path): accounts_dir = self.config.accounts_dir_for_server_path(server_path) try: candidates = os.listdir(accounts_dir) except OSError: return [] accounts = [] for account_id in candidates: try: accounts.append(self._load_for_server_path(account_id, server_path)) except errors.AccountStorageError: logger.debug("Account loading problem", exc_info=True) if not accounts and server_path in constants.LE_REUSE_SERVERS: # find all for the next link down prev_server_path = constants.LE_REUSE_SERVERS[server_path] prev_accounts = self._find_all_for_server_path(prev_server_path) # if we found something, link to that if prev_accounts: try: self._symlink_to_accounts_dir(prev_server_path, server_path) except OSError: return [] accounts = prev_accounts return accounts def find_all(self): return self._find_all_for_server_path(self.config.server_path) def _symlink_to_account_dir(self, prev_server_path, server_path, account_id): prev_account_dir = self._account_dir_path_for_server_path(account_id, prev_server_path) new_account_dir = self._account_dir_path_for_server_path(account_id, server_path) os.symlink(prev_account_dir, new_account_dir) def _symlink_to_accounts_dir(self, prev_server_path, server_path): accounts_dir = self.config.accounts_dir_for_server_path(server_path) if os.path.islink(accounts_dir): os.unlink(accounts_dir) else: os.rmdir(accounts_dir) prev_account_dir = self.config.accounts_dir_for_server_path(prev_server_path) os.symlink(prev_account_dir, accounts_dir) def _load_for_server_path(self, account_id, server_path): account_dir_path = self._account_dir_path_for_server_path(account_id, server_path) if not os.path.isdir(account_dir_path): # isdir is also true for symlinks if server_path in constants.LE_REUSE_SERVERS: prev_server_path = constants.LE_REUSE_SERVERS[server_path] prev_loaded_account = self._load_for_server_path(account_id, prev_server_path) # we didn't error so we found something, so create a symlink to that accounts_dir = self.config.accounts_dir_for_server_path(server_path) # If accounts_dir isn't empty, make an account specific symlink if os.listdir(accounts_dir): self._symlink_to_account_dir(prev_server_path, server_path, account_id) else: self._symlink_to_accounts_dir(prev_server_path, server_path) return prev_loaded_account else: raise errors.AccountNotFound( "Account at %s does not exist" % account_dir_path) try: with open(self._regr_path(account_dir_path)) as regr_file: regr = messages.RegistrationResource.json_loads(regr_file.read()) with open(self._key_path(account_dir_path)) as key_file: key = jose.JWK.json_loads(key_file.read()) with open(self._metadata_path(account_dir_path)) as metadata_file: meta = Account.Meta.json_loads(metadata_file.read()) except IOError as error: raise errors.AccountStorageError(error) acc = Account(regr, key, meta) if acc.id != account_id: raise errors.AccountStorageError( "Account ids mismatch (expected: {0}, found: {1}".format( account_id, acc.id)) return acc def load(self, account_id): return self._load_for_server_path(account_id, self.config.server_path) def save(self, account, acme): self._save(account, acme, regr_only=False) def save_regr(self, account, acme): """Save the registration resource. :param Account account: account whose regr should be saved """ self._save(account, acme, regr_only=True) def delete(self, account_id): """Delete registration info from disk :param account_id: id of account which should be deleted """ account_dir_path = self._account_dir_path(account_id) if not os.path.isdir(account_dir_path): raise errors.AccountNotFound( "Account at %s does not exist" % account_dir_path) # Step 1: Delete account specific links and the directory self._delete_account_dir_for_server_path(account_id, self.config.server_path) # Step 2: Remove any accounts links and directories that are now empty if not os.listdir(self.config.accounts_dir): self._delete_accounts_dir_for_server_path(self.config.server_path) def _delete_account_dir_for_server_path(self, account_id, server_path): link_func = functools.partial(self._account_dir_path_for_server_path, account_id) nonsymlinked_dir = self._delete_links_and_find_target_dir(server_path, link_func) shutil.rmtree(nonsymlinked_dir) def _delete_accounts_dir_for_server_path(self, server_path): link_func = self.config.accounts_dir_for_server_path nonsymlinked_dir = self._delete_links_and_find_target_dir(server_path, link_func) os.rmdir(nonsymlinked_dir) def _delete_links_and_find_target_dir(self, server_path, link_func): """Delete symlinks and return the nonsymlinked directory path. :param str server_path: file path based on server :param callable link_func: callable that returns possible links given a server_path :returns: the final, non-symlinked target :rtype: str """ dir_path = link_func(server_path) # does an appropriate directory link to me? if so, make sure that's gone reused_servers = {} for k in constants.LE_REUSE_SERVERS: reused_servers[constants.LE_REUSE_SERVERS[k]] = k # is there a next one up? possible_next_link = True while possible_next_link: possible_next_link = False if server_path in reused_servers: next_server_path = reused_servers[server_path] next_dir_path = link_func(next_server_path) if os.path.islink(next_dir_path) and os.readlink(next_dir_path) == dir_path: possible_next_link = True server_path = next_server_path dir_path = next_dir_path # if there's not a next one up to delete, then delete me # and whatever I link to while os.path.islink(dir_path): target = os.readlink(dir_path) os.unlink(dir_path) dir_path = target return dir_path def _save(self, account, acme, regr_only): account_dir_path = self._account_dir_path(account.id) util.make_or_verify_dir(account_dir_path, 0o700, os.geteuid(), self.config.strict_permissions) try: with open(self._regr_path(account_dir_path), "w") as regr_file: regr = account.regr # If we have a value for new-authz, save it for forwards # compatibility with older versions of Certbot. If we don't # have a value for new-authz, this is an ACMEv2 directory where # an older version of Certbot won't work anyway. if hasattr(acme.directory, "new-authz"): regr = RegistrationResourceWithNewAuthzrURI( new_authzr_uri=acme.directory.new_authz, body={}, uri=regr.uri) else: regr = messages.RegistrationResource( body={}, uri=regr.uri) regr_file.write(regr.json_dumps()) if not regr_only: with util.safe_open(self._key_path(account_dir_path), "w", chmod=0o400) as key_file: key_file.write(account.key.json_dumps()) with open(self._metadata_path( account_dir_path), "w") as metadata_file: metadata_file.write(account.meta.json_dumps()) except IOError as error: raise errors.AccountStorageError(error) certbot-0.27.0/certbot/notify.py0000644000175000017500000000205013344054434016757 0ustar ericaerica00000000000000"""Send e-mail notification to system administrators.""" import email import smtplib import socket import subprocess def notify(subject, whom, what): """Send email notification. Try to notify the addressee (``whom``) by e-mail, with Subject: defined by ``subject`` and message body by ``what``. """ msg = email.message_from_string(what) msg.add_header("From", "Certbot renewal agent ") msg.add_header("To", whom) msg.add_header("Subject", subject) msg = msg.as_string() try: lmtp = smtplib.LMTP() lmtp.connect() lmtp.sendmail("root", [whom], msg) except (smtplib.SMTPHeloError, smtplib.SMTPRecipientsRefused, smtplib.SMTPSenderRefused, smtplib.SMTPDataError, socket.error): # We should try using /usr/sbin/sendmail in this case try: proc = subprocess.Popen(["/usr/sbin/sendmail", "-t"], stdin=subprocess.PIPE) proc.communicate(msg) except OSError: return False return True certbot-0.27.0/certbot/constants.py0000644000175000017500000001452213344054434017472 0ustar ericaerica00000000000000"""Certbot constants.""" import logging import os import pkg_resources from acme import challenges SETUPTOOLS_PLUGINS_ENTRY_POINT = "certbot.plugins" """Setuptools entry point group name for plugins.""" OLD_SETUPTOOLS_PLUGINS_ENTRY_POINT = "letsencrypt.plugins" """Plugins Setuptools entry point before rename.""" CLI_DEFAULTS = dict( config_files=[ "/etc/letsencrypt/cli.ini", # http://freedesktop.org/wiki/Software/xdg-user-dirs/ os.path.join(os.environ.get("XDG_CONFIG_HOME", "~/.config"), "letsencrypt", "cli.ini"), ], # Main parser verbose_count=-int(logging.INFO / 10), text_mode=False, max_log_backups=1000, noninteractive_mode=False, force_interactive=False, domains=[], certname=None, dry_run=False, register_unsafely_without_email=False, update_registration=False, email=None, eff_email=None, reinstall=False, expand=False, renew_by_default=False, renew_with_new_domains=False, autorenew=True, allow_subset_of_names=False, tos=False, account=None, duplicate=False, os_packages_only=False, no_self_upgrade=False, no_bootstrap=False, quiet=False, staging=False, debug=False, debug_challenges=False, no_verify_ssl=False, tls_sni_01_port=challenges.TLSSNI01Response.PORT, tls_sni_01_address="", http01_port=challenges.HTTP01Response.PORT, http01_address="", break_my_certs=False, rsa_key_size=2048, must_staple=False, redirect=None, auto_hsts=False, hsts=None, uir=None, staple=None, strict_permissions=False, pref_challs=[], validate_hooks=True, directory_hooks=True, reuse_key=False, disable_renew_updates=False, # Subparsers num=None, user_agent=None, user_agent_comment=None, csr=None, reason=0, delete_after_revoke=None, rollback_checkpoints=1, init=False, prepare=False, ifaces=None, # Path parsers auth_cert_path="./cert.pem", auth_chain_path="./chain.pem", key_path=None, config_dir="/etc/letsencrypt", work_dir="/var/lib/letsencrypt", logs_dir="/var/log/letsencrypt", server="https://acme-v02.api.letsencrypt.org/directory", # Plugins parsers configurator=None, authenticator=None, installer=None, apache=False, nginx=False, standalone=False, manual=False, webroot=False, dns_cloudflare=False, dns_cloudxns=False, dns_digitalocean=False, dns_dnsimple=False, dns_dnsmadeeasy=False, dns_gehirn=False, dns_google=False, dns_linode=False, dns_luadns=False, dns_nsone=False, dns_ovh=False, dns_rfc2136=False, dns_route53=False, dns_sakuracloud=False ) STAGING_URI = "https://acme-staging-v02.api.letsencrypt.org/directory" # The set of reasons for revoking a certificate is defined in RFC 5280 in # section 5.3.1. The reasons that users are allowed to submit are restricted to # those accepted by the ACME server implementation. They are listed in # `letsencrypt.boulder.revocation.reasons.go`. REVOCATION_REASONS = { "unspecified": 0, "keycompromise": 1, "affiliationchanged": 3, "superseded": 4, "cessationofoperation": 5} """Defaults for CLI flags and `.IConfig` attributes.""" QUIET_LOGGING_LEVEL = logging.WARNING """Logging level to use in quiet mode.""" RENEWER_DEFAULTS = dict( renewer_enabled="yes", renew_before_expiry="30 days", # This value should ensure that there is never a deployment delay by # default. deploy_before_expiry="99 years", ) """Defaults for renewer script.""" ENHANCEMENTS = ["redirect", "ensure-http-header", "ocsp-stapling", "spdy"] """List of possible :class:`certbot.interfaces.IInstaller` enhancements. List of expected options parameters: - redirect: None - ensure-http-header: name of header (i.e. Strict-Transport-Security) - ocsp-stapling: certificate chain file path - spdy: TODO """ ARCHIVE_DIR = "archive" """Archive directory, relative to `IConfig.config_dir`.""" CONFIG_DIRS_MODE = 0o755 """Directory mode for ``.IConfig.config_dir`` et al.""" ACCOUNTS_DIR = "accounts" """Directory where all accounts are saved.""" LE_REUSE_SERVERS = { 'acme-v02.api.letsencrypt.org/directory': 'acme-v01.api.letsencrypt.org/directory', 'acme-staging-v02.api.letsencrypt.org/directory': 'acme-staging.api.letsencrypt.org/directory' } """Servers that can reuse accounts from other servers.""" BACKUP_DIR = "backups" """Directory (relative to `IConfig.work_dir`) where backups are kept.""" CSR_DIR = "csr" """See `.IConfig.csr_dir`.""" IN_PROGRESS_DIR = "IN_PROGRESS" """Directory used before a permanent checkpoint is finalized (relative to `IConfig.work_dir`).""" KEY_DIR = "keys" """Directory (relative to `IConfig.config_dir`) where keys are saved.""" LIVE_DIR = "live" """Live directory, relative to `IConfig.config_dir`.""" TEMP_CHECKPOINT_DIR = "temp_checkpoint" """Temporary checkpoint directory (relative to `IConfig.work_dir`).""" RENEWAL_CONFIGS_DIR = "renewal" """Renewal configs directory, relative to `IConfig.config_dir`.""" RENEWAL_HOOKS_DIR = "renewal-hooks" """Basename of directory containing hooks to run with the renew command.""" RENEWAL_PRE_HOOKS_DIR = "pre" """Basename of directory containing pre-hooks to run with the renew command.""" RENEWAL_DEPLOY_HOOKS_DIR = "deploy" """Basename of directory containing deploy-hooks to run with the renew command.""" RENEWAL_POST_HOOKS_DIR = "post" """Basename of directory containing post-hooks to run with the renew command.""" FORCE_INTERACTIVE_FLAG = "--force-interactive" """Flag to disable TTY checking in IDisplay.""" EFF_SUBSCRIBE_URI = "https://supporters.eff.org/subscribe/certbot" """EFF URI used to submit the e-mail address of users who opt-in.""" SSL_DHPARAMS_DEST = "ssl-dhparams.pem" """Name of the ssl_dhparams file as saved in `IConfig.config_dir`.""" SSL_DHPARAMS_SRC = pkg_resources.resource_filename( "certbot", "ssl-dhparams.pem") """Path to the nginx ssl_dhparams file found in the Certbot distribution.""" UPDATED_SSL_DHPARAMS_DIGEST = ".updated-ssl-dhparams-pem-digest.txt" """Name of the hash of the updated or informed ssl_dhparams as saved in `IConfig.config_dir`.""" ALL_SSL_DHPARAMS_HASHES = [ '9ba6429597aeed2d8617a7705b56e96d044f64b07971659382e426675105654b', ] """SHA256 hashes of the contents of all versions of SSL_DHPARAMS_SRC""" certbot-0.27.0/certbot/achallenges.py0000644000175000017500000000313013344054434017715 0ustar ericaerica00000000000000"""Client annotated ACME challenges. Please use names such as ``achall`` to distinguish from variables "of type" :class:`acme.challenges.Challenge` (denoted by ``chall``) and :class:`.ChallengeBody` (denoted by ``challb``):: from acme import challenges from acme import messages from certbot import achallenges chall = challenges.DNS(token='foo') challb = messages.ChallengeBody(chall=chall) achall = achallenges.DNS(chall=challb, domain='example.com') Note, that all annotated challenges act as a proxy objects:: achall.token == challb.token """ import logging import josepy as jose from acme import challenges logger = logging.getLogger(__name__) # pylint: disable=too-few-public-methods class AnnotatedChallenge(jose.ImmutableMap): """Client annotated challenge. Wraps around server provided challenge and annotates with data useful for the client. :ivar challb: Wrapped `~.ChallengeBody`. """ __slots__ = ('challb',) acme_type = NotImplemented def __getattr__(self, name): return getattr(self.challb, name) class KeyAuthorizationAnnotatedChallenge(AnnotatedChallenge): """Client annotated `KeyAuthorizationChallenge` challenge.""" __slots__ = ('challb', 'domain', 'account_key') def response_and_validation(self, *args, **kwargs): """Generate response and validation.""" return self.challb.chall.response_and_validation( self.account_key, *args, **kwargs) class DNS(AnnotatedChallenge): """Client annotated "dns" ACME challenge.""" __slots__ = ('challb', 'domain') acme_type = challenges.DNS certbot-0.27.0/MANIFEST.in0000644000175000017500000000035613344054434015200 0ustar ericaerica00000000000000include README.rst include CHANGES.rst include CONTRIBUTING.md include LICENSE.txt include linter_plugin.py recursive-include docs * recursive-include examples * recursive-include certbot/tests/testdata * include certbot/ssl-dhparams.pem certbot-0.27.0/docs/0002755000175000017500000000000013344054435014371 5ustar ericaerica00000000000000certbot-0.27.0/docs/cli-help.txt0000644000175000017500000011377513344054434016642 0ustar ericaerica00000000000000usage: certbot [SUBCOMMAND] [options] [-d DOMAIN] [-d DOMAIN] ... Certbot can obtain and install HTTPS/TLS/SSL certificates. By default, it will attempt to use a webserver both for obtaining and installing the certificate. The most common SUBCOMMANDS and flags are: obtain, install, and renew certificates: (default) run Obtain & install a certificate in your current webserver certonly Obtain or renew a certificate, but do not install it renew Renew all previously obtained certificates that are near expiry enhance Add security enhancements to your existing configuration -d DOMAINS Comma-separated list of domains to obtain a certificate for --apache Use the Apache plugin for authentication & installation --standalone Run a standalone webserver for authentication --nginx Use the Nginx plugin for authentication & installation --webroot Place files in a server's webroot folder for authentication --manual Obtain certificates interactively, or using shell script hooks -n Run non-interactively --test-cert Obtain a test certificate from a staging server --dry-run Test "renew" or "certonly" without saving any certificates to disk manage certificates: certificates Display information about certificates you have from Certbot revoke Revoke a certificate (supply --cert-path) delete Delete a certificate manage your account with Let's Encrypt: register Create a Let's Encrypt ACME account --agree-tos Agree to the ACME server's Subscriber Agreement -m EMAIL Email address for important account notifications optional arguments: -h, --help show this help message and exit -c CONFIG_FILE, --config CONFIG_FILE path to config file (default: /etc/letsencrypt/cli.ini and ~/.config/letsencrypt/cli.ini) -v, --verbose This flag can be used multiple times to incrementally increase the verbosity of output, e.g. -vvv. (default: -2) --max-log-backups MAX_LOG_BACKUPS Specifies the maximum number of backup logs that should be kept by Certbot's built in log rotation. Setting this flag to 0 disables log rotation entirely, causing Certbot to always append to the same log file. (default: 1000) -n, --non-interactive, --noninteractive Run without ever asking for user input. This may require additional command line flags; the client will try to explain which ones are required if it finds one missing (default: False) --force-interactive Force Certbot to be interactive even if it detects it's not being run in a terminal. This flag cannot be used with the renew subcommand. (default: False) -d DOMAIN, --domains DOMAIN, --domain DOMAIN Domain names to apply. For multiple domains you can use multiple -d flags or enter a comma separated list of domains as a parameter. The first domain provided will be the subject CN of the certificate, and all domains will be Subject Alternative Names on the certificate. The first domain will also be used in some software user interfaces and as the file paths for the certificate and related material unless otherwise specified or you already have a certificate with the same name. In the case of a name collision it will append a number like 0001 to the file path name. (default: Ask) --cert-name CERTNAME Certificate name to apply. This name is used by Certbot for housekeeping and in file paths; it doesn't affect the content of the certificate itself. To see certificate names, run 'certbot certificates'. When creating a new certificate, specifies the new certificate's name. (default: the first provided domain or the name of an existing certificate on your system for the same domains) --dry-run Perform a test run of the client, obtaining test (invalid) certificates but not saving them to disk. This can currently only be used with the 'certonly' and 'renew' subcommands. Note: Although --dry-run tries to avoid making any persistent changes on a system, it is not completely side-effect free: if used with webserver authenticator plugins like apache and nginx, it makes and then reverts temporary config changes in order to obtain test certificates, and reloads webservers to deploy and then roll back those changes. It also calls --pre-hook and --post-hook commands if they are defined because they may be necessary to accurately simulate renewal. --deploy- hook commands are not called. (default: False) --debug-challenges After setting up challenges, wait for user input before submitting to CA (default: False) --preferred-challenges PREF_CHALLS A sorted, comma delimited list of the preferred challenge to use during authorization with the most preferred challenge listed first (Eg, "dns" or "tls- sni-01,http,dns"). Not all plugins support all challenges. See https://certbot.eff.org/docs/using.html#plugins for details. ACME Challenges are versioned, but if you pick "http" rather than "http-01", Certbot will select the latest version automatically. (default: []) --user-agent USER_AGENT Set a custom user agent string for the client. User agent strings allow the CA to collect high level statistics about success rates by OS, plugin and use case, and to know when to deprecate support for past Python versions and flags. If you wish to hide this information from the Let's Encrypt server, set this to "". (default: CertbotACMEClient/0.26.1 (certbot(-auto); OS_NAME OS_VERSION) Authenticator/XXX Installer/YYY (SUBCOMMAND; flags: FLAGS) Py/major.minor.patchlevel). The flags encoded in the user agent are: --duplicate, --force-renew, --allow- subset-of-names, -n, and whether any hooks are set. --user-agent-comment USER_AGENT_COMMENT Add a comment to the default user agent string. May be used when repackaging Certbot or calling it from another tool to allow additional statistical data to be collected. Ignored if --user-agent is set. (Example: Foo-Wrapper/1.0) (default: None) automation: Flags for automating execution & other tweaks --keep-until-expiring, --keep, --reinstall If the requested certificate matches an existing certificate, always keep the existing one until it is due for renewal (for the 'run' subcommand this means reinstall the existing certificate). (default: Ask) --expand If an existing certificate is a strict subset of the requested names, always expand and replace it with the additional names. (default: Ask) --version show program's version number and exit --force-renewal, --renew-by-default If a certificate already exists for the requested domains, renew it now, regardless of whether it is near expiry. (Often --keep-until-expiring is more appropriate). Also implies --expand. (default: False) --renew-with-new-domains If a certificate already exists for the requested certificate name but does not match the requested domains, renew it now, regardless of whether it is near expiry. (default: False) --reuse-key When renewing, use the same private key as the existing certificate. (default: False) --allow-subset-of-names When performing domain validation, do not consider it a failure if authorizations can not be obtained for a strict subset of the requested domains. This may be useful for allowing renewals for multiple domains to succeed even if some domains no longer point at this system. This option cannot be used with --csr. (default: False) --agree-tos Agree to the ACME Subscriber Agreement (default: Ask) --duplicate Allow making a certificate lineage that duplicates an existing one (both can be renewed in parallel) (default: False) --os-packages-only (certbot-auto only) install OS package dependencies and then stop (default: False) --no-self-upgrade (certbot-auto only) prevent the certbot-auto script from upgrading itself to newer released versions (default: Upgrade automatically) --no-bootstrap (certbot-auto only) prevent the certbot-auto script from installing OS-level dependencies (default: Prompt to install OS-wide dependencies, but exit if the user says 'No') -q, --quiet Silence all output except errors. Useful for automation via cron. Implies --non-interactive. (default: False) security: Security parameters & server settings --rsa-key-size N Size of the RSA key. (default: 2048) --must-staple Adds the OCSP Must Staple extension to the certificate. Autoconfigures OCSP Stapling for supported setups (Apache version >= 2.3.3 ). (default: False) --redirect Automatically redirect all HTTP traffic to HTTPS for the newly authenticated vhost. (default: Ask) --no-redirect Do not automatically redirect all HTTP traffic to HTTPS for the newly authenticated vhost. (default: Ask) --hsts Add the Strict-Transport-Security header to every HTTP response. Forcing browser to always use SSL for the domain. Defends against SSL Stripping. (default: None) --uir Add the "Content-Security-Policy: upgrade-insecure- requests" header to every HTTP response. Forcing the browser to use https:// for every http:// resource. (default: None) --staple-ocsp Enables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS. (default: None) --strict-permissions Require that all configuration files are owned by the current user; only needed if your config is somewhere unsafe like /tmp/ (default: False) --auto-hsts Gradually increasing max-age value for HTTP Strict Transport Security security header (default: False) testing: The following flags are meant for testing and integration purposes only. --test-cert, --staging Use the staging server to obtain or revoke test (invalid) certificates; equivalent to --server https ://acme-staging-v02.api.letsencrypt.org/directory (default: False) --debug Show tracebacks in case of errors, and allow certbot- auto execution on experimental platforms (default: False) --no-verify-ssl Disable verification of the ACME server's certificate. (default: False) --tls-sni-01-port TLS_SNI_01_PORT Port used during tls-sni-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 443. (default: 443) --tls-sni-01-address TLS_SNI_01_ADDRESS The address the server listens to during tls-sni-01 challenge. (default: ) --http-01-port HTTP01_PORT Port used in the http-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 80. (default: 80) --http-01-address HTTP01_ADDRESS The address the server listens to during http-01 challenge. (default: ) --break-my-certs Be willing to replace or renew valid certificates with invalid (testing/staging) certificates (default: False) paths: Flags for changing execution paths & servers --cert-path CERT_PATH Path to where certificate is saved (with auth --csr), installed from, or revoked. (default: None) --key-path KEY_PATH Path to private key for certificate installation or revocation (if account key is missing) (default: None) --fullchain-path FULLCHAIN_PATH Accompanying path to a full certificate chain (certificate plus chain). (default: None) --chain-path CHAIN_PATH Accompanying path to a certificate chain. (default: None) --config-dir CONFIG_DIR Configuration directory. (default: /etc/letsencrypt) --work-dir WORK_DIR Working directory. (default: /var/lib/letsencrypt) --logs-dir LOGS_DIR Logs directory. (default: /var/log/letsencrypt) --server SERVER ACME Directory Resource URI. (default: https://acme-v02.api.letsencrypt.org/directory) manage: Various subcommands and flags are available for managing your certificates: certificates List certificates managed by Certbot delete Clean up all files related to a certificate renew Renew all certificates (or one specified with --cert- name) revoke Revoke a certificate specified with --cert-path update_symlinks Recreate symlinks in your /etc/letsencrypt/live/ directory run: Options for obtaining & installing certificates certonly: Options for modifying how a certificate is obtained --csr CSR Path to a Certificate Signing Request (CSR) in DER or PEM format. Currently --csr only works with the 'certonly' subcommand. (default: None) renew: The 'renew' subcommand will attempt to renew all certificates (or more precisely, certificate lineages) you have previously obtained if they are close to expiry, and print a summary of the results. By default, 'renew' will reuse the options used to create obtain or most recently successfully renew each certificate lineage. You can try it with `--dry-run` first. For more fine-grained control, you can renew individual lineages with the `certonly` subcommand. Hooks are available to run commands before and after renewal; see https://certbot.eff.org/docs/using.html#renewal for more information on these. --pre-hook PRE_HOOK Command to be run in a shell before obtaining any certificates. Intended primarily for renewal, where it can be used to temporarily shut down a webserver that might conflict with the standalone plugin. This will only be called if a certificate is actually to be obtained/renewed. When renewing several certificates that have identical pre-hooks, only the first will be executed. (default: None) --post-hook POST_HOOK Command to be run in a shell after attempting to obtain/renew certificates. Can be used to deploy renewed certificates, or to restart any servers that were stopped by --pre-hook. This is only run if an attempt was made to obtain/renew a certificate. If multiple renewed certificates have identical post- hooks, only one will be run. (default: None) --deploy-hook DEPLOY_HOOK Command to be run in a shell once for each successfully issued certificate. For this command, the shell variable $RENEWED_LINEAGE will point to the config live subdirectory (for example, "/etc/letsencrypt/live/example.com") containing the new certificates and keys; the shell variable $RENEWED_DOMAINS will contain a space-delimited list of renewed certificate domains (for example, "example.com www.example.com" (default: None) --disable-hook-validation Ordinarily the commands specified for --pre-hook /--post-hook/--deploy-hook will be checked for validity, to see if the programs being run are in the $PATH, so that mistakes can be caught early, even when the hooks aren't being run just yet. The validation is rather simplistic and fails if you use more advanced shell constructs, so you can use this switch to disable it. (default: False) --no-directory-hooks Disable running executables found in Certbot's hook directories during renewal. (default: False) --disable-renew-updates Disable automatic updates to your server configuration that would otherwise be done by the selected installer plugin, and triggered when the user executes "certbot renew", regardless of if the certificate is renewed. This setting does not apply to important TLS configuration updates. (default: False) --no-autorenew Disable auto renewal of certificates. (default: True) certificates: List certificates managed by Certbot delete: Options for deleting a certificate revoke: Options for revocation of certificates --reason {unspecified,keycompromise,affiliationchanged,superseded,cessationofoperation} Specify reason for revoking certificate. (default: unspecified) --delete-after-revoke Delete certificates after revoking them. (default: None) --no-delete-after-revoke Do not delete certificates after revoking them. This option should be used with caution because the 'renew' subcommand will attempt to renew undeleted revoked certificates. (default: None) register: Options for account registration & modification --register-unsafely-without-email Specifying this flag enables registering an account with no email address. This is strongly discouraged, because in the event of key loss or account compromise you will irrevocably lose access to your account. You will also be unable to receive notice about impending expiration or revocation of your certificates. Updates to the Subscriber Agreement will still affect you, and will be effective 14 days after posting an update to the web site. (default: False) --update-registration With the register verb, indicates that details associated with an existing registration, such as the e-mail address, should be updated, rather than registering a new account. (default: False) -m EMAIL, --email EMAIL Email used for registration and recovery contact. Use comma to register multiple emails, ex: u1@example.com,u2@example.com. (default: Ask). --eff-email Share your e-mail address with EFF (default: None) --no-eff-email Don't share your e-mail address with EFF (default: None) unregister: Options for account deactivation. --account ACCOUNT_ID Account ID to use (default: None) install: Options for modifying how a certificate is deployed config_changes: Options for controlling which changes are displayed --num NUM How many past revisions you want to be displayed (default: None) rollback: Options for rolling back server configuration changes --checkpoints N Revert configuration N number of checkpoints. (default: 1) plugins: Options for for the "plugins" subcommand --init Initialize plugins. (default: False) --prepare Initialize and prepare plugins. (default: False) --authenticators Limit to authenticator plugins only. (default: None) --installers Limit to installer plugins only. (default: None) update_symlinks: Recreates certificate and key symlinks in /etc/letsencrypt/live, if you changed them by hand or edited a renewal configuration file enhance: Helps to harden the TLS configuration by adding security enhancements to already existing configuration. plugins: Plugin Selection: Certbot client supports an extensible plugins architecture. See 'certbot plugins' for a list of all installed plugins and their names. You can force a particular plugin by setting options provided below. Running --help will list flags specific to that plugin. --configurator CONFIGURATOR Name of the plugin that is both an authenticator and an installer. Should not be used together with --authenticator or --installer. (default: Ask) -a AUTHENTICATOR, --authenticator AUTHENTICATOR Authenticator plugin name. (default: None) -i INSTALLER, --installer INSTALLER Installer plugin name (also used to find domains). (default: None) --apache Obtain and install certificates using Apache (default: False) --nginx Obtain and install certificates using Nginx (default: False) --standalone Obtain certificates using a "standalone" webserver. (default: False) --manual Provide laborious manual instructions for obtaining a certificate (default: False) --webroot Obtain certificates by placing files in a webroot directory. (default: False) --dns-cloudflare Obtain certificates using a DNS TXT record (if you are using Cloudflare for DNS). (default: False) --dns-cloudxns Obtain certificates using a DNS TXT record (if you are using CloudXNS for DNS). (default: False) --dns-digitalocean Obtain certificates using a DNS TXT record (if you are using DigitalOcean for DNS). (default: False) --dns-dnsimple Obtain certificates using a DNS TXT record (if you are using DNSimple for DNS). (default: False) --dns-dnsmadeeasy Obtain certificates using a DNS TXT record (if you areusing DNS Made Easy for DNS). (default: False) --dns-gehirn Obtain certificates using a DNS TXT record (if you are using Gehirn Infrastracture Service for DNS). (default: False) --dns-google Obtain certificates using a DNS TXT record (if you are using Google Cloud DNS). (default: False) --dns-linode Obtain certificates using a DNS TXT record (if you are using Linode for DNS). (default: False) --dns-luadns Obtain certificates using a DNS TXT record (if you are using LuaDNS for DNS). (default: False) --dns-nsone Obtain certificates using a DNS TXT record (if you are using NS1 for DNS). (default: False) --dns-ovh Obtain certificates using a DNS TXT record (if you are using OVH for DNS). (default: False) --dns-rfc2136 Obtain certificates using a DNS TXT record (if you are using BIND for DNS). (default: False) --dns-route53 Obtain certificates using a DNS TXT record (if you are using Route53 for DNS). (default: False) --dns-sakuracloud Obtain certificates using a DNS TXT record (if you are using Sakura Cloud for DNS). (default: False) apache: Apache Web Server plugin - Beta --apache-enmod APACHE_ENMOD Path to the Apache 'a2enmod' binary. (default: a2enmod) --apache-dismod APACHE_DISMOD Path to the Apache 'a2dismod' binary. (default: a2dismod) --apache-le-vhost-ext APACHE_LE_VHOST_EXT SSL vhost configuration extension. (default: -le- ssl.conf) --apache-server-root APACHE_SERVER_ROOT Apache server root directory. (default: /etc/apache2) --apache-vhost-root APACHE_VHOST_ROOT Apache server VirtualHost configuration root (default: None) --apache-logs-root APACHE_LOGS_ROOT Apache server logs directory (default: /var/log/apache2) --apache-challenge-location APACHE_CHALLENGE_LOCATION Directory path for challenge configuration. (default: /etc/apache2) --apache-handle-modules APACHE_HANDLE_MODULES Let installer handle enabling required modules for you. (Only Ubuntu/Debian currently) (default: True) --apache-handle-sites APACHE_HANDLE_SITES Let installer handle enabling sites for you. (Only Ubuntu/Debian currently) (default: True) certbot-route53:auth: Obtain certificates using a DNS TXT record (if you are using AWS Route53 for DNS). --certbot-route53:auth-propagation-seconds CERTBOT_ROUTE53:AUTH_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 10) dns-cloudflare: Obtain certificates using a DNS TXT record (if you are using Cloudflare for DNS). --dns-cloudflare-propagation-seconds DNS_CLOUDFLARE_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 10) --dns-cloudflare-credentials DNS_CLOUDFLARE_CREDENTIALS Cloudflare credentials INI file. (default: None) dns-cloudxns: Obtain certificates using a DNS TXT record (if you are using CloudXNS for DNS). --dns-cloudxns-propagation-seconds DNS_CLOUDXNS_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 30) --dns-cloudxns-credentials DNS_CLOUDXNS_CREDENTIALS CloudXNS credentials INI file. (default: None) dns-digitalocean: Obtain certs using a DNS TXT record (if you are using DigitalOcean for DNS). --dns-digitalocean-propagation-seconds DNS_DIGITALOCEAN_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 10) --dns-digitalocean-credentials DNS_DIGITALOCEAN_CREDENTIALS DigitalOcean credentials INI file. (default: None) dns-dnsimple: Obtain certificates using a DNS TXT record (if you are using DNSimple for DNS). --dns-dnsimple-propagation-seconds DNS_DNSIMPLE_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 30) --dns-dnsimple-credentials DNS_DNSIMPLE_CREDENTIALS DNSimple credentials INI file. (default: None) dns-dnsmadeeasy: Obtain certificates using a DNS TXT record (if you are using DNS Made Easy for DNS). --dns-dnsmadeeasy-propagation-seconds DNS_DNSMADEEASY_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 60) --dns-dnsmadeeasy-credentials DNS_DNSMADEEASY_CREDENTIALS DNS Made Easy credentials INI file. (default: None) dns-gehirn: Obtain certificates using a DNS TXT record (if you are using Gehirn Infrastracture Service for DNS). --dns-gehirn-propagation-seconds DNS_GEHIRN_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 30) --dns-gehirn-credentials DNS_GEHIRN_CREDENTIALS Gehirn Infrastracture Service credentials file. (default: None) dns-google: Obtain certificates using a DNS TXT record (if you are using Google Cloud DNS for DNS). --dns-google-propagation-seconds DNS_GOOGLE_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 60) --dns-google-credentials DNS_GOOGLE_CREDENTIALS Path to Google Cloud DNS service account JSON file. (See https://developers.google.com/identity/protocols/ OAuth2ServiceAccount#creatinganaccount forinformation about creating a service account and https://cloud.google.com/dns/access- control#permissions_and_roles for information about therequired permissions.) (default: None) dns-linode: Obtain certs using a DNS TXT record (if you are using Linode for DNS). --dns-linode-propagation-seconds DNS_LINODE_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 960) --dns-linode-credentials DNS_LINODE_CREDENTIALS Linode credentials INI file. (default: None) dns-luadns: Obtain certificates using a DNS TXT record (if you are using LuaDNS for DNS). --dns-luadns-propagation-seconds DNS_LUADNS_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 30) --dns-luadns-credentials DNS_LUADNS_CREDENTIALS LuaDNS credentials INI file. (default: None) dns-nsone: Obtain certificates using a DNS TXT record (if you are using NS1 for DNS). --dns-nsone-propagation-seconds DNS_NSONE_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 30) --dns-nsone-credentials DNS_NSONE_CREDENTIALS NS1 credentials file. (default: None) dns-ovh: Obtain certificates using a DNS TXT record (if you are using OVH for DNS). --dns-ovh-propagation-seconds DNS_OVH_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 30) --dns-ovh-credentials DNS_OVH_CREDENTIALS OVH credentials INI file. (default: None) dns-rfc2136: Obtain certificates using a DNS TXT record (if you are using BIND for DNS). --dns-rfc2136-propagation-seconds DNS_RFC2136_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 60) --dns-rfc2136-credentials DNS_RFC2136_CREDENTIALS RFC 2136 credentials INI file. (default: None) dns-route53: Obtain certificates using a DNS TXT record (if you are using AWS Route53 for DNS). --dns-route53-propagation-seconds DNS_ROUTE53_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 10) dns-sakuracloud: Obtain certificates using a DNS TXT record (if you are using Sakura Cloud for DNS). --dns-sakuracloud-propagation-seconds DNS_SAKURACLOUD_PROPAGATION_SECONDS The number of seconds to wait for DNS to propagate before asking the ACME server to verify the DNS record. (default: 90) --dns-sakuracloud-credentials DNS_SAKURACLOUD_CREDENTIALS Sakura Cloud credentials file. (default: None) manual: Authenticate through manual configuration or custom shell scripts. When using shell scripts, an authenticator script must be provided. The environment variables available to this script depend on the type of challenge. $CERTBOT_DOMAIN will always contain the domain being authenticated. For HTTP-01 and DNS-01, $CERTBOT_VALIDATION is the validation string, and $CERTBOT_TOKEN is the filename of the resource requested when performing an HTTP-01 challenge. When performing a TLS- SNI-01 challenge, $CERTBOT_SNI_DOMAIN will contain the SNI name for which the ACME server expects to be presented with the self-signed certificate located at $CERTBOT_CERT_PATH. The secret key needed to complete the TLS handshake is located at $CERTBOT_KEY_PATH. An additional cleanup script can also be provided and can use the additional variable $CERTBOT_AUTH_OUTPUT which contains the stdout output from the auth script. --manual-auth-hook MANUAL_AUTH_HOOK Path or command to execute for the authentication script (default: None) --manual-cleanup-hook MANUAL_CLEANUP_HOOK Path or command to execute for the cleanup script (default: None) --manual-public-ip-logging-ok Automatically allows public IP logging (default: Ask) nginx: Nginx Web Server plugin --nginx-server-root NGINX_SERVER_ROOT Nginx server root directory. (default: /etc/nginx or /usr/local/etc/nginx) --nginx-ctl NGINX_CTL Path to the 'nginx' binary, used for 'configtest' and retrieving nginx version number. (default: nginx) null: Null Installer standalone: Spin up a temporary webserver webroot: Place files in webroot directory --webroot-path WEBROOT_PATH, -w WEBROOT_PATH public_html / webroot path. This can be specified multiple times to handle different domains; each domain will have the webroot path that preceded it. For instance: `-w /var/www/example -d example.com -d www.example.com -w /var/www/thing -d thing.net -d m.thing.net` (default: Ask) --webroot-map WEBROOT_MAP JSON dictionary mapping domains to webroot paths; this implies -d for each entry. You may need to escape this from your shell. E.g.: --webroot-map '{"eg1.is,m.eg1.is":"/www/eg1/", "eg2.is":"/www/eg2"}' This option is merged with, but takes precedence over, -w / -d entries. At present, if you put webroot-map in a config file, it needs to be on a single line, like: webroot-map = {"example.com":"/var/www"}. (default: {}) certbot-0.27.0/docs/resources.rst0000644000175000017500000000022313344054434017127 0ustar ericaerica00000000000000===================== Resources ===================== .. include:: ../README.rst :start-after: tag:links-begin :end-before: tag:links-end certbot-0.27.0/docs/api.rst0000644000175000017500000000013113344054434015664 0ustar ericaerica00000000000000================= API Documentation ================= .. toctree:: :glob: api/** certbot-0.27.0/docs/intro.rst0000644000175000017500000000040213344054434016247 0ustar ericaerica00000000000000===================== Introduction ===================== .. note:: To get started quickly, use the `interactive installation guide `_. .. include:: ../README.rst :start-after: tag:intro-begin :end-before: tag:intro-end certbot-0.27.0/docs/man/0002755000175000017500000000000013344054435015144 5ustar ericaerica00000000000000certbot-0.27.0/docs/man/certbot.rst0000644000175000017500000000004413344054434017333 0ustar ericaerica00000000000000.. literalinclude:: ../cli-help.txt certbot-0.27.0/docs/_templates/0002755000175000017500000000000013344054435016526 5ustar ericaerica00000000000000certbot-0.27.0/docs/_templates/footer.html0000644000175000017500000000371713344054434020717 0ustar ericaerica00000000000000
{% if (theme_prev_next_buttons_location == 'bottom' or theme_prev_next_buttons_location == 'both') and (next or prev) %} {% endif %}

© Copyright 2014-2018 - The Certbot software and documentation are licensed under the Apache 2.0 license as described at https://eff.org/cb-license.

Let's Encrypt Status {%- if build_id and build_url %} {% trans build_url=build_url, build_id=build_id %} Build {{ build_id }}. {% endtrans %} {%- elif commit %} {% trans commit=commit %} Revision {{ commit }}. {% endtrans %} {%- elif last_updated %} {% trans last_updated=last_updated|e %}Last updated on {{ last_updated }}.{% endtrans %} {%- endif %}

{%- if show_sphinx %} {% trans %}Built with Sphinx using a theme provided by Read the Docs{% endtrans %}. {%- endif %} {%- block extrafooter %} {% endblock %}
certbot-0.27.0/docs/contributing.rst0000644000175000017500000004320113344054434017627 0ustar ericaerica00000000000000=============== Developer Guide =============== .. contents:: Table of Contents :local: .. _getting_started: Getting Started =============== Certbot has the same :ref:`system requirements ` when set up for development. While the section below will help you install Certbot and its dependencies, Certbot needs to be run on a UNIX-like OS so if you're using Windows, you'll need to set up a (virtual) machine running an OS such as Linux and continue with these instructions on that UNIX-like OS. Running a local copy of the client ---------------------------------- Running the client in developer mode from your local tree is a little different than running Certbot as a user. To get set up, clone our git repository by running: .. code-block:: shell git clone https://github.com/certbot/certbot If you're on macOS, we recommend you skip the rest of this section and instead run Certbot in Docker. You can find instructions for how to do this :ref:`here `. If you're running on Linux, you can run the following commands to install dependencies and set up a virtual environment where you can run Certbot. .. code-block:: shell cd certbot ./certbot-auto --debug --os-packages-only tools/venv.sh If you have Python3 available and want to use it, run the ``venv3.sh`` script. .. code-block:: shell tools/venv3.sh .. note:: You may need to repeat this when Certbot's dependencies change or when a new plugin is introduced. You can now run the copy of Certbot from git either by executing ``venv/bin/certbot``, or by activating the virtual environment. You can do the latter by running: .. code-block:: shell source venv/bin/activate # or source venv3/bin/activate After running this command, ``certbot`` and development tools like ``ipdb``, ``ipython``, ``pytest``, and ``tox`` are available in the shell where you ran the command. These tools are installed in the virtual environment and are kept separate from your global Python installation. This works by setting environment variables so the right executables are found and Python can pull in the versions of various packages needed by Certbot. More information can be found in the `virtualenv docs`_. .. _`virtualenv docs`: https://virtualenv.pypa.io Find issues to work on ---------------------- You can find the open issues in the `github issue tracker`_. Comparatively easy ones are marked `good first issue`_. If you're starting work on something, post a comment to let others know and seek feedback on your plan where appropriate. Once you've got a working branch, you can open a pull request. All changes in your pull request must have thorough unit test coverage, pass our tests, and be compliant with the :ref:`coding style `. .. _github issue tracker: https://github.com/certbot/certbot/issues .. _good first issue: https://github.com/certbot/certbot/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22 .. _testing: Testing ------- When you are working in a file ``foo.py``, there should also be a file ``foo_test.py`` either in the same directory as ``foo.py`` or in the ``tests`` subdirectory (if there isn't, make one). While you are working on your code and tests, run ``python foo_test.py`` to run the relevant tests. For debugging, we recommend putting ``import ipdb; ipdb.set_trace()`` statements inside the source code. Once you are done with your code changes, and the tests in ``foo_test.py`` pass, run all of the unittests for Certbot with ``tox -e py27`` (this uses Python 2.7). Once all the unittests pass, check for sufficient test coverage using ``tox -e cover``, and then check for code style with ``tox -e lint`` (all files) or ``pylint --rcfile=.pylintrc path/to/file.py`` (single file at a time). Once all of the above is successful, you may run the full test suite using ``tox --skip-missing-interpreters``. We recommend running the commands above first, because running all tests like this is very slow, and the large amount of output can make it hard to find specific failures when they happen. .. warning:: The full test suite may attempt to modify your system's Apache config if your user has sudo permissions, so it should not be run on a production Apache server. .. _integration: Integration testing with the Boulder CA ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Generally it is sufficient to open a pull request and let Github and Travis run integration tests for you, however, if you want to run them locally you need Docker and docker-compose installed and working. Fetch and start Boulder, Let's Encrypt's ACME CA software, by using: .. code-block:: shell ./tests/boulder-fetch.sh If you have problems with Docker, you may want to try `removing all containers and volumes`_ and making sure you have at least 1GB of memory. Set up a certbot_test alias that enables easily running against the local Boulder: .. code-block:: shell export SERVER=http://localhost:4000/directory source tests/integration/_common.sh Run the integration tests using: .. code-block:: shell ./tests/boulder-integration.sh .. _removing all containers and volumes: https://www.digitalocean.com/community/tutorials/how-to-remove-docker-images-containers-and-volumes Code components and layout ========================== acme contains all protocol specific code certbot main client code certbot-apache and certbot-nginx client code to configure specific web servers certbot.egg-info configuration for packaging Certbot Plugin-architecture ------------------- Certbot has a plugin architecture to facilitate support for different webservers, other TLS servers, and operating systems. The interfaces available for plugins to implement are defined in `interfaces.py`_ and `plugins/common.py`_. The main two plugin interfaces are `~certbot.interfaces.IAuthenticator`, which implements various ways of proving domain control to a certificate authority, and `~certbot.interfaces.IInstaller`, which configures a server to use a certificate once it is issued. Some plugins, like the built-in Apache and Nginx plugins, implement both interfaces and perform both tasks. Others, like the built-in Standalone authenticator, implement just one interface. There are also `~certbot.interfaces.IDisplay` plugins, which can change how prompts are displayed to a user. .. _interfaces.py: https://github.com/certbot/certbot/blob/master/certbot/interfaces.py .. _plugins/common.py: https://github.com/certbot/certbot/blob/master/certbot/plugins/common.py#L34 Authenticators -------------- Authenticators are plugins that prove control of a domain name by solving a challenge provided by the ACME server. ACME currently defines three types of challenges: HTTP, TLS-SNI, and DNS, represented by classes in `acme.challenges`. An authenticator plugin should implement support for at least one challenge type. An Authenticator indicates which challenges it supports by implementing `get_chall_pref(domain)` to return a sorted list of challenge types in preference order. An Authenticator must also implement `perform(achalls)`, which "performs" a list of challenges by, for instance, provisioning a file on an HTTP server, or setting a TXT record in DNS. Once all challenges have succeeded or failed, Certbot will call the plugin's `cleanup(achalls)` method to remove any files or DNS records that were needed only during authentication. Installer --------- Installers plugins exist to actually setup the certificate in a server, possibly tweak the security configuration to make it more correct and secure (Fix some mixed content problems, turn on HSTS, redirect to HTTPS, etc). Installer plugins tell the main client about their abilities to do the latter via the :meth:`~.IInstaller.supported_enhancements` call. We currently have two Installers in the tree, the `~.ApacheConfigurator`. and the `~.NginxConfigurator`. External projects have made some progress toward support for IIS, Icecast and Plesk. Installers and Authenticators will oftentimes be the same class/object (because for instance both tasks can be performed by a webserver like nginx) though this is not always the case (the standalone plugin is an authenticator that listens on port 443, but it cannot install certs; a postfix plugin would be an installer but not an authenticator). Installers and Authenticators are kept separate because it should be possible to use the `~.StandaloneAuthenticator` (it sets up its own Python server to perform challenges) with a program that cannot solve challenges itself (Such as MTA installers). Installer Development --------------------- There are a few existing classes that may be beneficial while developing a new `~certbot.interfaces.IInstaller`. Installers aimed to reconfigure UNIX servers may use Augeas for configuration parsing and can inherit from `~.AugeasConfigurator` class to handle much of the interface. Installers that are unable to use Augeas may still find the `~.Reverter` class helpful in handling configuration checkpoints and rollback. .. _dev-plugin: Writing your own plugin ~~~~~~~~~~~~~~~~~~~~~~~ Certbot client supports dynamic discovery of plugins through the `setuptools entry points`_ using the `certbot.plugins` group. This way you can, for example, create a custom implementation of `~certbot.interfaces.IAuthenticator` or the `~certbot.interfaces.IInstaller` without having to merge it with the core upstream source code. An example is provided in ``examples/plugins/`` directory. While developing, you can install your plugin into a Certbot development virtualenv like this: .. code-block:: shell . venv/bin/activate . tests/integration/_common.sh pip install -e examples/plugins/ certbot_test plugins Your plugin should show up in the output of the last command. If not, it was not installed properly. Once you've finished your plugin and published it, you can have your users install it system-wide with `pip install`. Note that this will only work for users who have Certbot installed from OS packages or via pip. Users who run `certbot-auto` are currently unable to use third-party plugins. It's technically possible to install third-party plugins into the virtualenv used by `certbot-auto`, but they will be wiped away when `certbot-auto` upgrades. .. warning:: Please be aware though that as this client is still in a developer-preview stage, the API may undergo a few changes. If you believe the plugin will be beneficial to the community, please consider submitting a pull request to the repo and we will update it with any necessary API changes. .. _`setuptools entry points`: http://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points .. _coding-style: Coding style ============ Please: 1. **Be consistent with the rest of the code**. 2. Read `PEP 8 - Style Guide for Python Code`_. 3. Follow the `Google Python Style Guide`_, with the exception that we use `Sphinx-style`_ documentation:: def foo(arg): """Short description. :param int arg: Some number. :returns: Argument :rtype: int """ return arg 4. Remember to use ``pylint``. .. _Google Python Style Guide: https://google.github.io/styleguide/pyguide.html .. _Sphinx-style: http://sphinx-doc.org/ .. _PEP 8 - Style Guide for Python Code: https://www.python.org/dev/peps/pep-0008 Mypy type annotations ===================== Certbot uses the `mypy`_ static type checker. Python 3 natively supports official type annotations, which can then be tested for consistency using mypy. Python 2 doesn’t, but type annotations can be `added in comments`_. Mypy does some type checks even without type annotations; we can find bugs in Certbot even without a fully annotated codebase. Certbot supports both Python 2 and 3, so we’re using Python 2-style annotations. Zulip wrote a `great guide`_ to using mypy. It’s useful, but you don’t have to read the whole thing to start contributing to Certbot. To run mypy on Certbot, use ``tox -e mypy`` on a machine that has Python 3 installed. Note that instead of just importing ``typing``, due to packaging issues, in Certbot we import from ``acme.magic_typing`` and have to add some comments for pylint like this: .. code-block:: python from acme.magic_typing import Dict # pylint: disable=unused-import, no-name-in-module Also note that OpenSSL, which we rely on, has type definitions for crypto but not SSL. We use both. Those imports should look like this: .. code-block:: python from OpenSSL import crypto from OpenSSL import SSL # type: ignore # https://github.com/python/typeshed/issues/2052 .. _mypy: https://mypy.readthedocs.io .. _added in comments: https://mypy.readthedocs.io/en/latest/cheat_sheet.html .. _great guide: https://blog.zulip.org/2016/10/13/static-types-in-python-oh-mypy/ Submitting a pull request ========================= Steps: 1. Write your code! 2. Make sure your environment is set up properly and that you're in your virtualenv. You can do this by running ``./tools/venv.sh``. (this is a **very important** step) 3. Run ``tox -e lint`` to check for pylint errors. Fix any errors. 4. Run ``tox --skip-missing-interpreters`` to run the entire test suite including coverage. The ``--skip-missing-interpreters`` argument ignores missing versions of Python needed for running the tests. Fix any errors. 5. Submit the PR. 6. Did your tests pass on Travis? If they didn't, fix any errors. Asking for help =============== If you have any questions while working on a Certbot issue, don't hesitate to ask for help! You can do this in the #letsencrypt-dev IRC channel on Freenode. If you don't already have an IRC client set up, we recommend you join using `Riot `_. Updating certbot-auto and letsencrypt-auto ========================================== Updating the scripts -------------------- Developers should *not* modify the ``certbot-auto`` and ``letsencrypt-auto`` files in the root directory of the repository. Rather, modify the ``letsencrypt-auto.template`` and associated platform-specific shell scripts in the ``letsencrypt-auto-source`` and ``letsencrypt-auto-source/pieces/bootstrappers`` directory, respectively. Building letsencrypt-auto-source/letsencrypt-auto ------------------------------------------------- Once changes to any of the aforementioned files have been made, the ``letsencrypt-auto-source/letsencrypt-auto`` script should be updated. In lieu of manually updating this script, run the build script, which lives at ``letsencrypt-auto-source/build.py``: .. code-block:: shell python letsencrypt-auto-source/build.py Running ``build.py`` will update the ``letsencrypt-auto-source/letsencrypt-auto`` script. Note that the ``certbot-auto`` and ``letsencrypt-auto`` scripts in the root directory of the repository will remain **unchanged** after this script is run. Your changes will be propagated to these files during the next release of Certbot. Opening a PR ------------ When opening a PR, ensure that the following files are committed: 1. ``letsencrypt-auto-source/letsencrypt-auto.template`` and ``letsencrypt-auto-source/pieces/bootstrappers/*`` 2. ``letsencrypt-auto-source/letsencrypt-auto`` (generated by ``build.py``) It might also be a good idea to double check that **no** changes were inadvertently made to the ``certbot-auto`` or ``letsencrypt-auto`` scripts in the root of the repository. These scripts will be updated by the core developers during the next release. Updating the documentation ========================== In order to generate the Sphinx documentation, run the following commands: .. code-block:: shell make -C docs clean html man This should generate documentation in the ``docs/_build/html`` directory. .. note:: If you skipped the "Getting Started" instructions above, run ``pip install -e ".[docs]"`` to install Certbot's docs extras modules. .. _docker-dev: Running the client with Docker ============================== You can use Docker Compose to quickly set up an environment for running and testing Certbot. To install Docker Compose, follow the instructions at https://docs.docker.com/compose/install/. .. note:: Linux users can simply run ``pip install docker-compose`` to get Docker Compose after installing Docker Engine and activating your shell as described in the :ref:`Getting Started ` section. Now you can develop on your host machine, but run Certbot and test your changes in Docker. When using ``docker-compose`` make sure you are inside your clone of the Certbot repository. As an example, you can run the following command to check for linting errors:: docker-compose run --rm --service-ports development bash -c 'tox -e lint' You can also leave a terminal open running a shell in the Docker container and modify Certbot code in another window. The Certbot repo on your host machine is mounted inside of the container so any changes you make immediately take effect. To do this, run:: docker-compose run --rm --service-ports development bash Now running the check for linting errors described above is as easy as:: tox -e lint .. _prerequisites: Notes on OS dependencies ======================== OS-level dependencies can be installed like so: .. code-block:: shell ./certbot-auto --debug --os-packages-only In general... * ``sudo`` is required as a suggested way of running privileged process * `Python`_ 2.7 or 3.4+ is required * `Augeas`_ is required for the Python bindings * ``virtualenv`` is used for managing other Python library dependencies .. _Python: https://wiki.python.org/moin/BeginnersGuide/Download .. _Augeas: http://augeas.net/ .. _Virtualenv: https://virtualenv.pypa.io FreeBSD ------- FreeBSD by default uses ``tcsh``. In order to activate virtualenv (see above), you will need a compatible shell, e.g. ``pkg install bash && bash``. certbot-0.27.0/docs/using.rst0000644000175000017500000013164613344054434016260 0ustar ericaerica00000000000000========== User Guide ========== .. contents:: Table of Contents :local: Certbot Commands ================ Certbot uses a number of different commands (also referred to as "subcommands") to request specific actions such as obtaining, renewing, or revoking certificates. The most important and commonly-used commands will be discussed throughout this document; an exhaustive list also appears near the end of the document. The ``certbot`` script on your web server might be named ``letsencrypt`` if your system uses an older package, or ``certbot-auto`` if you used an alternate installation method. Throughout the docs, whenever you see ``certbot``, swap in the correct name as needed. .. _plugins: Getting certificates (and choosing plugins) =========================================== The Certbot client supports two types of plugins for obtaining and installing certificates: authenticators and installers. Authenticators are plugins used with the ``certonly`` command to obtain a certificate. The authenticator validates that you control the domain(s) you are requesting a certificate for, obtains a certificate for the specified domain(s), and places the certificate in the ``/etc/letsencrypt`` directory on your machine. The authenticator does not install the certificate (it does not edit any of your server's configuration files to serve the obtained certificate). If you specify multiple domains to authenticate, they will all be listed in a single certificate. To obtain multiple separate certificates you will need to run Certbot multiple times. Installers are Plugins used with the ``install`` command to install a certificate. These plugins can modify your webserver's configuration to serve your website over HTTPS using certificates obtained by certbot. Plugins that do both can be used with the ``certbot run`` command, which is the default when no command is specified. The ``run`` subcommand can also be used to specify a combination_ of distinct authenticator and installer plugins. =========== ==== ==== =============================================================== ============================= Plugin Auth Inst Notes Challenge types (and port) =========== ==== ==== =============================================================== ============================= apache_ Y Y | Automates obtaining and installing a certificate with Apache tls-sni-01_ (443) | 2.4 on OSes with ``libaugeas0`` 1.0+. webroot_ Y N | Obtains a certificate by writing to the webroot directory of http-01_ (80) | an already running webserver. nginx_ Y Y | Automates obtaining and installing a certificate with Nginx. tls-sni-01_ (443) | Shipped with Certbot 0.9.0. standalone_ Y N | Uses a "standalone" webserver to obtain a certificate. http-01_ (80) or | Requires port 80 or 443 to be available. This is useful on tls-sni-01_ (443) | systems with no webserver, or when direct integration with | the local webserver is not supported or not desired. |dns_plugs| Y N | This category of plugins automates obtaining a certificate by dns-01_ (53) | modifying DNS records to prove you have control over a | domain. Doing domain validation in this way is | the only way to obtain wildcard certificates from Let's | Encrypt. manual_ Y N | Helps you obtain a certificate by giving you instructions to http-01_ (80), | perform domain validation yourself. Additionally allows you dns-01_ (53) or | to specify scripts to automate the validation task in a tls-sni-01_ (443) | customized way. =========== ==== ==== =============================================================== ============================= .. |dns_plugs| replace:: :ref:`DNS plugins ` Under the hood, plugins use one of several ACME protocol challenges_ to prove you control a domain. The options are http-01_ (which uses port 80), tls-sni-01_ (port 443) and dns-01_ (requiring configuration of a DNS server on port 53, though that's often not the same machine as your webserver). A few plugins support more than one challenge type, in which case you can choose one with ``--preferred-challenges``. There are also many third-party-plugins_ available. Below we describe in more detail the circumstances in which each plugin can be used, and how to use it. .. _challenges: https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-7 .. _tls-sni-01: https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-7.3 .. _http-01: https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-7.2 .. _dns-01: https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-7.4 Apache ------ The Apache plugin currently requires an OS with augeas version 1.0; currently `it supports `_ modern OSes based on Debian, Fedora, SUSE, Gentoo and Darwin. This automates both obtaining *and* installing certificates on an Apache webserver. To specify this plugin on the command line, simply include ``--apache``. Webroot ------- If you're running a local webserver for which you have the ability to modify the content being served, and you'd prefer not to stop the webserver during the certificate issuance process, you can use the webroot plugin to obtain a certificate by including ``certonly`` and ``--webroot`` on the command line. In addition, you'll need to specify ``--webroot-path`` or ``-w`` with the top-level directory ("web root") containing the files served by your webserver. For example, ``--webroot-path /var/www/html`` or ``--webroot-path /usr/share/nginx/html`` are two common webroot paths. If you're getting a certificate for many domains at once, the plugin needs to know where each domain's files are served from, which could potentially be a separate directory for each domain. When requesting a certificate for multiple domains, each domain will use the most recently specified ``--webroot-path``. So, for instance, :: certbot certonly --webroot -w /var/www/example -d www.example.com -d example.com -w /var/www/other -d other.example.net -d another.other.example.net would obtain a single certificate for all of those names, using the ``/var/www/example`` webroot directory for the first two, and ``/var/www/other`` for the second two. The webroot plugin works by creating a temporary file for each of your requested domains in ``${webroot-path}/.well-known/acme-challenge``. Then the Let's Encrypt validation server makes HTTP requests to validate that the DNS for each requested domain resolves to the server running certbot. An example request made to your web server would look like: :: 66.133.109.36 - - [05/Jan/2016:20:11:24 -0500] "GET /.well-known/acme-challenge/HGr8U1IeTW4kY_Z6UIyaakzOkyQgPr_7ArlLgtZE8SX HTTP/1.1" 200 87 "-" "Mozilla/5.0 (compatible; Let's Encrypt validation server; +https://www.letsencrypt.org)" Note that to use the webroot plugin, your server must be configured to serve files from hidden directories. If ``/.well-known`` is treated specially by your webserver configuration, you might need to modify the configuration to ensure that files inside ``/.well-known/acme-challenge`` are served by the webserver. Nginx ----- The Nginx plugin has been distributed with Certbot since version 0.9.0 and should work for most configurations. We recommend backing up Nginx configurations before using it (though you can also revert changes to configurations with ``certbot --nginx rollback``). You can use it by providing the ``--nginx`` flag on the commandline. :: certbot --nginx .. _standalone: Standalone ---------- Use standalone mode to obtain a certificate if you don't want to use (or don't currently have) existing server software. The standalone plugin does not rely on any other server software running on the machine where you obtain the certificate. To obtain a certificate using a "standalone" webserver, you can use the standalone plugin by including ``certonly`` and ``--standalone`` on the command line. This plugin needs to bind to port 80 or 443 in order to perform domain validation, so you may need to stop your existing webserver. To control which port the plugin uses, include one of the options shown below on the command line. * ``--preferred-challenges http`` to use port 80 * ``--preferred-challenges tls-sni`` to use port 443 It must still be possible for your machine to accept inbound connections from the Internet on the specified port using each requested domain name. By default, Certbot first attempts to bind to the port for all interfaces using IPv6 and then bind to that port using IPv4; Certbot continues so long as at least one bind succeeds. On most Linux systems, IPv4 traffic will be routed to the bound IPv6 port and the failure during the second bind is expected. Use ``---address`` to explicitly tell Certbot which interface (and protocol) to bind. .. note:: The ``--standalone-supported-challenges`` option has been deprecated since ``certbot`` version 0.9.0. .. _dns_plugins: DNS Plugins ----------- If you'd like to obtain a wildcard certificate from Let's Encrypt or run ``certbot`` on a machine other than your target webserver, you can use one of Certbot's DNS plugins. These plugins are still in the process of being packaged by many distributions and cannot currently be installed with ``certbot-auto``. If, however, you are comfortable installing the certificates yourself, you can run these plugins with :ref:`Docker `. Once installed, you can find documentation on how to use each plugin at: * `certbot-dns-cloudflare `_ * `certbot-dns-cloudxns `_ * `certbot-dns-digitalocean `_ * `certbot-dns-dnsimple `_ * `certbot-dns-dnsmadeeasy `_ * `certbot-dns-google `_ * `certbot-dns-linode `_ * `certbot-dns-luadns `_ * `certbot-dns-nsone `_ * `certbot-dns-ovh `_ * `certbot-dns-rfc2136 `_ * `certbot-dns-route53 `_ Manual ------ If you'd like to obtain a certificate running ``certbot`` on a machine other than your target webserver or perform the steps for domain validation yourself, you can use the manual plugin. While hidden from the UI, you can use the plugin to obtain a certificate by specifying ``certonly`` and ``--manual`` on the command line. This requires you to copy and paste commands into another terminal session, which may be on a different computer. The manual plugin can use either the ``http``, ``dns`` or the ``tls-sni`` challenge. You can use the ``--preferred-challenges`` option to choose the challenge of your preference. The ``http`` challenge will ask you to place a file with a specific name and specific content in the ``/.well-known/acme-challenge/`` directory directly in the top-level directory (“web root”) containing the files served by your webserver. In essence it's the same as the webroot_ plugin, but not automated. When using the ``dns`` challenge, ``certbot`` will ask you to place a TXT DNS record with specific contents under the domain name consisting of the hostname for which you want a certificate issued, prepended by ``_acme-challenge``. For example, for the domain ``example.com``, a zone file entry would look like: :: _acme-challenge.example.com. 300 IN TXT "gfj9Xq...Rg85nM" When using the ``tls-sni`` challenge, ``certbot`` will prepare a self-signed SSL certificate for you with the challenge validation appropriately encoded into a subjectAlternatNames entry. You will need to configure your SSL server to present this challenge SSL certificate to the ACME server using SNI. Additionally you can specify scripts to prepare for validation and perform the authentication procedure and/or clean up after it by using the ``--manual-auth-hook`` and ``--manual-cleanup-hook`` flags. This is described in more depth in the hooks_ section. .. _combination: Combining plugins ----------------- Sometimes you may want to specify a combination of distinct authenticator and installer plugins. To do so, specify the authenticator plugin with ``--authenticator`` or ``-a`` and the installer plugin with ``--installer`` or ``-i``. For instance, you may want to create a certificate using the webroot_ plugin for authentication and the apache_ plugin for installation, perhaps because you use a proxy or CDN for SSL and only want to secure the connection between them and your origin server, which cannot use the tls-sni-01_ challenge due to the intermediate proxy. :: certbot run -a webroot -i apache -w /var/www/html -d example.com .. _third-party-plugins: Third-party plugins ------------------- There are also a number of third-party plugins for the client, provided by other developers. Many are beta/experimental, but some are already in widespread use: =========== ==== ==== =============================================================== Plugin Auth Inst Notes =========== ==== ==== =============================================================== plesk_ Y Y Integration with the Plesk web hosting tool haproxy_ Y Y Integration with the HAProxy load balancer s3front_ Y Y Integration with Amazon CloudFront distribution of S3 buckets gandi_ Y Y Integration with Gandi's hosting products and API varnish_ Y N Obtain certificates via a Varnish server external_ Y N A plugin for convenient scripting (See also ticket 2782_) icecast_ N Y Deploy certificates to Icecast 2 streaming media servers pritunl_ N Y Install certificates in pritunl distributed OpenVPN servers proxmox_ N Y Install certificates in Proxmox Virtualization servers postfix_ N Y STARTTLS Everywhere is becoming a Certbot Postfix/Exim plugin heroku_ Y Y Integration with Heroku SSL =========== ==== ==== =============================================================== .. _plesk: https://github.com/plesk/letsencrypt-plesk .. _haproxy: https://github.com/greenhost/certbot-haproxy .. _s3front: https://github.com/dlapiduz/letsencrypt-s3front .. _gandi: https://github.com/Gandi/letsencrypt-gandi .. _icecast: https://github.com/e00E/lets-encrypt-icecast .. _varnish: http://git.sesse.net/?p=letsencrypt-varnish-plugin .. _2782: https://github.com/certbot/certbot/issues/2782 .. _pritunl: https://github.com/kharkevich/letsencrypt-pritunl .. _proxmox: https://github.com/kharkevich/letsencrypt-proxmox .. _external: https://github.com/marcan/letsencrypt-external .. _postfix: https://github.com/EFForg/starttls-everywhere .. _heroku: https://github.com/gboudreau/certbot-heroku If you're interested, you can also :ref:`write your own plugin `. .. _managing-certs: Managing certificates ===================== To view a list of the certificates Certbot knows about, run the ``certificates`` subcommand: ``certbot certificates`` This returns information in the following format:: Found the following certs: Certificate Name: example.com Domains: example.com, www.example.com Expiry Date: 2017-02-19 19:53:00+00:00 (VALID: 30 days) Certificate Path: /etc/letsencrypt/live/example.com/fullchain.pem Private Key Path: /etc/letsencrypt/live/example.com/privkey.pem ``Certificate Name`` shows the name of the certificate. Pass this name using the ``--cert-name`` flag to specify a particular certificate for the ``run``, ``certonly``, ``certificates``, ``renew``, and ``delete`` commands. Example:: certbot certonly --cert-name example.com .. _updating_certs: Re-creating and Updating Existing Certificates ---------------------------------------------- You can use ``certonly`` or ``run`` subcommands to request the creation of a single new certificate even if you already have an existing certificate with some of the same domain names. If a certificate is requested with ``run`` or ``certonly`` specifying a certificate name that already exists, Certbot updates the existing certificate. Otherwise a new certificate is created and assigned the specified name. The ``--force-renewal``, ``--duplicate``, and ``--expand`` options control Certbot's behavior when re-creating a certificate with the same name as an existing certificate. If you don't specify a requested behavior, Certbot may ask you what you intended. ``--force-renewal`` tells Certbot to request a new certificate with the same domains as an existing certificate. Each domain must be explicitly specified via ``-d``. If successful, this certificate is saved alongside the earlier one and symbolic links (the "``live``" reference) will be updated to point to the new certificate. This is a valid method of renewing a specific individual certificate. ``--duplicate`` tells Certbot to create a separate, unrelated certificate with the same domains as an existing certificate. This certificate is saved completely separately from the prior one. Most users will not need to issue this command in normal circumstances. ``--expand`` tells Certbot to update an existing certificate with a new certificate that contains all of the old domains and one or more additional new domains. With the ``--expand`` option, use the ``-d`` option to specify all existing domains and one or more new domains. Example: .. code-block:: none certbot --expand -d existing.com,example.com,newdomain.com If you prefer, you can specify the domains individually like this: .. code-block:: none certbot --expand -d existing.com -d example.com -d newdomain.com Consider using ``--cert-name`` instead of ``--expand``, as it gives more control over which certificate is modified and it lets you remove domains as well as adding them. ``--allow-subset-of-names`` tells Certbot to continue with certificate generation if only some of the specified domain authorizations can be obtained. This may be useful if some domains specified in a certificate no longer point at this system. Whenever you obtain a new certificate in any of these ways, the new certificate exists alongside any previously obtained certificates, whether or not the previous certificates have expired. The generation of a new certificate counts against several rate limits that are intended to prevent abuse of the ACME protocol, as described `here `__. .. _changing: Changing a Certificate's Domains ================================ The ``--cert-name`` flag can also be used to modify the domains a certificate contains, by specifying new domains using the ``-d`` or ``--domains`` flag. If certificate ``example.com`` previously contained ``example.com`` and ``www.example.com``, it can be modified to only contain ``example.com`` by specifying only ``example.com`` with the ``-d`` or ``--domains`` flag. Example:: certbot certonly --cert-name example.com -d example.com The same format can be used to expand the set of domains a certificate contains, or to replace that set entirely:: certbot certonly --cert-name example.com -d example.org,www.example.org Revoking certificates --------------------- If your account key has been compromised or you otherwise need to revoke a certificate, use the ``revoke`` command to do so. Note that the ``revoke`` command takes the certificate path (ending in ``cert.pem``), not a certificate name or domain. Example:: certbot revoke --cert-path /etc/letsencrypt/live/CERTNAME/cert.pem You can also specify the reason for revoking your certificate by using the ``reason`` flag. Reasons include ``unspecified`` which is the default, as well as ``keycompromise``, ``affiliationchanged``, ``superseded``, and ``cessationofoperation``:: certbot revoke --cert-path /etc/letsencrypt/live/CERTNAME/cert.pem --reason keycompromise Additionally, if a certificate is a test certificate obtained via the ``--staging`` or ``--test-cert`` flag, that flag must be passed to the ``revoke`` subcommand. Once a certificate is revoked (or for other certificate management tasks), all of a certificate's relevant files can be removed from the system with the ``delete`` subcommand:: certbot delete --cert-name example.com .. note:: If you don't use ``delete`` to remove the certificate completely, it will be renewed automatically at the next renewal event. .. note:: Revoking a certificate will have no effect on the rate limit imposed by the Let's Encrypt server. .. _renewal: Renewing certificates --------------------- .. note:: Let's Encrypt CA issues short-lived certificates (90 days). Make sure you renew the certificates at least once in 3 months. .. seealso:: Many of the certbot clients obtained through a distribution come with automatic renewal out of the box, such as Debian and Ubuntu versions installed through `apt`, CentOS/RHEL 7 through EPEL, etc. See `Automated Renewals`_ for more details. As of version 0.10.0, Certbot supports a ``renew`` action to check all installed certificates for impending expiry and attempt to renew them. The simplest form is simply ``certbot renew`` This command attempts to renew any previously-obtained certificates that expire in less than 30 days. The same plugin and options that were used at the time the certificate was originally issued will be used for the renewal attempt, unless you specify other plugins or options. Unlike ``certonly``, ``renew`` acts on multiple certificates and always takes into account whether each one is near expiry. Because of this, ``renew`` is suitable (and designed) for automated use, to allow your system to automatically renew each certificate when appropriate. Since ``renew`` only renews certificates that are near expiry it can be run as frequently as you want - since it will usually take no action. The ``renew`` command includes hooks for running commands or scripts before or after a certificate is renewed. For example, if you have a single certificate obtained using the standalone_ plugin, you might need to stop the webserver before renewing so standalone can bind to the necessary ports, and then restart it after the plugin is finished. Example:: certbot renew --pre-hook "service nginx stop" --post-hook "service nginx start" If a hook exits with a non-zero exit code, the error will be printed to ``stderr`` but renewal will be attempted anyway. A failing hook doesn't directly cause Certbot to exit with a non-zero exit code, but since Certbot exits with a non-zero exit code when renewals fail, a failed hook causing renewal failures will indirectly result in a non-zero exit code. Hooks will only be run if a certificate is due for renewal, so you can run the above command frequently without unnecessarily stopping your webserver. ``--pre-hook`` and ``--post-hook`` hooks run before and after every renewal attempt. If you want your hook to run only after a successful renewal, use ``--deploy-hook`` in a command like this. ``certbot renew --deploy-hook /path/to/deploy-hook-script`` For example, if you have a daemon that does not read its certificates as the root user, a deploy hook like this can copy them to the correct location and apply appropriate file permissions. /path/to/deploy-hook-script .. code-block:: none #!/bin/sh set -e for domain in $RENEWED_DOMAINS; do case $domain in example.com) daemon_cert_root=/etc/some-daemon/certs # Make sure the certificate and private key files are # never world readable, even just for an instant while # we're copying them into daemon_cert_root. umask 077 cp "$RENEWED_LINEAGE/fullchain.pem" "$daemon_cert_root/$domain.cert" cp "$RENEWED_LINEAGE/privkey.pem" "$daemon_cert_root/$domain.key" # Apply the proper file ownership and permissions for # the daemon to read its certificate and key. chown some-daemon "$daemon_cert_root/$domain.cert" \ "$daemon_cert_root/$domain.key" chmod 400 "$daemon_cert_root/$domain.cert" \ "$daemon_cert_root/$domain.key" service some-daemon restart >/dev/null ;; esac done You can also specify hooks by placing files in subdirectories of Certbot's configuration directory. Assuming your configuration directory is ``/etc/letsencrypt``, any executable files found in ``/etc/letsencrypt/renewal-hooks/pre``, ``/etc/letsencrypt/renewal-hooks/deploy``, and ``/etc/letsencrypt/renewal-hooks/post`` will be run as pre, deploy, and post hooks respectively when any certificate is renewed with the ``renew`` subcommand. These hooks are run in alphabetical order and are not run for other subcommands. (The order the hooks are run is determined by the byte value of the characters in their filenames and is not dependent on your locale.) Hooks specified in the command line, :ref:`configuration file `, or :ref:`renewal configuration files ` are run as usual after running all hooks in these directories. One minor exception to this is if a hook specified elsewhere is simply the path to an executable file in the hook directory of the same type (e.g. your pre-hook is the path to an executable in ``/etc/letsencrypt/renewal-hooks/pre``), the file is not run a second time. You can stop Certbot from automatically running executables found in these directories by including ``--no-directory-hooks`` on the command line. More information about hooks can be found by running ``certbot --help renew``. If you're sure that this command executes successfully without human intervention, you can add the command to ``crontab`` (since certificates are only renewed when they're determined to be near expiry, the command can run on a regular basis, like every week or every day). In that case, you are likely to want to use the ``-q`` or ``--quiet`` quiet flag to silence all output except errors. If you are manually renewing all of your certificates, the ``--force-renewal`` flag may be helpful; it causes the expiration time of the certificate(s) to be ignored when considering renewal, and attempts to renew each and every installed certificate regardless of its age. (This form is not appropriate to run daily because each certificate will be renewed every day, which will quickly run into the certificate authority rate limit.) Note that options provided to ``certbot renew`` will apply to *every* certificate for which renewal is attempted; for example, ``certbot renew --rsa-key-size 4096`` would try to replace every near-expiry certificate with an equivalent certificate using a 4096-bit RSA public key. If a certificate is successfully renewed using specified options, those options will be saved and used for future renewals of that certificate. An alternative form that provides for more fine-grained control over the renewal process (while renewing specified certificates one at a time), is ``certbot certonly`` with the complete set of subject domains of a specific certificate specified via `-d` flags. You may also want to include the ``-n`` or ``--noninteractive`` flag to prevent blocking on user input (which is useful when running the command from cron). ``certbot certonly -n -d example.com -d www.example.com`` All of the domains covered by the certificate must be specified in this case in order to renew and replace the old certificate rather than obtaining a new one; don't forget any `www.` domains! Specifying a subset of the domains creates a new, separate certificate containing only those domains, rather than replacing the original certificate. When run with a set of domains corresponding to an existing certificate, the ``certonly`` command attempts to renew that specific certificate. Please note that the CA will send notification emails to the address you provide if you do not renew certificates that are about to expire. Certbot is working hard to improve the renewal process, and we apologize for any inconvenience you encounter in integrating these commands into your individual environment. .. note:: ``certbot renew`` exit status will only be 1 if a renewal attempt failed. This means ``certbot renew`` exit status will be 0 if no certificate needs to be updated. If you write a custom script and expect to run a command only after a certificate was actually renewed you will need to use the ``--deploy-hook`` since the exit status will be 0 both on successful renewal and when renewal is not necessary. .. _renewal-config-file: Modifying the Renewal Configuration File ---------------------------------------- When a certificate is issued, by default Certbot creates a renewal configuration file that tracks the options that were selected when Certbot was run. This allows Certbot to use those same options again when it comes time for renewal. These renewal configuration files are located at ``/etc/letsencrypt/renewal/CERTNAME``. For advanced certificate management tasks, it is possible to manually modify the certificate's renewal configuration file, but this is discouraged since it can easily break Certbot's ability to renew your certificates. If you choose to modify the renewal configuration file we advise you to test its validity with the ``certbot renew --dry-run`` command. .. warning:: Modifying any files in ``/etc/letsencrypt`` can damage them so Certbot can no longer properly manage its certificates, and we do not recommend doing so. For most tasks, it is safest to limit yourself to pointing symlinks at the files there, or using ``--deploy-hook`` to copy / make new files based upon those files, if your operational situation requires it (for instance, combining certificates and keys in different way, or having copies of things with different specific permissions that are demanded by other programs). If the contents of ``/etc/letsencrypt/archive/CERTNAME`` are moved to a new folder, first specify the new folder's name in the renewal configuration file, then run ``certbot update_symlinks`` to point the symlinks in ``/etc/letsencrypt/live/CERTNAME`` to the new folder. If you would like the live certificate files whose symlink location Certbot updates on each run to reside in a different location, first move them to that location, then specify the full path of each of the four files in the renewal configuration file. Since the symlinks are relative links, you must follow this with an invocation of ``certbot update_symlinks``. For example, say that a certificate's renewal configuration file previously contained the following directives:: archive_dir = /etc/letsencrypt/archive/example.com cert = /etc/letsencrypt/live/example.com/cert.pem privkey = /etc/letsencrypt/live/example.com/privkey.pem chain = /etc/letsencrypt/live/example.com/chain.pem fullchain = /etc/letsencrypt/live/example.com/fullchain.pem The following commands could be used to specify where these files are located:: mv /etc/letsencrypt/archive/example.com /home/user/me/certbot/example_archive sed -i 's,/etc/letsencrypt/archive/example.com,/home/user/me/certbot/example_archive,' /etc/letsencrypt/renewal/example.com.conf mv /etc/letsencrypt/live/example.com/*.pem /home/user/me/certbot/ sed -i 's,/etc/letsencrypt/live/example.com,/home/user/me/certbot,g' /etc/letsencrypt/renewal/example.com.conf certbot update_symlinks Automated Renewals ------------------ Many Linux distributions provide automated renewal when you use the packages installed through their system package manager. The following table is an *incomplete* list of distributions which do so, as well as their methods for doing so. If you are not sure whether or not your system has this already automated, refer to your distribution's documentation, or check your system's crontab (typically in `/etc/crontab/` and `/etc/cron.*/*` and systemd timers (`systemctl list-timers`). .. csv-table:: Distributions with Automated Renewal :header: "Distribution Name", "Distribution Version", "Automation Method" "CentOS", "EPEL 7", "systemd" "Debian", "jessie", "cron, systemd" "Debian", "stretch", "cron, systemd" "Debian", "testing/sid", "cron, systemd" "Fedora", "26", "systemd" "Fedora", "27", "systemd" "RHEL", "EPEL 7", "systemd" "Ubuntu", "17.10", "cron, systemd" "Ubuntu", "certbot PPA", "cron, systemd" .. _where-certs: Where are my certificates? ========================== All generated keys and issued certificates can be found in ``/etc/letsencrypt/live/$domain``. Rather than copying, please point your (web) server configuration directly to those files (or create symlinks). During the renewal_, ``/etc/letsencrypt/live`` is updated with the latest necessary files. .. note:: ``/etc/letsencrypt/archive`` and ``/etc/letsencrypt/keys`` contain all previous keys and certificates, while ``/etc/letsencrypt/live`` symlinks to the latest versions. The following files are available: ``privkey.pem`` Private key for the certificate. .. warning:: This **must be kept secret at all times**! Never share it with anyone, including Certbot developers. You cannot put it into a safe, however - your server still needs to access this file in order for SSL/TLS to work. This is what Apache needs for `SSLCertificateKeyFile `_, and Nginx for `ssl_certificate_key `_. ``fullchain.pem`` All certificates, **including** server certificate (aka leaf certificate or end-entity certificate). The server certificate is the first one in this file, followed by any intermediates. This is what Apache >= 2.4.8 needs for `SSLCertificateFile `_, and what Nginx needs for `ssl_certificate `_. ``cert.pem`` and ``chain.pem`` (less common) ``cert.pem`` contains the server certificate by itself, and ``chain.pem`` contains the additional intermediate certificate or certificates that web browsers will need in order to validate the server certificate. If you provide one of these files to your web server, you **must** provide both of them, or some browsers will show "This Connection is Untrusted" errors for your site, `some of the time `_. Apache < 2.4.8 needs these for `SSLCertificateFile `_. and `SSLCertificateChainFile `_, respectively. If you're using OCSP stapling with Nginx >= 1.3.7, ``chain.pem`` should be provided as the `ssl_trusted_certificate `_ to validate OCSP responses. .. note:: All files are PEM-encoded. If you need other format, such as DER or PFX, then you could convert using ``openssl``. You can automate that with ``--deploy-hook`` if you're using automatic renewal_. .. _hooks: Pre and Post Validation Hooks ============================= Certbot allows for the specification of pre and post validation hooks when run in manual mode. The flags to specify these scripts are ``--manual-auth-hook`` and ``--manual-cleanup-hook`` respectively and can be used as follows: :: certbot certonly --manual --manual-auth-hook /path/to/http/authenticator.sh --manual-cleanup-hook /path/to/http/cleanup.sh -d secure.example.com This will run the ``authenticator.sh`` script, attempt the validation, and then run the ``cleanup.sh`` script. Additionally certbot will pass relevant environment variables to these scripts: - ``CERTBOT_DOMAIN``: The domain being authenticated - ``CERTBOT_VALIDATION``: The validation string (HTTP-01 and DNS-01 only) - ``CERTBOT_TOKEN``: Resource name part of the HTTP-01 challenge (HTTP-01 only) - ``CERTBOT_CERT_PATH``: The challenge SSL certificate (TLS-SNI-01 only) - ``CERTBOT_KEY_PATH``: The private key associated with the aforementioned SSL certificate (TLS-SNI-01 only) - ``CERTBOT_SNI_DOMAIN``: The SNI name for which the ACME server expects to be presented the self-signed certificate located at ``$CERTBOT_CERT_PATH`` (TLS-SNI-01 only) Additionally for cleanup: - ``CERTBOT_AUTH_OUTPUT``: Whatever the auth script wrote to stdout Example usage for HTTP-01: :: certbot certonly --manual --preferred-challenges=http --manual-auth-hook /path/to/http/authenticator.sh --manual-cleanup-hook /path/to/http/cleanup.sh -d secure.example.com /path/to/http/authenticator.sh .. code-block:: none #!/bin/bash echo $CERTBOT_VALIDATION > /var/www/htdocs/.well-known/acme-challenge/$CERTBOT_TOKEN /path/to/http/cleanup.sh .. code-block:: none #!/bin/bash rm -f /var/www/htdocs/.well-known/acme-challenge/$CERTBOT_TOKEN Example usage for DNS-01 (Cloudflare API v4) (for example purposes only, do not use as-is) :: certbot certonly --manual --preferred-challenges=dns --manual-auth-hook /path/to/dns/authenticator.sh --manual-cleanup-hook /path/to/dns/cleanup.sh -d secure.example.com /path/to/dns/authenticator.sh .. code-block:: none #!/bin/bash # Get your API key from https://www.cloudflare.com/a/account/my-account API_KEY="your-api-key" EMAIL="your.email@example.com" # Strip only the top domain to get the zone id DOMAIN=$(expr match "$CERTBOT_DOMAIN" '.*\.\(.*\..*\)') # Get the Cloudflare zone id ZONE_EXTRA_PARAMS="status=active&page=1&per_page=20&order=status&direction=desc&match=all" ZONE_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$DOMAIN&$ZONE_EXTRA_PARAMS" \ -H "X-Auth-Email: $EMAIL" \ -H "X-Auth-Key: $API_KEY" \ -H "Content-Type: application/json" | python -c "import sys,json;print(json.load(sys.stdin)['result'][0]['id'])") # Create TXT record CREATE_DOMAIN="_acme-challenge.$CERTBOT_DOMAIN" RECORD_ID=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \ -H "X-Auth-Email: $EMAIL" \ -H "X-Auth-Key: $API_KEY" \ -H "Content-Type: application/json" \ --data '{"type":"TXT","name":"'"$CREATE_DOMAIN"'","content":"'"$CERTBOT_VALIDATION"'","ttl":120}' \ | python -c "import sys,json;print(json.load(sys.stdin)['result']['id'])") # Save info for cleanup if [ ! -d /tmp/CERTBOT_$CERTBOT_DOMAIN ];then mkdir -m 0700 /tmp/CERTBOT_$CERTBOT_DOMAIN fi echo $ZONE_ID > /tmp/CERTBOT_$CERTBOT_DOMAIN/ZONE_ID echo $RECORD_ID > /tmp/CERTBOT_$CERTBOT_DOMAIN/RECORD_ID # Sleep to make sure the change has time to propagate over to DNS sleep 25 /path/to/dns/cleanup.sh .. code-block:: none #!/bin/bash # Get your API key from https://www.cloudflare.com/a/account/my-account API_KEY="your-api-key" EMAIL="your.email@example.com" if [ -f /tmp/CERTBOT_$CERTBOT_DOMAIN/ZONE_ID ]; then ZONE_ID=$(cat /tmp/CERTBOT_$CERTBOT_DOMAIN/ZONE_ID) rm -f /tmp/CERTBOT_$CERTBOT_DOMAIN/ZONE_ID fi if [ -f /tmp/CERTBOT_$CERTBOT_DOMAIN/RECORD_ID ]; then RECORD_ID=$(cat /tmp/CERTBOT_$CERTBOT_DOMAIN/RECORD_ID) rm -f /tmp/CERTBOT_$CERTBOT_DOMAIN/RECORD_ID fi # Remove the challenge TXT record from the zone if [ -n "${ZONE_ID}" ]; then if [ -n "${RECORD_ID}" ]; then curl -s -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID" \ -H "X-Auth-Email: $EMAIL" \ -H "X-Auth-Key: $API_KEY" \ -H "Content-Type: application/json" fi fi .. _lock-files: Changing the ACME Server ======================== By default, Certbot uses Let's Encrypt's initial production server at https://acme-v01.api.letsencrypt.org/. You can tell Certbot to use a different CA by providing ``--server`` on the command line or in a :ref:`configuration file ` with the URL of the server's ACME directory. For example, if you would like to use Let's Encrypt's new ACMEv2 server, you would add ``--server https://acme-v02.api.letsencrypt.org/directory`` to the command line. Certbot will automatically select which version of the ACME protocol to use based on the contents served at the provided URL. If you use ``--server`` to specify an ACME CA that implements a newer version of the spec, you may be able to obtain a certificate for a wildcard domain. Some CAs (such as Let's Encrypt) require that domain validation for wildcard domains must be done through modifications to DNS records which means that the dns-01_ challenge type must be used. To see a list of Certbot plugins that support this challenge type and how to use them, see plugins_. Lock Files ========== When processing a validation Certbot writes a number of lock files on your system to prevent multiple instances from overwriting each other's changes. This means that be default two instances of Certbot will not be able to run in parallel. Since the directories used by Certbot are configurable, Certbot will write a lock file for all of the directories it uses. This include Certbot's ``--work-dir``, ``--logs-dir``, and ``--config-dir``. By default these are ``/var/lib/letsencrypt``, ``/var/logs/letsencrypt``, and ``/etc/letsencrypt`` respectively. Additionally if you are using Certbot with Apache or nginx it will lock the configuration folder for that program, which are typically also in the ``/etc`` directory. Note that these lock files will only prevent other instances of Certbot from using those directories, not other processes. If you'd like to run multiple instances of Certbot simultaneously you should specify different directories as the ``--work-dir``, ``--logs-dir``, and ``--config-dir`` for each instance of Certbot that you would like to run. .. _config-file: Configuration file ================== Certbot accepts a global configuration file that applies its options to all invocations of Certbot. Certificate specific configuration choices should be set in the ``.conf`` files that can be found in ``/etc/letsencrypt/renewal``. By default no cli.ini file is created, after creating one it is possible to specify the location of this configuration file with ``certbot-auto --config cli.ini`` (or shorter ``-c cli.ini``). An example configuration file is shown below: .. include:: ../examples/cli.ini :code: ini By default, the following locations are searched: - ``/etc/letsencrypt/cli.ini`` - ``$XDG_CONFIG_HOME/letsencrypt/cli.ini`` (or ``~/.config/letsencrypt/cli.ini`` if ``$XDG_CONFIG_HOME`` is not set). Since this configuration file applies to all invocations of certbot it is incorrect to list domains in it. Listing domains in cli.ini may prevent renewal from working. Additionally due to how arguments in cli.ini are parsed, options which wish to not be set should not be listed. Options set to false will instead be read as being set to true by older versions of Certbot, since they have been listed in the config file. .. keep it up to date with constants.py .. _log-rotation: Log Rotation ============ By default certbot stores status logs in ``/var/log/letsencrypt``. By default certbot will begin rotating logs once there are 1000 logs in the log directory. Meaning that once 1000 files are in ``/var/log/letsencrypt`` Certbot will delete the oldest one to make room for new logs. The number of subsequent logs can be changed by passing the desired number to the command line flag ``--max-log-backups``. .. note:: Some distributions, including Debian and Ubuntu, disable certbot's internal log rotation in favor of a more traditional logrotate script. If you are using a distribution's packages and want to alter the log rotation, check `/etc/logrotate.d/` for a certbot rotation script. .. _command-line: Certbot command-line options ============================ Certbot supports a lot of command line options. Here's the full list, from ``certbot --help all``: .. literalinclude:: cli-help.txt Getting help ============ If you're having problems, we recommend posting on the Let's Encrypt `Community Forum `_. You can also chat with us on IRC: `(#letsencrypt @ freenode) `_ If you find a bug in the software, please do report it in our `issue tracker `_. Remember to give us as much information as possible: - copy and paste exact command line used and the output (though mind that the latter might include some personally identifiable information, including your email and domains) - copy and paste logs from ``/var/log/letsencrypt`` (though mind they also might contain personally identifiable information) - copy and paste ``certbot --version`` output - your operating system, including specific version - specify which installation method you've chosen certbot-0.27.0/docs/.gitignore0000644000175000017500000000001113344054434016346 0ustar ericaerica00000000000000/_build/ certbot-0.27.0/docs/install.rst0000644000175000017500000002532613344054434016576 0ustar ericaerica00000000000000===================== Get Certbot ===================== .. contents:: Table of Contents :local: About Certbot ============= Certbot is packaged for many common operating systems and web servers. Check whether ``certbot`` (or ``letsencrypt``) is packaged for your web server's OS by visiting certbot.eff.org_, where you will also find the correct installation instructions for your system. .. Note:: Unless you have very specific requirements, we kindly suggest that you use the Certbot packages provided by your package manager (see certbot.eff.org_). If such packages are not available, we recommend using ``certbot-auto``, which automates the process of installing Certbot on your system. .. _certbot.eff.org: https://certbot.eff.org .. _system_requirements: System Requirements =================== Certbot currently requires Python 2.7 or 3.4+ running on a UNIX-like operating system. By default, it requires root access in order to write to ``/etc/letsencrypt``, ``/var/log/letsencrypt``, ``/var/lib/letsencrypt``; to bind to ports 80 and 443 (if you use the ``standalone`` plugin) and to read and modify webserver configurations (if you use the ``apache`` or ``nginx`` plugins). If none of these apply to you, it is theoretically possible to run without root privileges, but for most users who want to avoid running an ACME client as root, either `letsencrypt-nosudo `_ or `simp_le `_ are more appropriate choices. The Apache plugin currently requires an OS with augeas version 1.0; currently `it supports `_ modern OSes based on Debian, Fedora, SUSE, Gentoo and Darwin. Additional integrity verification of certbot-auto script can be done by verifying its digital signature. This requires a local installation of gpg2, which comes packaged in many Linux distributions under name gnupg or gnupg2. Installing with ``certbot-auto`` requires 512MB of RAM in order to build some of the dependencies. Installing from pre-built OS packages avoids this requirement. You can also temporarily set a swap file. See "Problems with Python virtual environment" below for details. Alternate installation methods ================================ If you are offline or your operating system doesn't provide a package, you can use an alternate method for installing ``certbot``. .. _certbot-auto: Certbot-Auto ------------ The ``certbot-auto`` wrapper script installs Certbot, obtaining some dependencies from your web server OS and putting others in a python virtual environment. You can download and run it as follows:: user@webserver:~$ wget https://dl.eff.org/certbot-auto user@webserver:~$ chmod a+x ./certbot-auto user@webserver:~$ ./certbot-auto --help To check the integrity of the ``certbot-auto`` script, you can use these steps:: user@webserver:~$ wget -N https://dl.eff.org/certbot-auto.asc user@webserver:~$ gpg2 --keyserver pool.sks-keyservers.net --recv-key A2CFB51FA275A7286234E7B24D17C995CD9775F2 user@webserver:~$ gpg2 --trusted-key 4D17C995CD9775F2 --verify certbot-auto.asc certbot-auto The output of the last command should look something like:: gpg: Signature made Wed 02 May 2018 05:29:12 AM IST gpg: using RSA key A2CFB51FA275A7286234E7B24D17C995CD9775F2 gpg: key 4D17C995CD9775F2 marked as ultimately trusted gpg: checking the trustdb gpg: marginals needed: 3 completes needed: 1 trust model: pgp gpg: depth: 0 valid: 2 signed: 2 trust: 0-, 0q, 0n, 0m, 0f, 2u gpg: depth: 1 valid: 2 signed: 0 trust: 2-, 0q, 0n, 0m, 0f, 0u gpg: next trustdb check due at 2027-11-22 gpg: Good signature from "Let's Encrypt Client Team " [ultimate] The ``certbot-auto`` command updates to the latest client release automatically. Since ``certbot-auto`` is a wrapper to ``certbot``, it accepts exactly the same command line flags and arguments. For more information, see `Certbot command-line options `_. For full command line help, you can type:: ./certbot-auto --help all Problems with Python virtual environment ---------------------------------------- On a low memory system such as VPS with less than 512MB of RAM, the required dependencies of Certbot will fail to build. This can be identified if the pip outputs contains something like ``internal compiler error: Killed (program cc1)``. You can workaround this restriction by creating a temporary swapfile:: user@webserver:~$ sudo fallocate -l 1G /tmp/swapfile user@webserver:~$ sudo chmod 600 /tmp/swapfile user@webserver:~$ sudo mkswap /tmp/swapfile user@webserver:~$ sudo swapon /tmp/swapfile Disable and remove the swapfile once the virtual environment is constructed:: user@webserver:~$ sudo swapoff /tmp/swapfile user@webserver:~$ sudo rm /tmp/swapfile .. _docker-user: Running with Docker ------------------- Docker_ is an amazingly simple and quick way to obtain a certificate. However, this mode of operation is unable to install certificates or configure your webserver, because our installer plugins cannot reach your webserver from inside the Docker container. Most users should use the operating system packages (see instructions at certbot.eff.org_) or, as a fallback, ``certbot-auto``. You should only use Docker if you are sure you know what you are doing and have a good reason to do so. You should definitely read the :ref:`where-certs` section, in order to know how to manage the certs manually. `Our ciphersuites page `__ provides some information about recommended ciphersuites. If none of these make much sense to you, you should definitely use the certbot-auto_ method, which enables you to use installer plugins that cover both of those hard topics. If you're still not convinced and have decided to use this method, from the server that the domain you're requesting a certficate for resolves to, `install Docker`_, then issue a command like the one found below. If you are using Certbot with the :ref:`Standalone` plugin, you will need to make the port it uses accessible from outside of the container by including something like ``-p 80:80`` or ``-p 443:443`` on the command line before ``certbot/certbot``. .. code-block:: shell sudo docker run -it --rm --name certbot \ -v "/etc/letsencrypt:/etc/letsencrypt" \ -v "/var/lib/letsencrypt:/var/lib/letsencrypt" \ certbot/certbot certonly Running Certbot with the ``certonly`` command will obtain a certificate and place it in the directory ``/etc/letsencrypt/live`` on your system. Because Certonly cannot install the certificate from within Docker, you must install the certificate manually according to the procedure recommended by the provider of your webserver. There are also Docker images for each of Certbot's DNS plugins available at https://hub.docker.com/u/certbot which automate doing domain validation over DNS for popular providers. To use one, just replace ``certbot/certbot`` in the command above with the name of the image you want to use. For example, to use Certbot's plugin for Amazon Route 53, you'd use ``certbot/dns-route53``. You may also need to add flags to Certbot and/or mount additional directories to provide access to your DNS API credentials as specified in the :ref:`DNS plugin documentation `. If you would like to obtain a wildcard certificate from Let's Encrypt's ACMEv2 server, you'll need to include ``--server https://acme-v02.api.letsencrypt.org/directory`` on the command line as well. For more information about the layout of the ``/etc/letsencrypt`` directory, see :ref:`where-certs`. .. _Docker: https://docker.com .. _`install Docker`: https://docs.docker.com/engine/installation/ Operating System Packages ------------------------- **Arch Linux** .. code-block:: shell sudo pacman -S certbot **Debian** If you run Debian Stretch or Debian Sid, you can install certbot packages. .. code-block:: shell sudo apt-get update sudo apt-get install certbot python-certbot-apache If you don't want to use the Apache plugin, you can omit the ``python-certbot-apache`` package. Or you can install ``python-certbot-nginx`` instead. Packages exist for Debian Jessie via backports. First you'll have to follow the instructions at http://backports.debian.org/Instructions/ to enable the Jessie backports repo, if you have not already done so. Then run: .. code-block:: shell sudo apt-get install certbot python-certbot-apache -t jessie-backports **Fedora** .. code-block:: shell sudo dnf install certbot python2-certbot-apache **FreeBSD** * Port: ``cd /usr/ports/security/py-certbot && make install clean`` * Package: ``pkg install py27-certbot`` **Gentoo** The official Certbot client is available in Gentoo Portage. If you want to use the Apache plugin, it has to be installed separately: .. code-block:: shell emerge -av app-crypt/certbot emerge -av app-crypt/certbot-apache When using the Apache plugin, you will run into a "cannot find an SSLCertificateFile directive" or "cannot find an SSLCertificateKeyFile directive for certificate" error if you're sporting the default Gentoo ``httpd.conf``. You can fix this by commenting out two lines in ``/etc/apache2/httpd.conf`` as follows: Change .. code-block:: shell LoadModule ssl_module modules/mod_ssl.so to .. code-block:: shell # LoadModule ssl_module modules/mod_ssl.so # For the time being, this is the only way for the Apache plugin to recognise the appropriate directives when installing the certificate. Note: this change is not required for the other plugins. **NetBSD** * Build from source: ``cd /usr/pkgsrc/security/py-certbot && make install clean`` * Install pre-compiled package: ``pkg_add py27-certbot`` **OpenBSD** * Port: ``cd /usr/ports/security/letsencrypt/client && make install clean`` * Package: ``pkg_add letsencrypt`` **Other Operating Systems** OS packaging is an ongoing effort. If you'd like to package Certbot for your distribution of choice please have a look at the :doc:`packaging`. Installing from source ---------------------- Installation from source is only supported for developers and the whole process is described in the :doc:`contributing`. .. warning:: Please do **not** use ``python setup.py install``, ``python pip install .``, or ``easy_install .``. Please do **not** attempt the installation commands as superuser/root and/or without virtual environment, e.g. ``sudo python setup.py install``, ``sudo pip install``, ``sudo ./venv/bin/...``. These modes of operation might corrupt your operating system and are **not supported** by the Certbot team! certbot-0.27.0/docs/Makefile0000644000175000017500000001563413344054434016037 0ustar ericaerica00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/LetsEncrypt.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/LetsEncrypt.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/LetsEncrypt" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/LetsEncrypt" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." certbot-0.27.0/docs/api/0002755000175000017500000000000013344054435015142 5ustar ericaerica00000000000000certbot-0.27.0/docs/api/display.rst0000644000175000017500000000070513344054434017340 0ustar ericaerica00000000000000:mod:`certbot.display` -------------------------- .. automodule:: certbot.display :members: :mod:`certbot.display.util` =============================== .. automodule:: certbot.display.util :members: :mod:`certbot.display.ops` ============================== .. automodule:: certbot.display.ops :members: :mod:`certbot.display.enhancements` ======================================= .. automodule:: certbot.display.enhancements :members: certbot-0.27.0/docs/api/constants.rst0000644000175000017500000000035113344054434017704 0ustar ericaerica00000000000000:mod:`certbot.constants` ----------------------------------- .. automodule:: certbot.constants :members: :exclude-members: SSL_DHPARAMS_SRC .. autodata:: SSL_DHPARAMS_SRC :annotation: = '/path/to/certbot/ssl-dhparams.pem' certbot-0.27.0/docs/api/util.rst0000644000175000017500000000013213344054434016642 0ustar ericaerica00000000000000:mod:`certbot.util` -------------------------- .. automodule:: certbot.util :members: certbot-0.27.0/docs/api/interfaces.rst0000644000175000017500000000015113344054434020011 0ustar ericaerica00000000000000:mod:`certbot.interfaces` ----------------------------- .. automodule:: certbot.interfaces :members: certbot-0.27.0/docs/api/crypto_util.rst0000644000175000017500000000015413344054434020246 0ustar ericaerica00000000000000:mod:`certbot.crypto_util` ------------------------------ .. automodule:: certbot.crypto_util :members: certbot-0.27.0/docs/api/storage.rst0000644000175000017500000000014013344054434017330 0ustar ericaerica00000000000000:mod:`certbot.storage` -------------------------- .. automodule:: certbot.storage :members: certbot-0.27.0/docs/api/log.rst0000644000175000017500000000012413344054434016447 0ustar ericaerica00000000000000:mod:`certbot.log` ---------------------- .. automodule:: certbot.log :members: certbot-0.27.0/docs/api/configuration.rst0000644000175000017500000000016213344054434020537 0ustar ericaerica00000000000000:mod:`certbot.configuration` -------------------------------- .. automodule:: certbot.configuration :members: certbot-0.27.0/docs/api/client.rst0000644000175000017500000000013513344054434017146 0ustar ericaerica00000000000000:mod:`certbot.client` ------------------------- .. automodule:: certbot.client :members: certbot-0.27.0/docs/api/reporter.rst0000644000175000017500000000014313344054434017531 0ustar ericaerica00000000000000:mod:`certbot.reporter` --------------------------- .. automodule:: certbot.reporter :members: certbot-0.27.0/docs/api/renewal.rst0000644000175000017500000000014013344054434017321 0ustar ericaerica00000000000000:mod:`certbot.renewal` -------------------------- .. automodule:: certbot.renewal :members: certbot-0.27.0/docs/api/hooks.rst0000644000175000017500000000013213344054434017010 0ustar ericaerica00000000000000:mod:`certbot.hooks` ------------------------ .. automodule:: certbot.hooks :members: certbot-0.27.0/docs/api/error_handler.rst0000644000175000017500000000016213344054434020516 0ustar ericaerica00000000000000:mod:`certbot.error_handler` -------------------------------- .. automodule:: certbot.error_handler :members: certbot-0.27.0/docs/api/eff.rst0000644000175000017500000000012413344054434016426 0ustar ericaerica00000000000000:mod:`certbot.eff` ---------------------- .. automodule:: certbot.eff :members: certbot-0.27.0/docs/api/ocsp.rst0000644000175000017500000000012713344054434016635 0ustar ericaerica00000000000000:mod:`certbot.ocsp` ----------------------- .. automodule:: certbot.ocsp :members: certbot-0.27.0/docs/api/achallenges.rst0000644000175000017500000000015413344054434020137 0ustar ericaerica00000000000000:mod:`certbot.achallenges` ------------------------------ .. automodule:: certbot.achallenges :members: certbot-0.27.0/docs/api/reverter.rst0000644000175000017500000000014313344054434017525 0ustar ericaerica00000000000000:mod:`certbot.reverter` --------------------------- .. automodule:: certbot.reverter :members: certbot-0.27.0/docs/api/main.rst0000644000175000017500000000012713344054434016615 0ustar ericaerica00000000000000:mod:`certbot.main` ----------------------- .. automodule:: certbot.main :members: certbot-0.27.0/docs/api/cert_manager.rst0000644000175000017500000000015713344054434020323 0ustar ericaerica00000000000000:mod:`certbot.cert_manager` ------------------------------- .. automodule:: certbot.cert_manager :members: certbot-0.27.0/docs/api/plugins/0002755000175000017500000000000013344054435016623 5ustar ericaerica00000000000000certbot-0.27.0/docs/api/plugins/common.rst0000644000175000017500000000016513344054434020644 0ustar ericaerica00000000000000:mod:`certbot.plugins.common` --------------------------------- .. automodule:: certbot.plugins.common :members: certbot-0.27.0/docs/api/plugins/webroot.rst0000644000175000017500000000017013344054434021031 0ustar ericaerica00000000000000:mod:`certbot.plugins.webroot` ---------------------------------- .. automodule:: certbot.plugins.webroot :members: certbot-0.27.0/docs/api/plugins/util.rst0000644000175000017500000000015713344054434020332 0ustar ericaerica00000000000000:mod:`certbot.plugins.util` ------------------------------- .. automodule:: certbot.plugins.util :members: certbot-0.27.0/docs/api/plugins/selection.rst0000644000175000017500000000017613344054434021343 0ustar ericaerica00000000000000:mod:`certbot.plugins.selection` ------------------------------------ .. automodule:: certbot.plugins.selection :members: certbot-0.27.0/docs/api/plugins/manual.rst0000644000175000017500000000016513344054434020631 0ustar ericaerica00000000000000:mod:`certbot.plugins.manual` --------------------------------- .. automodule:: certbot.plugins.manual :members: certbot-0.27.0/docs/api/plugins/dns_common_lexicon.rst0000644000175000017500000000022513344054434023226 0ustar ericaerica00000000000000:mod:`certbot.plugins.dns_common_lexicon` ----------------------------------------- .. automodule:: certbot.plugins.dns_common_lexicon :members: certbot-0.27.0/docs/api/plugins/dns_common.rst0000644000175000017500000000017513344054434021511 0ustar ericaerica00000000000000:mod:`certbot.plugins.dns_common` --------------------------------- .. automodule:: certbot.plugins.dns_common :members: certbot-0.27.0/docs/api/plugins/standalone.rst0000644000175000017500000000020113344054434021473 0ustar ericaerica00000000000000:mod:`certbot.plugins.standalone` ------------------------------------- .. automodule:: certbot.plugins.standalone :members: certbot-0.27.0/docs/api/plugins/disco.rst0000644000175000017500000000016213344054434020452 0ustar ericaerica00000000000000:mod:`certbot.plugins.disco` -------------------------------- .. automodule:: certbot.plugins.disco :members: certbot-0.27.0/docs/api/account.rst0000644000175000017500000000014013344054434017320 0ustar ericaerica00000000000000:mod:`certbot.account` -------------------------- .. automodule:: certbot.account :members: certbot-0.27.0/docs/api/cli.rst0000644000175000017500000000012413344054434016435 0ustar ericaerica00000000000000:mod:`certbot.cli` ---------------------- .. automodule:: certbot.cli :members: certbot-0.27.0/docs/api/notify.rst0000644000175000017500000000013513344054434017200 0ustar ericaerica00000000000000:mod:`certbot.notify` ------------------------- .. automodule:: certbot.notify :members: certbot-0.27.0/docs/api/errors.rst0000644000175000017500000000013513344054434017204 0ustar ericaerica00000000000000:mod:`certbot.errors` ------------------------- .. automodule:: certbot.errors :members: certbot-0.27.0/docs/api/lock.rst0000644000175000017500000000012713344054434016621 0ustar ericaerica00000000000000:mod:`certbot.lock` ----------------------- .. automodule:: certbot.lock :members: certbot-0.27.0/docs/api/index.rst0000644000175000017500000000011013344054434016770 0ustar ericaerica00000000000000:mod:`certbot` ------------------ .. automodule:: certbot :members: certbot-0.27.0/docs/api/auth_handler.rst0000644000175000017500000000015713344054434020332 0ustar ericaerica00000000000000:mod:`certbot.auth_handler` ------------------------------- .. automodule:: certbot.auth_handler :members: certbot-0.27.0/docs/packaging.rst0000644000175000017500000001157413344054434017054 0ustar ericaerica00000000000000=============== Packaging Guide =============== Releases ======== We release packages and upload them to PyPI (wheels and source tarballs). - https://pypi.python.org/pypi/acme - https://pypi.python.org/pypi/certbot - https://pypi.python.org/pypi/certbot-apache - https://pypi.python.org/pypi/certbot-nginx - https://pypi.python.org/pypi/certbot-dns-cloudflare - https://pypi.python.org/pypi/certbot-dns-cloudxns - https://pypi.python.org/pypi/certbot-dns-digitalocean - https://pypi.python.org/pypi/certbot-dns-dnsimple - https://pypi.python.org/pypi/certbot-dns-dnsmadeeasy - https://pypi.python.org/pypi/certbot-dns-google - https://pypi.python.org/pypi/certbot-dns-linode - https://pypi.python.org/pypi/certbot-dns-luadns - https://pypi.python.org/pypi/certbot-dns-nsone - https://pypi.python.org/pypi/certbot-dns-ovh - https://pypi.python.org/pypi/certbot-dns-rfc2136 - https://pypi.python.org/pypi/certbot-dns-route53 The following scripts are used in the process: - https://github.com/letsencrypt/letsencrypt/blob/master/tools/release.sh We use git tags to identify releases, using `Semantic Versioning`_. For example: `v0.11.1`. .. _`Semantic Versioning`: http://semver.org/ Notes for package maintainers ============================= 0. Please use our tagged releases, not ``master``! 1. Do not package ``certbot-compatibility-test`` or ``letshelp-certbot`` - it's only used internally. 2. If you'd like to include automated renewal in your package ``certbot renew -q`` should be added to crontab or systemd timer. Additionally you should include a random per-machine time offset to avoid having a large number of your clients hit Let's Encrypt's servers simultaneously. 3. ``jws`` is an internal script for ``acme`` module and it doesn't have to be packaged - it's mostly for debugging: you can use it as ``echo foo | jws sign | jws verify``. 4. Do get in touch with us. We are happy to make any changes that will make packaging easier. If you need to apply some patches don't do it downstream - make a PR here. Already ongoing efforts ======================= Arch ---- From our official releases: - https://www.archlinux.org/packages/community/any/python-acme - https://www.archlinux.org/packages/community/any/certbot - https://www.archlinux.org/packages/community/any/certbot-apache - https://www.archlinux.org/packages/community/any/certbot-nginx - https://www.archlinux.org/packages/community/any/certbot-dns-cloudflare - https://www.archlinux.org/packages/community/any/certbot-dns-cloudxns - https://www.archlinux.org/packages/community/any/certbot-dns-digitalocean - https://www.archlinux.org/packages/community/any/certbot-dns-dnsimple - https://www.archlinux.org/packages/community/any/certbot-dns-dnsmadeeasy - https://www.archlinux.org/packages/community/any/certbot-dns-google - https://www.archlinux.org/packages/community/any/certbot-dns-luadns - https://www.archlinux.org/packages/community/any/certbot-dns-nsone - https://www.archlinux.org/packages/community/any/certbot-dns-rfc2136 - https://www.archlinux.org/packages/community/any/certbot-dns-route53 From ``master``: https://aur.archlinux.org/packages/certbot-git Debian (and its derivatives, including Ubuntu) ---------------------------------------------- - https://packages.debian.org/sid/certbot - https://packages.debian.org/sid/python-certbot - https://packages.debian.org/sid/python-certbot-apache Fedora ------ In Fedora 23+. - https://apps.fedoraproject.org/packages/python-acme - https://apps.fedoraproject.org/packages/certbot - https://apps.fedoraproject.org/packages/python-certbot-apache - https://apps.fedoraproject.org/packages/python-certbot-dns-cloudflare - https://apps.fedoraproject.org/packages/python-certbot-dns-cloudxns - https://apps.fedoraproject.org/packages/python-certbot-dns-digitalocean - https://apps.fedoraproject.org/packages/python-certbot-dns-dnsimple - https://apps.fedoraproject.org/packages/python-certbot-dns-dnsmadeeasy - https://apps.fedoraproject.org/packages/python-certbot-dns-google - https://apps.fedoraproject.org/packages/python-certbot-dns-luadns - https://apps.fedoraproject.org/packages/python-certbot-dns-nsone - https://apps.fedoraproject.org/packages/python-certbot-dns-rfc2136 - https://apps.fedoraproject.org/packages/python-certbot-dns-route53 - https://apps.fedoraproject.org/packages/python-certbot-nginx FreeBSD ------- - https://www.freshports.org/security/py-acme/ - https://www.freshports.org/security/py-certbot/ Gentoo ------ Currently, all ``certbot`` related packages are in the testing branch: - https://packages.gentoo.org/packages/app-crypt/certbot - https://packages.gentoo.org/packages/app-crypt/certbot-apache - https://packages.gentoo.org/packages/app-crypt/certbot-nginx - https://packages.gentoo.org/packages/app-crypt/acme GNU Guix -------- - https://www.gnu.org/software/guix/package-list.html#certbot OpenBSD ------- - http://cvsweb.openbsd.org/cgi-bin/cvsweb/ports/security/letsencrypt/client/ certbot-0.27.0/docs/_static/0002755000175000017500000000000013344054435016017 5ustar ericaerica00000000000000certbot-0.27.0/docs/_static/.gitignore0000644000175000017500000000000013344054434017772 0ustar ericaerica00000000000000certbot-0.27.0/docs/what.rst0000644000175000017500000000326613344054434016072 0ustar ericaerica00000000000000====================== What is a Certificate? ====================== A public key or digital *certificate* (formerly called an SSL certificate) uses a public key and a private key to enable secure communication between a client program (web browser, email client, etc.) and a server over an encrypted SSL (secure socket layer) or TLS (transport layer security) connection. The certificate is used both to encrypt the initial stage of communication (secure key exchange) and to identify the server. The certificate includes information about the key, information about the server identity, and the digital signature of the certificate issuer. If the issuer is trusted by the software that initiates the communication, and the signature is valid, then the key can be used to communicate securely with the server identified by the certificate. Using a certificate is a good way to prevent "man-in-the-middle" attacks, in which someone in between you and the server you think you are talking to is able to insert their own (harmful) content. You can use Certbot to easily obtain and configure a free certificate from Let's Encrypt, a joint project of EFF, Mozilla, and many other sponsors. Certificates and Lineages ========================= Certbot introduces the concept of a *lineage,* which is a collection of all the versions of a certificate plus Certbot configuration information maintained for that certificate from renewal to renewal. Whenever you renew a certificate, Certbot keeps the same configuration unless you explicitly change it, for example by adding or removing domains. If you add domains, you can either add them to an existing lineage or create a new one. See also: :ref:`updating_certs` certbot-0.27.0/docs/challenges.rst0000644000175000017500000001337713344054434017240 0ustar ericaerica00000000000000Challenges ========== To receive a certificate from Let's Encrypt certificate authority (CA), you must pass a *challenge* to prove you control each of the domain names that will be listed in the certificate. A challenge is one of three tasks that only someone who controls the domain should be able to accomplish: * Posting a specified file in a specified location on a web site (the HTTP-01 challenge) * Offering a specified temporary certificate on a web site (the TLS-SNI-01 challenge) * Posting a specified DNS record in the domain name system (the DNS-01 challenge) It’s possible to complete each type of challenge *automatically* (Certbot directly makes the necessary changes itself, or runs another program that does so), or *manually* (Certbot tells you to make a certain change, and you edit a configuration file of some kind in order to accomplish it). Certbot's design favors performing challenges automatically, and this is the normal case for most users of Certbot. Some plugins offer an *authenticator*, meaning that they can satisfy challenges: * Apache plugin: (TLS-SNI-01) Tries to edit your Apache configuration files to temporarily serve a Certbot-generated certificate for a specified name. Use the Apache plugin when you're running Certbot on a web server with Apache listening on port 443. * NGINX plugin: (TLS-SNI-01) Tries to edit your NGINX configuration files to temporarily serve a Certbot-generated certificate for a specified name. Use the NGINX plugin when you're running Certbot on a web server with NGINX listening on port 443. * Webroot plugin: (HTTP-01) Tries to place a file where it can be served over HTTP on port 80 by a web server running on your system. Use the Webroot plugin when you're running Certbot on a web server with any server application listening on port 80 serving files from a folder on disk in response. * Standalone plugin: (TLS-SNI-01 or HTTP-01) Tries to run a temporary web server listening on either HTTP on port 80 (for HTTP-01) or HTTPS on port 443 (for TLS-SNI-01). Use the Standalone plugin if no existing program is listening to these ports. Choose TLS-SNI-01 or HTTP-01 using the `--preferred-challenges` option. * Manual plugin: (DNS-01 or HTTP-01) Either tells you what changes to make to your configuration or updates your DNS records using an external script (for DNS-01) or your webroot (for HTTP-01). Use the Manual plugin if you have the technical knowledge to make configuration changes yourself when asked to do so. Tips for Challenges ------------------- General tips: * Run Certbot on your web server, not on your laptop or another server. It’s usually the easiest way to get a certificate. * Use a tool like the DNSchecker at dnsstuff.com to check your DNS records to make sure there are no serious errors. A DNS error can prevent a certificate authority from issuing a certificate, even if it does not prevent your site from loading in a browser. * If you are using Apache or NGINX plugins, make sure the configuration of your Apache or NGINX server is correct. HTTP-01 Challenge ~~~~~~~~~~~~~~~~~ * Make sure the domain name exists and is already pointed to the public IP address of the server where you’re requesting the certificate. * Make sure port 80 is open, publicly reachable from the Internet, and not blocked by a router or firewall. * When using the Webroot plugin or the manual plugin, make sure the the webroot directory exists and that you specify it properly. If you set the webroot directory for example.com to `/var/www/example.com` then a file placed in `/var/www/example.com/.well-known/acme-challenge/testfile` should appear on your web site at `http://example.com/.well-known/acme-challenge/testfile` (A redirection to HTTPS is OK here and should not stop the challenge from working.) * In some web server configurations, all pages are dynamically generated by some kind of framework, usually using a database backend. In this case, there might not be a particular directory from which the web server can serve filesdirectly. Using the Webroot plugin in this case requires making a change to your web server configuration first. * Make sure your web server serves files properly from the directory where the challenge file is placed (e. g. `/.well-known/acme-challenge`) to the expected location on the website without adding a header or footer. * When using the Standalone plugin, make sure another program is not already listening to port 80 on the server. * When using the Webroot plugin, make sure there is a web server listening on port 80. TLS-SNI-01 Challenge ~~~~~~~~~~~~~~~~~~~~ * The TLS-SNI-01 challenge doesn’t work with content delivery networks (CDNs) like CloudFlare and Akamai because the domain name is pointed at the CDN, not directly at your server. * Make sure port 443 is open, publicly reachable from the Internet, and not blocked by a router or firewall. * When using the Apache plugin, make sure you are running Apache and no other web server on port 443. * When using the NGINX plugin, make sure you are running NGINX and no other web server on port 443. * With either the Apache or NGINX plugin, certbot modifies your web server configuration. If you get an error after successfully completing the challenge, then you have received a certificate but the plugin was unable to modify your web server configuration, meaning that you'll have to install the certificate manually. In that case, please file a bug to help us improve certbot! * When using the Standalone plugin, make sure another program is not already listening to port 443 on the server. DNS-01 Challenge ~~~~~~~~~~~~~~~~ * When using the manual plugin, make sure your DNS records are correctly updated; you must be able to make appropriate changes to your DNS zone in order to pass the challenge. certbot-0.27.0/docs/index.rst0000644000175000017500000000051213344054434016225 0ustar ericaerica00000000000000Welcome to the Certbot documentation! ================================================== .. toctree:: :maxdepth: 2 intro what install using contributing packaging resources .. toctree:: :maxdepth: 1 api Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` certbot-0.27.0/docs/conf.py0000644000175000017500000002466413344054434015701 0ustar ericaerica00000000000000# -*- coding: utf-8 -*- # # Certbot documentation build configuration file, created by # sphinx-quickstart on Sun Nov 23 20:35:21 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import codecs import os import re import sys here = os.path.abspath(os.path.dirname(__file__)) # read version number (and other metadata) from package init init_fn = os.path.join(here, '..', 'certbot', '__init__.py') with codecs.open(init_fn, encoding='utf8') as fd: meta = dict(re.findall(r"""__([a-z]+)__ = '([^']+)""", fd.read())) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath(os.path.join(here, '..'))) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.imgconverter', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'repoze.sphinx.autointerface', ] autodoc_member_order = 'bysource' autodoc_default_flags = ['show-inheritance', 'private-members'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Certbot' # this is now overridden by the footer.html template #copyright = u'2014-2018 - The Certbot software and documentation are licensed under the Apache 2.0 license as described at https://eff.org/cb-license.' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '.'.join(meta['version'].split('.')[:2]) # The full version, including alpha/beta/rc tags. release = meta['version'] # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. default_role = 'py:obj' # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True suppress_warnings = ['image.nonlocal_uri'] # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # http://docs.readthedocs.org/en/latest/theme.html#how-do-i-use-this-locally-and-on-read-the-docs # on_rtd is whether we are on readthedocs.org on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # otherwise, readthedocs.org uses their theme by default, so no need to specify it # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'Certbotdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Certbot.tex', u'Certbot Documentation', u'Certbot Project', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'certbot', u'Certbot Documentation', [project], 7), ('man/certbot', 'certbot', u'certbot script documentation', [project], 1), ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Certbot', u'Certbot Documentation', u'Certbot Project', 'Certbot', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False intersphinx_mapping = { 'python': ('https://docs.python.org/', None), 'acme': ('https://acme-python.readthedocs.org/en/latest/', None), } certbot-0.27.0/docs/make.bat0000644000175000017500000001612613344054434016001 0ustar ericaerica00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 2> nul if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\LetsEncrypt.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\LetsEncrypt.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end certbot-0.27.0/docs/ciphers.rst0000644000175000017500000003751613344054434016571 0ustar ericaerica00000000000000============ Ciphersuites ============ .. contents:: Table of Contents :local: .. _ciphersuites: Introduction ============ Autoupdates ----------- Within certain limits, TLS server software can choose what kind of cryptography to use when a client connects. These choices can affect security, compatibility, and performance in complex ways. Most of these options are independent of a particular certificate. Certbot tries to provide defaults that we think are most useful to our users. As described below, Certbot will default to modifying server software's cryptographic settings to keep these up-to-date with what we think are appropriate defaults when new versions of the Certbot are installed (for example, by an operating system package manager). When this feature is implemented, this document will be updated to describe how to disable these automatic changes. Cryptographic choices --------------------- Software that uses cryptography must inevitably make choices about what kind of cryptography to use and how. These choices entail assumptions about how well particular cryptographic mechanisms resist attack, and what trade-offs are available and appropriate. The choices are constrained by compatibility issues (in order to interoperate with other software, an implementation must agree to use cryptographic mechanisms that the other side also supports) and protocol issues (cryptographic mechanisms must be specified in protocols and there must be a way to agree to use them in a particular context). The best choices for a particular application may change over time in response to new research, new standardization events, changes in computer hardware, and changes in the prevalence of legacy software. Much important research on cryptanalysis and cryptographic vulnerabilities is unpublished because many researchers have been working in the interest of improving some entities' communications security while weakening, or failing to improve, others' security. But important information that improves our understanding of the state of the art is published regularly. When enabling TLS support in a compatible web server (which is a separate step from obtaining a certificate), Certbot has the ability to update that web server's TLS configuration. Again, this is *different from the cryptographic particulars of the certificate itself*; the certificate as of the initial release will be RSA-signed using one of Let's Encrypt's 2048-bit RSA keys, and will describe the subscriber's RSA public key ("subject public key") of at least 2048 bits, which is used for key establishment. Note that the subscriber's RSA public key can be used in a wide variety of key establishment methods, most of which do not use RSA directly for key exchange, but only for authenticating the server! For example, in DHE and ECDHE key exchanges, the subject public key is just used to sign other parameters for authentication. You do not have to "use RSA" for other purposes just because you're using an RSA key for authentication. The certificate doesn't specify other cryptographic or ciphersuite particulars; for example, it doesn't say whether or not parties should use a particular symmetric algorithm like 3DES, or what cipher modes they should use. All of these details are negotiated between client and server independent of the content of the ciphersuite. The Let's Encrypt project hopes to provide useful defaults that reflect good security choices with respect to the publicly-known state of the art. However, the Let's Encrypt certificate authority does *not* dictate end-users' security policy, and any site is welcome to change its preferences in accordance with its own policy or its administrators' preferences, and use different cryptographic mechanisms or parameters, or a different priority order, than the defaults provided by Certbot. If you don't use Certbot to configure your server directly, because the client doesn't integrate with your server software or because you chose not to use this integration, then the cryptographic defaults haven't been modified, and the cryptography chosen by the server will still be whatever the default for your software was. For example, if you obtain a certificate using *standalone* mode and then manually install it in an IMAP or LDAP server, your cryptographic settings will not be modified by the client in any way. Sources of defaults ------------------- Initially, Certbot will configure users' servers to use the cryptographic defaults recommended by the Mozilla project. These settings are well-reasoned recommendations that carefully consider client software compatibility. They are described at https://wiki.mozilla.org/Security/Server_Side_TLS and the version implemented by Certbot will be the version that was most current as of the release date of each client version. Mozilla offers three separate sets of cryptographic options, which trade off security and compatibility differently. These are referred to as the "Modern", "Intermediate", and "Old" configurations (in order from most secure to least secure, and least-backwards compatible to most-backwards compatible). The client will follow the Mozilla defaults for the *Intermediate* configuration by default, at least with regards to ciphersuites and TLS versions. Mozilla's web site describes which client software will be compatible with each configuration. You can also use the Qualys SSL Labs site, which Certbot will suggest when installing a certificate, to test your server and see whether it will be compatible with particular software versions. It will be possible to ask Certbot to instead apply (and track) Modern or Old configurations. The Let's Encrypt project expects to follow the Mozilla recommendations in the future as those recommendations are updated. (For example, some users have proposed prioritizing a new ciphersuite known as ``0xcc13`` which uses the ChaCha and Poly1305 algorithms, and which is already implemented by the Chrome browser. Mozilla has delayed recommending ``0xcc13`` over compatibility and standardization concerns, but is likely to recommend it in the future once these concerns have been addressed. At that point, Certbot would likely follow the Mozilla recommendations and favor the use of this ciphersuite as well.) The Let's Encrypt project may deviate from the Mozilla recommendations in the future if good cause is shown and we believe our users' priorities would be well-served by doing so. In general, please address relevant proposals for changing priorities to the Mozilla security team first, before asking the Certbot developers to change Certbot's priorities. The Mozilla security team is likely to have more resources and expertise to bring to bear on evaluating reasons why its recommendations should be updated. The Let's Encrypt project will entertain proposals to create a *very* small number of alternative configurations (apart from Modern, Intermediate, and Old) that there's reason to believe would be widely used by sysadmins; this would usually be a preferable course to modifying an existing configuration. For example, if many sysadmins want their servers configured to track a different expert recommendation, Certbot could add an option to do so. Resources for recommendations ----------------------------- In the course of considering how to handle this issue, we received recommendations with sources of expert guidance on ciphersuites and other cryptographic parameters. We're grateful to everyone who contributed suggestions. The recommendations we received are available under Feedback_. Certbot users are welcome to review these authorities to better inform their own cryptographic parameter choices. We also welcome suggestions of other resources to add to this list. Please keep in mind that different recommendations may reflect different priorities or evaluations of trade-offs, especially related to compatibility! Changing your settings ---------------------- This will probably look something like .. code-block:: shell certbot --cipher-recommendations mozilla-secure certbot --cipher-recommendations mozilla-intermediate certbot --cipher-recommendations mozilla-old to track Mozilla's *Secure*, *Intermediate*, or *Old* recommendations, and .. code-block:: shell certbot --update-ciphers on to enable updating ciphers with each new Certbot release, or .. code-block:: shell certbot --update-ciphers off to disable automatic configuration updates. These features have not yet been implemented and this syntax may change when they are implemented. TODO ---- The status of this feature is tracked as part of issue #1123 in our bug tracker. https://github.com/certbot/certbot/issues/1123 Prior to implementation of #1123, the client does not actually modify ciphersuites (this is intended to be implemented as a "configuration enhancement", but the only configuration enhancement implemented so far is redirecting HTTP requests to HTTPS in web servers, the "redirect" enhancement). The changes here would probably be either a new "ciphersuite" enhancement in each plugin that provides an installer, or a family of enhancements, one per selectable ciphersuite configuration. Feedback ======== We receive lots of feedback on the type of ciphersuites that Let's Encrypt supports and list some collated feedback below. This section aims to track suggestions and references that people have offered or identified to improve the ciphersuites that Let's Encrypt enables when configuring TLS on servers. Because of the Chatham House Rule applicable to some of the discussions, people are *not* individually credited for their suggestions, but most suggestions here were made or found by other people, and I thank them for their contributions. Some people provided rationale information mostly having to do with compatibility of particular user-agents (especially UAs that don't support ECC, or that don't support DH groups > 1024 bits). Some ciphersuite configurations have been chosen to try to increase compatibility with older UAs while allowing newer UAs to negotiate stronger crypto. For example, some configurations forego forward secrecy entirely for connections from old UAs, like by offering ECDHE and RSA key exchange, but no DHE at all. (There are UAs that can fail the negotiation completely if a DHE ciphersuite with prime > 1024 bits is offered.) References ---------- RFC 7575 ~~~~~~~~ IETF has published a BCP document, RFC 7525, "Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS)" https://datatracker.ietf.org/doc/rfc7525/ BetterCrypto.org ~~~~~~~~~~~~~~~~ BetterCrypto.org, a collaboration of mostly European IT security experts, has published a draft paper, "Applied Crypto Hardening" https://bettercrypto.org/static/applied-crypto-hardening.pdf FF-DHE Internet-Draft ~~~~~~~~~~~~~~~~~~~~~ Gillmor's Internet-Draft "Negotiated Discrete Log Diffie-Hellman Ephemeral Parameters for TLS" is being developed at the IETF TLS WG. It advocates using *standardized* DH groups in all cases, not individually-chosen ones (mostly because of the Triple Handshake attack which can involve maliciously choosing invalid DH groups). The draft provides a list of recommended groups, with primes beginning at 2048 bits and going up from there. It also has a new protocol mechanism for agreeing to use these groups, with the possibility of backwards compatibility (and use of weaker DH groups) for older clients and servers that don't know about this mechanism. https://tools.ietf.org/html/draft-ietf-tls-negotiated-ff-dhe-10 Mozilla ~~~~~~~ Mozilla's general server configuration guidance is available at https://wiki.mozilla.org/Security/Server_Side_TLS Mozilla has also produced a configuration generator: https://mozilla.github.io/server-side-tls/ssl-config-generator/ Dutch National Cyber Security Centre ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Dutch National Cyber Security Centre has published guidance on "ICT-beveiligingsrichtlijnen voor Transport Layer Security (TLS)" ("IT Security Guidelines for Transport Layer Security (TLS)"). These are available only in Dutch at https://www.ncsc.nl/dienstverlening/expertise-advies/kennisdeling/whitepapers/ict-beveiligingsrichtlijnen-voor-transport-layer-security-tls.html I have access to an English-language summary of the recommendations. Keylength.com ~~~~~~~~~~~~~ Damien Giry collects recommendations by academic researchers and standards organizations about keylengths for particular cryptoperiods, years, or security levels. The keylength recommendations of the various sources are summarized in a chart. This site has been updated over time and includes expert guidance from eight sources published between 2000 and 2017. http://www.keylength.com/ NIST ~~~~ NISA published its "NIST Special Publication 800-52 Revision 1: Guidelines for the Selection, Configuration, and Use of Transport Layer Security (TLS) Implementations" http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-52r1.pdf and its "NIST Special Publication 800-57: Recommendation for Key Management – Part 1: General (Revision 3)" http://csrc.nist.gov/publications/nistpubs/800-57/sp800-57_part1_rev3_general.pdf ENISA ~~~~~ ENISA published its "Algorithms, Key Sizes and Parameters Report - 2013" https://www.enisa.europa.eu/activities/identity-and-trust/library/deliverables/algorithms-key-sizes-and-parameters-report WeakDH/Logjam ------------- The WeakDH/Logjam research has thrown into question the safety of some existing practice using DH ciphersuites, especially the use of standardized groups with a prime ≤ 1024 bits. The authors provided detailed guidance, including ciphersuite lists, at https://weakdh.org/sysadmin.html These lists may have been derived from Mozilla's recommendations. One of the authors clarified his view of the priorities for various changes as a result of the research at https://www.ietf.org/mail-archive/web/tls/current/msg16496.html In particular, he supports ECDHE and also supports the use of the standardized groups in the FF-DHE Internet-Draft mentioned above (which isn't clear from the group's original recommendations). Particular sites' opinions or configurations -------------------------------------------- Amazon ELB ~~~~~~~~~~ Amazon ELB explains its current ciphersuite choices at https://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-security-policy-table.html U.S. Government 18F ~~~~~~~~~~~~~~~~~~~ The 18F site (https://18f.gsa.gov/) is using :: ssl_ciphers 'kEECDH+ECDSA+AES128 kEECDH+ECDSA+AES256 kEECDH+AES128 kEECDH+AES256 kEDH+AES128 kEDH+AES256 DES-CBC3-SHA +SHA !aNULL !eNULL !LOW !MD5 !EXP !DSS !PSK !SRP !kECDH !CAMELLIA !RC4 !SEED'; Duraconf ~~~~~~~~ The Duraconf project collects particular configuration files, with an apparent focus on avoiding the use of obsolete symmetric ciphers and hash functions, and favoring forward secrecy while not requiring it. https://github.com/ioerror/duraconf Site scanning or rating tools ----------------------------- Qualys SSL Labs ~~~~~~~~~~~~~~~ Qualys offers the best-known TLS security scanner, maintained by Ivan Ristić. https://www.ssllabs.com/ Dutch NCSC ~~~~~~~~~~ The Dutch NCSC, mentioned above, has also made available its own site security scanner which indicates how well sites comply with the recommendations. https://en.internet.nl/ Java compatibility issue ------------------------ A lot of backward-compatibility concerns have to do with Java hard-coding DHE primes to a 1024-bit limit, accepting DHE ciphersuites in negotiation, and then aborting the connection entirely if a prime > 1024 bits is presented. The simple summary is that servers offering a Java-compatible DHE ciphersuite in preference to other Java-compatible ciphersuites, and then presenting a DH group with a prime > 1024 bits, will be completely incompatible with clients running some versions of Java. (This may also be the case with very old MSIE versions...?) There are various strategies for dealing with this, and maybe we can document the options here. certbot-0.27.0/examples/0002755000175000017500000000000013344054435015257 5ustar ericaerica00000000000000certbot-0.27.0/examples/cli.ini0000644000175000017500000000165713344054434016535 0ustar ericaerica00000000000000# This is an example of the kind of things you can do in a configuration file. # All flags used by the client can be configured here. Run Certbot with # "--help" to learn more about the available options. # # Note that these options apply automatically to all use of Certbot for # obtaining or renewing certificates, so options specific to a single # certificate on a system with several certificates should not be placed # here. # Use a 4096 bit RSA key instead of 2048 rsa-key-size = 4096 # Uncomment and update to register with the specified e-mail address # email = foo@example.com # Uncomment to use the standalone authenticator on port 443 # authenticator = standalone # standalone-supported-challenges = tls-sni-01 # Uncomment to use the webroot authenticator. Replace webroot-path with the # path to the public_html / webroot folder being served by your web server. # authenticator = webroot # webroot-path = /usr/share/nginx/html certbot-0.27.0/examples/generate-csr.sh0000755000175000017500000000132113344054434020167 0ustar ericaerica00000000000000#!/bin/sh # This script generates a simple SAN CSR to be used with Let's Encrypt # CA. Mostly intended for "auth --csr" testing, but, since it's easily # auditable, feel free to adjust it and use it on your production web # server. if [ "$#" -lt 1 ] then echo "Usage: $0 domain [domain...]" >&2 exit 1 fi domains="DNS:$1" shift for x in "$@" do domains="$domains,DNS:$x" done SAN="$domains" openssl req -config "${OPENSSL_CNF:-openssl.cnf}" \ -new -nodes -subj '/' -reqexts san \ -out "${CSR_PATH:-csr.der}" \ -keyout "${KEY_PATH:-key.pem}" \ -newkey rsa:2048 \ -outform DER # 512 or 1024 too low for Boulder, 2048 is smallest for tests echo "You can now run: certbot auth --csr ${CSR_PATH:-csr.der}" certbot-0.27.0/examples/openssl.cnf0000644000175000017500000000016213344054434017426 0ustar ericaerica00000000000000[ req ] distinguished_name = req_distinguished_name [ req_distinguished_name ] [ san ] subjectAltName=${ENV::SAN} certbot-0.27.0/examples/dev-cli.ini0000644000175000017500000000103213344054434017274 0ustar ericaerica00000000000000# Always use the staging/testing server - avoids rate limiting server = https://acme-staging-v02.api.letsencrypt.org/directory # This is an example configuration file for developers config-dir = /tmp/le/conf work-dir = /tmp/le/conf logs-dir = /tmp/le/logs # make sure to use a valid email and domains! email = foo@example.com domains = example.com text = True agree-tos = True debug = True # Unfortunately, it's not possible to specify "verbose" multiple times # (correspondingly to -vvvvvv) verbose = True authenticator = standalone certbot-0.27.0/examples/.gitignore0000644000175000017500000000004413344054434017242 0ustar ericaerica00000000000000# generate-csr.sh: /key.pem /csr.dercertbot-0.27.0/examples/plugins/0002755000175000017500000000000013344054435016740 5ustar ericaerica00000000000000certbot-0.27.0/examples/plugins/certbot_example_plugins.py0000644000175000017500000000153513344054434024231 0ustar ericaerica00000000000000"""Example Certbot plugins. For full examples, see `certbot.plugins`. """ import zope.interface from certbot import interfaces from certbot.plugins import common @zope.interface.implementer(interfaces.IAuthenticator) @zope.interface.provider(interfaces.IPluginFactory) class Authenticator(common.Plugin): """Example Authenticator.""" description = "Example Authenticator plugin" # Implement all methods from IAuthenticator, remembering to add # "self" as first argument, e.g. def prepare(self)... @zope.interface.implementer(interfaces.IInstaller) @zope.interface.provider(interfaces.IPluginFactory) class Installer(common.Plugin): """Example Installer.""" description = "Example Installer plugin" # Implement all methods from IInstaller, remembering to add # "self" as first argument, e.g. def get_all_names(self)... certbot-0.27.0/examples/plugins/setup.py0000644000175000017500000000062513344054434020452 0ustar ericaerica00000000000000from setuptools import setup setup( name='certbot-example-plugins', package='certbot_example_plugins.py', install_requires=[ 'certbot', 'zope.interface', ], entry_points={ 'certbot.plugins': [ 'example_authenticator = certbot_example_plugins:Authenticator', 'example_installer = certbot_example_plugins:Installer', ], }, ) certbot-0.27.0/setup.py0000644000175000017500000001017613344054435015156 0ustar ericaerica00000000000000import codecs import os import re from setuptools import find_packages, setup # Workaround for http://bugs.python.org/issue8876, see # http://bugs.python.org/issue8876#msg208792 # This can be removed when using Python 2.7.9 or later: # https://hg.python.org/cpython/raw-file/v2.7.9/Misc/NEWS if os.path.abspath(__file__).split(os.path.sep)[1] == 'vagrant': del os.link def read_file(filename, encoding='utf8'): """Read unicode from given file.""" with codecs.open(filename, encoding=encoding) as fd: return fd.read() here = os.path.abspath(os.path.dirname(__file__)) # read version number (and other metadata) from package init init_fn = os.path.join(here, 'certbot', '__init__.py') meta = dict(re.findall(r"""__([a-z]+)__ = '([^']+)""", read_file(init_fn))) readme = read_file(os.path.join(here, 'README.rst')) changes = read_file(os.path.join(here, 'CHANGES.rst')) version = meta['version'] # This package relies on PyOpenSSL, requests, and six, however, it isn't # specified here to avoid masking the more specific request requirements in # acme. See https://github.com/pypa/pip/issues/988 for more info. install_requires = [ 'acme>=0.26.0', # We technically need ConfigArgParse 0.10.0 for Python 2.6 support, but # saying so here causes a runtime error against our temporary fork of 0.9.3 # in which we added 2.6 support (see #2243), so we relax the requirement. 'ConfigArgParse>=0.9.3', 'configobj', 'cryptography>=1.2', # load_pem_x509_certificate 'josepy', 'mock', 'parsedatetime>=1.3', # Calendar.parseDT 'pyrfc3339', 'pytz', 'setuptools', 'zope.component', 'zope.interface', ] dev_extras = [ # Pin astroid==1.3.5, pylint==1.4.2 as a workaround for #289 'astroid==1.3.5', 'coverage', 'ipdb', 'pytest', 'pytest-cov', 'pytest-xdist', 'pylint==1.4.2', # upstream #248 'tox', 'twine', 'wheel', ] dev3_extras = [ 'mypy', 'typing', # for python3.4 ] docs_extras = [ 'repoze.sphinx.autointerface', # sphinx.ext.imgconverter 'Sphinx >=1.6', 'sphinx_rtd_theme', ] setup( name='certbot', version=version, description="ACME client", long_description=readme, # later: + '\n\n' + changes url='https://github.com/letsencrypt/letsencrypt', author="Certbot Project", author_email='client-dev@letsencrypt.org', license='Apache License 2.0', python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Environment :: Console :: Curses', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Security', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Networking', 'Topic :: System :: Systems Administration', 'Topic :: Utilities', ], packages=find_packages(exclude=['docs', 'examples', 'tests', 'venv']), include_package_data=True, install_requires=install_requires, extras_require={ 'dev': dev_extras, 'dev3': dev3_extras, 'docs': docs_extras, }, # to test all packages run "python setup.py test -s # {acme,certbot_apache,certbot_nginx}" test_suite='certbot', entry_points={ 'console_scripts': [ 'certbot = certbot.main:main', ], 'certbot.plugins': [ 'manual = certbot.plugins.manual:Authenticator', 'null = certbot.plugins.null:Installer', 'standalone = certbot.plugins.standalone:Authenticator', 'webroot = certbot.plugins.webroot:Authenticator', ], }, ) certbot-0.27.0/linter_plugin.py0000644000175000017500000000145513344054434016670 0ustar ericaerica00000000000000"""Certbot ACME PyLint plugin. http://docs.pylint.org/plugins.html """ from astroid import MANAGER from astroid import nodes def register(unused_linter): """Register this module as PyLint plugin.""" def _transform(cls): # fix the "no-member" error on instances of # letsencrypt.acme.util.ImmutableMap subclasses (instance # attributes are initialized dynamically based on __slots__) # TODO: this is too broad and applies to any tested class... if cls.slots() is not None: for slot in cls.slots(): cls.locals[slot.value] = [nodes.EmptyNode()] if cls.name == 'JSONObjectWithFields': # _fields is magically introduced by JSONObjectWithFieldsMeta cls.locals['_fields'] = [nodes.EmptyNode()] MANAGER.register_transform(nodes.Class, _transform) certbot-0.27.0/CHANGES.rst0000644000175000017500000000042413344054434015240 0ustar ericaerica00000000000000ChangeLog ========= To see the changes in a given release, view the issues closed in a given release's GitHub milestone: - `Past releases `_ - `Upcoming releases `_