CERTBOT(7)
π CERTBOT(7) β the certbot manual page, bestie edition π
okay so this is CERTBOT(7), the Certbot documentation. yes the whole thing. grab a snack π
β¨ NAME β¨
certbot β Certbot Documentation. that's it, that's the name. iconic behaviour honestly π
πΈ INTRODUCTION πΈ
Note: π«Ά to get started quickly, use the interactive installation guide <https://certbot.eff.org>.
ok so imagine a badge that says GitHub Actions nightly CI status β that's an image, and it links to <https://github.com/certbot/certbot/actions/workflows/nightly.yml>. and then another image: the EFF Certbot Logo. we love a logo π
Certbot is part of EFF's effort to encrypt the entire Internet. no big deal. just the whole 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?). like, are you actually google.com or are you lying to me rn π
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. slay β¨
Anyone who has gone through the trouble of setting up a secure website knows what a hassle getting and maintaining a certificate is. literally everyone. the struggle is real π 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. free. periodt. πΈ
π Getting Started π
the best way to get started is to use our interactive guide <https://certbot.eff.org>. it generates instructions based on your configuration settings. in most cases, you'll need root or administrator access <https://certbot.eff.org/faq/#does-certbot-require-root-administrator-privileges> to your web server to run Certbot. yes, the big permissions. π
Certbot is meant to be run directly on your web server on the command line, not on your personal computer. read that again bestie. your laptop is not the vibe here π
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. ask them, not us, iykyk.
π¦ Contributing π¦
If you'd like to contribute to this project please read Developer Guide <https://certbot.eff.org/docs/contributing.html>. we'd love to have you π«Ά
This project is governed by EFF's Public Projects Code of Conduct <https://www.eff.org/pages/eppcode>. be nice, it's the rules.
β Links β
here's the whole link drop, no gatekeeping:
- Documentation: <https://certbot.eff.org/docs>
- Software project: <https://github.com/certbot/certbot>
- Changelog: <https://github.com/certbot/certbot/blob/main/certbot/CHANGELOG.md>
- For Contributors: <https://certbot.eff.org/docs/contributing.html>
- For Users: <https://certbot.eff.org/docs/using.html>
- Main Website: <https://certbot.eff.org>
- Let's Encrypt Website: <https://letsencrypt.org>
- Community: <https://community.letsencrypt.org>
- ACME spec: RFC 8555 <https://tools.ietf.org/html/rfc8555>
- ACME working area in github (archived): <https://github.com/ietf-wg-acme/acme>
π WHAT IS A CERTIFICATE? π
ok so storytime π
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. literally the worst. not on our watch π
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. choose your own adventure π¦
See also: Re-creating and Updating Existing Certificates <#updating-certs>
π GET CERTBOT π
π Table of Contents π
- System Requirements
- Installation
- Snap (Recommended)
- Alternative 1: Docker
- Alternative 2: Pip
- Alternative 3: Third Party Distributions
- Certbot-Auto [Deprecated]
π§ System Requirements π§
- Linux, macOS, BSD and Windows
- Recommended root access on Linux/BSD / Required Administrator access on Windows
- Port 80 Open
Note: π«Ά Certbot is most useful when run with root privileges, because it is then able to automatically configure TLS/SSL for Apache and nginx. Certbot is meant to be run directly on a web server, normally by a system administrator. In most cases, running Certbot on your personal computer is not a useful option. The instructions below relate to installing and running Certbot on a server.
π Installation π
Unless you have very specific requirements, we kindly suggest that you use the installation instructions for your system found at <https://certbot.eff.org/instructions>. like, just go there, it's tailored to you π
π Snap (Recommended) π
Our instructions are the same across all systems that use Snap. You can find instructions for installing Certbot through Snap can be found at <https://certbot.eff.org/instructions> by selecting your server software and then choosing "snapd" in the "System" dropdown menu. dropdown supremacy.
Most modern Linux distributions (basically any that use systemd) can install Certbot packaged as a snap. Snaps are available for x86_64, ARMv7 and ARMv8 architectures. The Certbot snap provides an easy way to ensure you have the latest version of Certbot with features like automated certificate renewal preconfigured. auto-renewal preconfigured?? we love a low-effort win β¨
If you unable to use snaps, you can use an alternate method for installing certbot. (yes, that's the original wording, we keep the facts exactly as they are π«Ά)
π³ Alternative 1: Docker π³
Docker <https://docker.com> 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. sad but true π
Most users should use the instructions at certbot.eff.org <https://certbot.eff.org/instructions>. You should only use Docker if you are sure you know what you are doing and have a good reason to do so. main character energy only π₯
You should definitely read the Where are my certificates? <#where-certs> section, in order to know how to manage the certificates manually. Our ciphersuites page <ciphers.html> provides some information about recommended ciphersuites. If none of these make much sense to you, you should definitely use the installation method recommended for your system at certbot.eff.org <https://certbot.eff.org/instructions>, which enables you to use installer plugins that cover both of those hard topics. genuinely, no shame, use the recommended path π«Ά
If you're still not convinced and have decided to use this method, from the server that the domain you're requesting a certificate for resolves to, install Docker <https://docs.docker.com/engine/installation/>, then issue a command like the one found below. If you are using Certbot with the Standalone <#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.
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. manual labour, unfortunately π
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 DNS plugin documentation <#dns-plugins>. π
For more information about the layout of the /etc/letsencrypt directory, see Where are my certificates? <#where-certs>.
π Alternative 2: Pip π
Installing Certbot through pip is only supported on a best effort basis and when using a virtual environment. Instructions for installing Certbot through pip can be found at <https://certbot.eff.org/instructions> by selecting your server software and then choosing "pip" in the "System" dropdown menu. venv girlies rise πΈ
π¦ Alternative 3: Third Party Distributions π¦
Third party distributions exist for other specific needs. They often are maintained by these parties outside of Certbot and tend to rapidly fall out of date on LTS-style distributions. β οΈ heads up: they go stale fast.
π Certbot-Auto [Deprecated] π
We used to have a shell script named certbot-auto to help people install Certbot on UNIX operating systems, however, this script is no longer supported. rip bozo πͺ¦
Please remove certbot-auto. To do so, you need to do three things:
- If you added a cron job or systemd timer to automatically run
certbot-autoto renew your certificates, you should delete it. If you did this by following our instructions, you can delete the entry added to/etc/crontabby running a command likesudo sed -i '/certbot-auto/d' /etc/crontab. - Delete the
certbot-autoscript. If you placed it in/usr/local/binlike we recommended, you can delete it by runningsudo rm /usr/local/bin/certbot-auto. - Delete the Certbot installation created by
certbot-autoby runningsudo rm -rf /opt/eff.org.
and that's where part 1 wraps... but bestie we are SO not done, there's more coming π β¨
π¦ USER GUIDE π¦
Table of Contents <span>π</span>
okay so here's the map of the whole guide, bestie β pick your adventure:
- Certbot Commands
- Getting certificates (and choosing plugins)
- Apache
- Webroot
- Nginx
- Standalone
- DNS Plugins
- Manual
- Combining plugins
- Third-party plugins
- Managing certificates
- Re-creating and Updating Existing Certificates
- Changing a Certificate's Domains
- RSA and ECDSA keys
- Changing a certificate's key type
- Revoking certificates
- Revoking by account key or certificate private key
- Deleting certificates
- Safely deleting certificates
- Renewing certificates
- Renaming certificates
- Modifying the Renewal Configuration of Existing Certificates
- Certbot v2.3.0 and newer
- Certbot v2.2.0 and older
- Automated Renewals
- Setting up automated renewal
- Where are my certificates?
- Pre and Post Validation Hooks
- Changing the ACME Server
- Lock Files
- Configuration file
- Log Rotation
- Certbot command-line options
- Getting help
β¨ Certbot Commands β¨
So Certbot speaks in commands β also called "subcommands," because the girlies love a technicality β and each one asks it to do a specific lil job. Obtaining a certificate? Renewing? Revoking? There's a command for that. π
The most important and commonly-used commands get discussed all throughout this document, and if you want the exhaustive list, it's chilling near the end of the doc. No cap.
π«Ά Heads up: thecertbotscript on your web server might actually be namedletsencryptif your system is running an older package. So literally anywhere in these docs that you seecertbot, just swap in the correct name as needed. iykyk.
π₯ Getting certificates (and choosing plugins) π₯
Certbot helps you achieve two tasks. Two! Iconic behavior:
- Obtaining a certificate: automatically performing the required authentication steps to prove that you control the domain(s), saving the certificate to
/etc/letsencrypt/live/and renewing it on a regular schedule. - Optionally, installing that certificate to supported web servers (like Apache or nginx) and other kinds of servers. This is done by automatically modifying the configuration of your server in order to use the certificate.
So if you want to obtain a certificate and install it? Use the certbot run command β or just certbot, which is the same thing. Same energy, shorter typing. π
And if you just want to obtain the certificate without installing it anywhere, that's what the certbot certonly ("certificate only") command is for. It's giving minimal effort, maximal result.
Some example ways to use Certbot:
# Obtain and install a certificate:
certbot
# Obtain a certificate but don't install it:
certbot certonly
# You may specify multiple domains with -d and obtain and
# install different certificates by running Certbot multiple times:
certbot certonly -d example.com -d www.example.com
certbot certonly -d app.example.com -d api.example.com
To perform these tasks, Certbot will ask you to choose from a selection of authenticator and installer plugins. Which ones are appropriate depends entirely on what kind of server software you're running and plan to use your certificates with. Vibe check your own server first, bestie.
Authenticators are plugins which automatically perform the required steps to prove that you control the domain names you're trying to request a certificate for. An authenticator is always required to obtain a certificate. periodt. π
Installers are plugins which can automatically modify your web server's configuration to serve your website over HTTPS, using the certificates obtained by Certbot. An installer is only required if you want Certbot to install the certificate to your web server β so like, optional, but the upgrade is worth it.
Some plugins are both authenticators and installers, and it's possible to specify a distinct combination of authenticator and plugin. Mix and match, main character energy only. π
π§ The plugin lineup, ranked by me (not really, here's the actual details)
The original does this as a big table, but tables are for spreadsheets and we're in our group-chat era, so here's every row, same facts, cuter packaging. Auth = authenticator, Inst = installer.
apacheβ Auth:YΒ· Inst:YΒ· Automates obtaining and installing a certificate with Apache. Β· Challenge types (and port):http-01(https://datatracker.ietf.org/doc/html/rfc8555#section-8.3) (80)nginxβ Auth:YΒ· Inst:YΒ· Automates obtaining and installing a certificate with Nginx. Β· Challenge types (and port):http-01(https://datatracker.ietf.org/doc/html/rfc8555#section-8.3) (80)webrootβ Auth:YΒ· Inst:NΒ· Obtains a certificate by writing to the webroot directory of an already running webserver. Β· Challenge types (and port):http-01(https://datatracker.ietf.org/doc/html/rfc8555#section-8.3) (80)standaloneβ Auth:YΒ· Inst:NΒ· Uses a "standalone" webserver to obtain a certificate. Requires port 80 to be available. This is useful on systems with no webserver, or when direct integration with the local webserver is not supported or not desired. Β· Challenge types (and port):http-01(https://datatracker.ietf.org/doc/html/rfc8555#section-8.3) (80)DNS pluginsβ Auth:YΒ· Inst:NΒ· This category of plugins automates obtaining a certificate by 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. Β· Challenge types (and port):dns-01(https://datatracker.ietf.org/doc/html/rfc8555#section-8.4) (53)
β little recap just so it's loud and clear:apacheandnginxdo both jobs,webroot,standaloneand the DNS plugins are authenticators only, and if you're chasing a wildcard certificate from Let's Encrypt, the DNS plugins are literally the only door. π
manualβ authenticator:Y, installer:N. You get a cert by manually following instructions and doing the domain validation yourself, bestie. Certs made this way do not support autorenewal π β but you can turn autorenewal on by handing it an authentication hook script that automates the domain validation steps. Challenges:http-01(port 80) anddns-01(port 53).
Under the hood, every plugin is out here using one of several ACME protocol challenges to prove you actually control the domain β <https://datatracker.ietf.org/doc/html/rfc8555#section-8>. Your options are http-01 (<https://datatracker.ietf.org/doc/html/rfc8555#section-8.3>, which uses port 80) and dns-01 (<https://datatracker.ietf.org/doc/html/rfc8555#section-8.4>, which requires you to configure a DNS server on port 53 β and yeah, that's usually not the same machine as your webserver, no cap). A few plugins support more than one challenge type, and in that case you get to pick your fave with --preferred-challenges. π
There are also like a ton of third-party plugins out there. Below we're gonna go into detail on when each plugin hits and how to actually use it. π«Ά
πͺΆ Apache
The Apache plugin currently supports modern OSes based on Debian, Fedora, SUSE, Gentoo, CentOS and Darwin β peep the entrypoint here: <https://github.com/certbot/certbot/blob/main/certbot/src/certbot/_internal/plugins/apache/entrypoint.py>. This one automates both obtaining and installing certificates on an Apache webserver, which is honestly iconic of it. To specify this plugin on the command line, just include --apache. β¨
π Webroot
If you're running a local webserver and you can modify the content being served, and you'd rather not stop the webserver while the cert gets issued, the webroot plugin is your girl. Get a cert by including certonly and --webroot on the command line. You'll also need --webroot-path or -w with the top-level directory (the "web root") containing the files your webserver serves. For example, --webroot-path /var/www/html or --webroot-path /usr/share/nginx/html β those are two super 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 β and that could legit be a separate directory for each domain. When you request a certificate for multiple domains, each domain uses 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. iykyk π₯
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)"
Heads up bestie π¨ β to use the webroot plugin, your server must be configured to serve files from hidden directories. If/.well-knowngets treated specially by your webserver configuration, you might need to modify that configuration to make sure files inside/.well-known/acme-challengeare actually served by the webserver.
Under Windows, Certbot will generate a web.config file (if one doesn't already exist) in /.well-known/acme-challenge so that IIS will serve the challenge files even when they don't have an extension. π
π¦ Nginx
The Nginx plugin 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
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 doesn't rely on any other server software running on the machine where you obtain the certificate β it's giving independent main character energy. π
To obtain a certificate using a "standalone" webserver, use the standalone plugin by including certonly and --standalone on the command line. This plugin needs to bind to port 80 to perform domain validation, so you may need to stop your existing webserver. π¬
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 β so don't panic, that's literally normal. π
Use --<challenge-type>-address to explicitly tell Certbot which interface (and protocol) to bind.
π 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, one of Certbot's DNS plugins is the move. πΈ
These plugins are not included in a default Certbot installation and must be installed separately. They're available in many OS package managers, as Docker images, and as snaps. Visit <https://certbot.eff.org> to learn the best way to use the DNS plugins on your system.
Once installed, you can find documentation on how to use each plugin at:
certbot-dns-cloudflareβ <https://certbot-dns-cloudflare.readthedocs.io>certbot-dns-digitaloceanβ <https://certbot-dns-digitalocean.readthedocs.io>certbot-dns-dnsimpleβ <https://certbot-dns-dnsimple.readthedocs.io>certbot-dns-dnsmadeeasyβ <https://certbot-dns-dnsmadeeasy.readthedocs.io>certbot-dns-gehirnβ <https://certbot-dns-gehirn.readthedocs.io>certbot-dns-googleβ <https://certbot-dns-google.readthedocs.io>certbot-dns-linodeβ <https://certbot-dns-linode.readthedocs.io>certbot-dns-luadnsβ <https://certbot-dns-luadns.readthedocs.io>certbot-dns-nsoneβ <https://certbot-dns-nsone.readthedocs.io>certbot-dns-ovhβ <https://certbot-dns-ovh.readthedocs.io>certbot-dns-rfc2136β <https://certbot-dns-rfc2136.readthedocs.io>certbot-dns-route53β <https://certbot-dns-route53.readthedocs.io>certbot-dns-sakuracloudβ <https://certbot-dns-sakuracloud.readthedocs.io>
π Manual
If you'd like to obtain a certificate while running certbot on a machine other than your target webserver, or you want to perform the domain validation steps yourself, the manual plugin has you. It's hidden from the UI, but you can use it 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 completely different computer, wild, I know. π
The manual plugin can use either the http or the dns challenge. 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"
π Renewal with the manual plugin
Certificates created using --manual do not support automatic renewal unless you combine them with an authentication hook script (see the hooks section) via --manual-auth-hook, which automatically sets up the required HTTP and/or TXT challenges. π
If you can use one of the other plugins that supports autorenewal to create your certificate, doing so is highly recommended. Fr fr. π«Ά
To manually renew a certificate using --manual without hooks, repeat the exact same certbot --manual command you used to create the certificate originally. Since this will require you to copy and paste new HTTP files or DNS TXT records, the command cannot be automated with a cron job. Periodt. β
π Combining plugins
Sometimes you may want to specify a combination of distinct authenticator and installer plugins β honestly a power move. To do so, specify the authenticator plugin with --authenticator or -a, and the installer plugin with --installer or -i. Slay. β¨
Like, the whole point of splitting plugins into authenticator + installer is that you get to mix and match, bestie π pick whichever combo fits your setup β no cap.
For instance, you could create a certificate using the webroot plugin for authentication and the apache plugin for installation.
certbot run -a webroot -i apache -w /var/www/html -d example.com
See how that works? -a webroot handles the authentication side, -i apache handles the installation side, -w /var/www/html hands over the webroot path, and -d example.com says which domain we're doing all this for. Iconic. π
Or you could create a certificate using the manual plugin for authentication and the nginx plugin for installation. (Note that this certificate cannot be renewed automatically.)
certbot run -a manual -i nginx -d example.com
π«Ά careful with that one, bestie β because the manual plugin is doing the auth, this certificate cannot be renewed automatically. Not a vibe for long-term setups, fr fr.
But yeah β that's the energy of run: authenticator here, installer there, one cert at the end. Slay. β¨
There are also a whole bunch of third-party plugins for the client, made by other devs (not us!). Many of them are beta/experimental, but some are already in widespread use β and honestly? iconic of them:
heads up bestie: each entry has two flags βAuthandInst.Ymeans yes,Nmeans no. And yes, the notes column is where the personality lives.
haproxyβ <https://github.com/greenhost/certbot-haproxy> βAuth: Y Β·Inst: Y β Integration with the HAProxy load balancers3frontβ <https://github.com/dlapiduz/letsencrypt-s3front> βAuth: Y Β·Inst: Y β Integration with Amazon CloudFront distribution of S3 bucketsgandiβ <https://github.com/obynio/certbot-plugin-gandi> βAuth: Y Β·Inst: N β Obtain certificates via the Gandi LiveDNS APIvarnishβ <https://git.sesse.net/?p=letsencrypt-varnish-plugin> βAuth: Y Β·Inst: N β Obtain certificates via a Varnish serverexternal-authβ <https://github.com/EnigmaBridge/certbot-external-auth> βAuth: Y Β·Inst: Y β A plugin for convenient scriptingpritunlβ <https://github.com/kharkevich/letsencrypt-pritunl> βAuth: N Β·Inst: Y β Install certificates in pritunl distributed OpenVPN serversproxmoxβ <https://github.com/kharkevich/letsencrypt-proxmox> βAuth: N Β·Inst: Y β Install certificates in Proxmox Virtualization serversdns-standaloneβ <https://github.com/siilike/certbot-dns-standalone> βAuth: Y Β·Inst: N β Obtain certificates via an integrated DNS serverdns-ispconfigβ <https://github.com/m42e/certbot-dns-ispconfig> βAuth: Y Β·Inst: N β DNS Authentication using ISPConfig as DNS serverdns-cloudnsβ <https://github.com/inventage/certbot-dns-cloudns> βAuth: Y Β·Inst: N β DNS Authentication using ClouDNS APIdns-clouddnsβ <https://github.com/vshosting/certbot-dns-clouddns> βAuth: Y Β·Inst: N β DNS Authentication using CloudDNS APIdns-lightsailβ <https://github.com/noi/certbot-dns-lightsail> βAuth: Y Β·Inst: N β DNS Authentication using Amazon Lightsail DNS APIdns-inwxβ <https://github.com/oGGy990/certbot-dns-inwx/> βAuth: Y Β·Inst: Y β DNS Authentication for INWX through the XML APIdns-azureβ <https://github.com/terricain/certbot-dns-azure> βAuth: Y Β·Inst: N β DNS Authentication using Azure DNSdns-godaddyβ <https://github.com/miigotu/certbot-dns-godaddy> βAuth: Y Β·Inst: N β DNS Authentication using Godaddy DNSdns-yandexcloudβ <https://github.com/PykupeJIbc/certbot-dns-yandexcloud> βAuth: Y Β·Inst: N β DNS Authentication using Yandex Cloud DNSdns-bunnyβ <https://github.com/mwt/certbot-dns-bunny> βAuth: Y Β·Inst: N β DNS Authentication using BunnyDNSnjallaβ <https://github.com/chaptergy/certbot-dns-njalla> βAuth: Y Β·Inst: N β DNS Authentication for njallaDuckDNSβ <https://github.com/infinityofspace/certbot_dns_duckdns> βAuth: Y Β·Inst: N β DNS Authentication for DuckDNS- Porkbun β
https://github.com/infinityofspace/certbot_dns_porkbunβ flagsY,Nβ DNS Authentication for Porkbun - Infomaniak β
https://github.com/Infomaniak/certbot-dns-infomaniakβ flagsY,Nβ DNS Authentication using Infomaniak Domains API - dns-multi β
https://github.com/alexzorin/certbot-dns-multiβ flagsY,Nβ DNS authentication of 100+ providers using go-acme/lego - dns-dnsmanager β
https://github.com/stayallive/certbot-dns-dnsmanagerβ flagsY,Nβ DNS Authentication for dnsmanager.io - standalone-nfq β
https://github.com/alexzorin/certbot-standalone-nfqβ flagsY,Nβ HTTP Authentication that works with any webserver (Linux only) - dns-solidserver β
https://gitlab.com/charlyhong/certbot-dns-solidserverβ flagsY,Nβ DNS Authentication using SOLIDserver (EfficientIP) - dns-stackit β
https://github.com/stackitcloud/certbot-dns-stackitβ flagsY,Nβ DNS Authentication using STACKIT DNS - dns-ionos β
https://github.com/ionos-cloud/certbot-dns-ionos-cloudβ flagsY,Nβ DNS Authentication using IONOS Cloud DNS - dns-mijn-host β
https://github.com/mijnhost/certbot-dns-mijn-hostβ flagsY,Nβ DNS Authentication using mijn.host DNS - nginx-unit β
https://github.com/kea/certbot-nginx-unitβ flagsY,Yβ Automates obtaining and installing a certificate with Nginx Unit - dns-cdmon β
https://github.com/rascazzione/certbot-dns-cdmonβ flagsY,Nβ DNS Authentication using cdmon's API - dns-synergy-wholesale β
https://github.com/ALameLlama/certbot-dns-synergy-wholesaleβ flagsY,Nβ DNS Authentication using Synergy Wholesale DNS - pkcs12 β
https://github.com/nasa-gcn/certbot-pkcs12β flagsN,Yβ Install certificates as PKCS#12 archives - dns-hetzner-cloud β
https://github.com/rolschewsky/certbot-dns-hetzner-cloudβ flagsY,Nβ DNS Authentication for Hetzner Cloud DNS - dns-czechia β
https://github.com/CZECHIA-COM/certbot-dns-czechiaβ flagsY,Nβ DNS Authentication for czechia.com - dns-eurodns β
https://pypi.org/project/certbot-dns-eurodns/β flagsY,Nβ DNS Authentication for EuroDNS - dns-dnscale β
https://github.com/dnscaleou/certbot-dns-dnscaleβ flagsY,Nβ DNS Authenticator for DNScale - dns-feno β
https://github.com/mrerikcodes/certbot-dns-fenoβ flagsY,Nβ DNS Authentication using the FENO (feno.no) API for.nodomains
And that's the whole plugin board, bestie β eighteen more down, zero skipped π
If you're interested, you can also write your own plugin <#dev-plugin>. (yes, literally you. go be the plugin you want to see in the world β¨)
π Managing certificates π
Okay so you've got certs and now you're like "wait, what do I even have?" β relatable. 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 certificates:
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
Key Type: RSA
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. Heads up though: the certificate name cannot contain filepath separators (i.e. / or \, depending on the platform). Like, it's a name, not a whole path, bestie π
Example:
certbot certonly --cert-name example.com
πΈ 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. (yes, overlapping domains are fine, it's not a crime π«Ά)
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. main character energy: either you're updating your fave or debuting a whole new one β¨
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. (it's not being nosy, it's being thorough π
)
--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. slay, one cert, hand-picked, no cap π
--duplicateβ okay so this one tells Certbot to make a whole separate, unrelated certificate with the same domains as one you already have. It gets saved completely separately from the prior one β like, no relation, they're strangers. Most users will not need to issue this in normal circumstances, so don't just do it for funsies π--expandβ this one tells Certbot to update an existing certificate with a new one that contains all of the old domains plus one or more additional new domains. With the--expandoption, you use the-doption to specify all existing domains and one or more new ones.
Example:
certbot --expand -d existing.com,example.com,newdomain.com
If you prefer, you can specify the domains individually like this:
certbot --expand -d existing.com -d example.com -d newdomain.com
Consider using --cert-name instead of --expand, because it gives you way more control over which certificate is modified and it lets you remove domains as well as adding them. Queen behavior honestly π
--allow-subset-of-namesβ tells Certbot to keep going 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. Like, bestie, if one of your domains wandered off, this lets the rest still slay β¨
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. Heads up: the generation of a new certificate counts against several rate limits that are intended to prevent abuse of the ACME protocol, as described here <https://letsencrypt.org/docs/rate-limits/>. So don't go spam-generating certs, the limits are watching π
πΈ 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
Same command shape, different energy β it's giving "one tool, so many destinies" π¦
π RSA and ECDSA keys π
Certbot supports two certificate private key algorithms: rsa and ecdsa.
As of version 2.0.0, Certbot defaults to ECDSA secp256r1 (P-256) certificate private keys for all new certificates. Existing certificates will continue to renew using their existing key type, unless a key type change is requested. So no, your old certs aren't gonna spontaneously switch up on you π
The type of key used by Certbot can be controlled through the --key-type option. You can use the --elliptic-curve option to control the curve used in ECDSA certificates and the --rsa-key-size option to control the size of RSA keys.
Warning: If you obtain certificates using ECDSA keys, you should be careful not to downgrade to a Certbot version earlier than 1.10.0 where ECDSA keys were not supported. Downgrades like this are possible if you switch from something like the snaps or pip to packages provided by your operating system which often lag behind. Fr fr, do NOT do that β that's a one-way ticket to broken-cert city π
π Changing a certificate's key type π
Unless you are aware that you need to support very old HTTPS clients that are not supported by most sites, you can safely transition your site to use ECDSA keys instead of RSA keys. Glow-up era β¨
If you want to change a single certificate to use ECDSA keys, you'll need to create or renew a certificate while setting --key-type ecdsa on the command line:
certbot renew --key-type ecdsa --cert-name example.com --force-renewal
If you want to use ECDSA keys for all certificates in the future (including renewals of existing certificates), you can add the following line to Certbot's configuration file:
key-type = ecdsa
which will take effect upon the next renewal of each certificate. Set it and forget it, bestie π
π Revoking certificates π
If you need to revoke a certificate, use the revoke subcommand to do so.
A certificate may be revoked by providing its name (see certbot certificates) or by providing its path directly:
certbot revoke --cert-name example.com
certbot revoke --cert-path /etc/letsencrypt/live/example.com/cert.pem
If the certificate being revoked was obtained via the --staging, --test-cert or a non-default --server flag, that flag must be passed to the revoke subcommand. Yeah, it's gotta match β no mixing and matching your flags π
Note: After revocation, Certbot will (by default) ask whether you want to delete the certificate. Unless deleted, Certbot will try to renew revoked certificates the next time certbot renew runs. So likeβ¦ actually finish the job or it'll come back like a ghost π»
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-name example.com --reason keycompromise
π Revoking by account key or certificate private key π
By default, Certbot will try revoke the certificate using your ACME account key. If the certificate was created from the same ACME account, the revocation will be successful. Match made in heaven, works every time π
If you instead have the corresponding private key file to the certificate you wish to revoke, use --key-path to perform the revocation from any ACME account:
certbot revoke --cert-path /etc/letsencrypt/live/example.com/cert.pem --key-path /etc/letsencrypt/live/example.com/privkey.pem
ποΈ Deleting certificates ποΈ
If you need to delete a certificate, use the delete subcommand.
Note: Read this and the Safely deleting certificates sections carefully. This is an irreversible operation and must be done with care. Irreversible. Gone. Poof. No undo button, bestie π
Certbot does not automatically revoke a certificate before deleting it. If you're no longer using a certificate and don't plan to use it anywhere else, you may want to follow the instructions in Revoking certificates instead. Generally, there's no need to revoke a certificate if its private key has not been compromised, but you may still receive expiration emails from Let's Encrypt unless you revoke.
Note: Do not manually delete certificate files from inside/etc/letsencrypt/. Always use thedeletesubcommand. I'm serious β do NOT go in there withrm, that's how you break everything π₯
A certificate may be deleted by providing its name with --cert-name. You may find its name using certbot certificates.
Otherwise, you will be prompted to choose one or more certificates to delete:
certbot delete --cert-name example.com
# or to choose from a list:
certbot delete
π‘οΈ Safely deleting certificates π‘οΈ
Deleting a certificate without following the proper steps can result in a non-functioning server. Not the vibe check you want to fail π To safely delete a certificate, follow all the steps below to make sure that references to a certificate are removed from the configuration of any installed server software (Apache, nginx, Postfix, etc) before deleting the certificate.
To explain further, when installing a certificate, Certbot modifies Apache or nginx's configuration to load the certificate and its private key from the /etc/letsencrypt/live/ directory. Before deleting a certificate, it is necessary to undo that modification, by removing any references to the certificate from the webserver's configuration files.
Follow these steps to safely delete a certificate:
- Find all references to the certificate (substitute
example.comin the command for the name of the certificate you wish to delete):
sudo bash -c 'grep -R live/example.com /etc/{nginx,httpd,apache2}'
If there are no references found, skip directly to Step 4. Lucky you, shortcut unlocked β¨
If some references are found, they will look something like:
/etc/apache2/sites-available/000-default-le-ssl.conf:SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
/etc/apache2/sites-available/000-default-le-ssl.conf:SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
- You will need a self-signed certificate to replace the certificate you are deleting. The following command will generate one for you, saving the certificate at
/etc/letsencrypt/self-signed-cert.pemand its private key at/etc/letsencrypt/self-signed-privkey.pem:
sudo openssl req -nodes -batch -x509 -newkey rsa:2048 -keyout /etc/letsencrypt/self-signed-privkey.pem -out /etc/letsencrypt/self-signed-cert.pem -days 356
- For each reference found in Step 1, open the file in a text editor and replace the reference to the existing certificate with a reference to the self-signed certificate.
Continuing from the previous example, you would open /etc/apache2/sites-available/000-default-le-ssl.conf in a text editor and modify the two matching lines of text to instead say:
SSLCertificateFile /etc/letsencrypt/self-signed-cert.pem
SSLCertificateKeyFile /etc/letsencrypt/self-signed-privkey.pem
- It is now safe to delete the certificate. Do so by running:
sudo certbot delete --cert-name example.com
See? Four steps, fully safe, server still standing, you're still iconic π
π Renewing certificates π
See also: Most Certbot installations come with automatic renewal out of the box. See Automated Renewals for more details.
See also: Users of the Manual plugin should note that --manual certificates will not renew automatically, unless combined with authentication hook scripts. See Renewal with the manual plugin <#manual-renewal>.
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 which are ready for renewal. As of Certbot 4.0.0, a certificate is considered ready for renewal when less than 1/3rd of its lifetime remains. For certificates with a lifetime of 10 days or less, that threshold is 1/2 of the lifetime. Prior to Certbot 4.0.0 the threshold was a fixed 30 days. Numbers matter, memorize the fractions π
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. Run it every hour, it literally does not care, it's chill like that π
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 fails and exits with a non-zero exit code, Certbot will print that error to stderr but will still try to renew anyway. A failing hook doesn't directly make Certbot exit non-zero, but since Certbot exits non-zero when renewals fail, a bad hook that causes a renewal failure will indirectly land you a non-zero exit code. Also, hooks only run when a certificate is actually due for renewal, which means you can run that command all the time without your webserver getting stopped for no reason. Obsessed with the efficiency honestly. π
So when Certbot peeps that a cert is due for renewal, --pre-hook and --post-hook run before and after each renewal attempt. If you want your hook to only fire after a successful renewal, use --deploy-hook in a command like this one:
certbot renew --deploy-hook /path/to/deploy-hook-script
You can also drop hooks in as files in subdirectories of Certbot's configuration directory. Assuming your config directory is /etc/letsencrypt, any executable files hanging out in /etc/letsencrypt/renewal-hooks/pre, /etc/letsencrypt/renewal-hooks/deploy, and /etc/letsencrypt/renewal-hooks/post will run as pre, deploy, and post hooks respectively. These run in alphabetical order β and lowkey the detail here is that the ordering is determined by the byte value of the characters in their filenames, so it does not care about your locale. It's giving "no thoughts, just bytes" π«Ά
Before certbot 3.2.0, hooks in directories only ran when certs were renewed with the renew subcommand β but as of 3.2.0, they run for any subcommand. Glow-up.
Hooks you specify on the command line, in the configuration file, or in renewal configuration files run as usual after all the hooks in those directories. One tiny exception: if a hook specified elsewhere is literally just the path to an executable file in the hook directory of the same type (like, your pre-hook is the path to an executable in /etc/letsencrypt/renewal-hooks/pre), that file does not get run a second time. Anyway, you can stop Certbot from auto-running executables in those directories by adding --no-directory-hooks on the command line.
More info about hooks? Just run certbot --help renew. Slay.
If you're confident this command runs successfully with zero human intervention, you can add it to crontab β since certs are only renewed when they're determined to be near expiry, it's totally fine to run it on the regular, like every week or every day. In that case you probably want the -q or --quiet flag to silence everything except errors. Peace and quiet, periodt. π€«
If you're manually renewing all your certificates, --force-renewal may be your bestie: it makes the expiration time of the certificate(s) get ignored when considering renewal, and attempts to renew each and every installed certificate no matter how old it is. > Heads up: this form is not appropriate to run daily, because each certificate will be renewed every single day, which will quickly smack into the certificate authority rate limit. π
Starting with Certbot 2.7.0, certbot provides the environment variables RENEWED_DOMAINS and FAILED_DOMAINS to all post renewal hooks. These variables contain a space separated list of domains, and you can use them to figure out whether a renewal succeeded or failed as part of your post renewal hook. Chef's kiss. π
Note that options you pass to certbot renew apply to every certificate for which renewal is attempted β so like, certbot renew --rsa-key-size 4096 would try to replace every near-expiry certificate with an equivalent cert using a 4096-bit RSA public key. If a cert is successfully renewed using specified options, those options get saved and used for future renewals of that cert. It remembers. π§
An alternative form that gives you more fine-grained control over renewal (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 -n or --noninteractive to prevent it blocking on user input β which is super 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, so it renews and replaces the old certificate rather than grabbing a new one β and don't forget any www. domains, bestie!! Specifying a subset of the domains creates a new, separate certificate containing only those domains instead of replacing the original one. When run with a set of domains corresponding to an existing certificate, the certonly command attempts to renew that specific certificate. β¨
Please note the CA will send notification emails to the address you provide if you don't renew certificates that are about to expire. So yeah, answer your emails. π
Certbot is working hard to improve the renewal process, and we apologize for any inconvenience you encounter integrating these commands into your individual environment. We're doing our best out here π₯Ί
Note:certbot renewexit status will only be1if a renewal attempt failed. That meanscertbot renewexit status will be0if 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'll need to use--deploy-hook, because the exit status is0both on successful renewal and when renewal isn't necessary. Sneaky little0, istg. π
π·οΈ Renaming certificates
So certbot doesn't have an internal rename function, but you can rename certs by requesting a new certificate using certbot's --cert-name flag. Here's the whole saga:
- View certificates with
certbot certificates
The output might be something like:
Found the following certs:
Certificate Name: yourdomain.com-0001
Serial Number: 2ce74f4e2b822211dd7648ea26c8927bdef6
Key Type: ECDSA
Domains: yourdomain.com subdomain.yourdomain.com
Expiry Date: 2025-11-16 20:27:27+00:00 (INVALID: TEST_CERT)
Certificate Path: /etc/letsencrypt/live/yourdomain.com-0001/fullchain.pem
Private Key Path: /etc/letsencrypt/live/yourdomain.com-0001/privkey.pem
Certificate Name: yourdomain.com
Serial Number: 2c72aa8cf58aa9fe9a33208d82304642d9ed
Key Type: ECDSA
Domains: yourdomain.com
Expiry Date: 2025-11-16 19:22:47+00:00 (INVALID: TEST_CERT)
Certificate Path: /etc/letsencrypt/live/yourdomain.com/fullchain.pem
Private Key Path: /etc/letsencrypt/live/yourdomain.com/privkey.pem
In this example, we're renaming certificate yourdomain.com-0001 to yourdomain.com. Iconic swap. π¦
- If the name you want is already in use and you're not using that cert, delete it using the instructions in the Deleting certificates section.
You'll then have:
Found the following certs:
Certificate Name: yourdomain.com-0001
Serial Number: 2ce74f4e2b822211dd7648ea26c8927bdef6
Key Type: ECDSA
Domains: yourdomain.com subdomain.yourdomain.com
Expiry Date: 2025-11-16 20:27:27+00:00 (INVALID: TEST_CERT)
Certificate Path: /etc/letsencrypt/live/yourdomain.com-0001/fullchain.pem
Private Key Path: /etc/letsencrypt/live/yourdomain.com-0001/privkey.pem
- If you're not sure how you set the cert up initially, note the relevant configuration options by inspecting
/etc/letsencrypt/renewal/yourdomain.com-0001.conf
It'll look something like:
version = 4.2.0
archive_dir = /etc/letsencrypt/archive/yourdomain.com-0001
cert = /etc/letsencrypt/live/yourdomain.com-0001/cert.pem
privkey = /etc/letsencrypt/live/yourdomain.com-0001/privkey.pem
chain = /etc/letsencrypt/live/yourdomain.com-0001/chain.pem
fullchain = /etc/letsencrypt/live/yourdomain.com-0001/fullchain.pem
[renewalparams]
account = abcdef12345678910
server = https://acme-staging-v02.api.letsencrypt.org/directory
authenticator = standalone
key_type = ecdsa
post_hook = "echo 'shut down server'"
You'll want to note the authenticator, installer, server, any hooks, etc. Take notes bestie, this is the lore. π
- Create a new cert with the options and name you want by running
certbot certonly --cert-name yourdomain.com -d yourdomain.com -d otherdomain.com --any-other-options. The value for--cert-namecan be anything you want; by default it's the first domain listed on the cert. - Make sure any links to your certificates are updated. If you're using certbot to manage the installation of certs on your webserver, you can run
certbot install --cert-name yourdomain.com. - Restart your webserver, if applicable. π
- You can now delete the old certificate β again, using the Deleting certificates section.
π οΈ Modifying the Renewal Configuration of Existing Certificates
When creating a certificate, Certbot keeps track of all the relevant options chosen by the user. At renewal time, Certbot remembers these options and applies them once again. It's got a whole memory for this. π
Sometimes you'll need to change some of these options for future certificate renewals, and to do that you gotta follow these steps:
Certbot v2.3.0 and newer
The certbot reconfigure command can be used to change a certificate's renewal options. This command uses the new renewal options to perform a test renewal against the Let's Encrypt staging server. If that works out, the new renewal options get saved and will apply to future renewals. Validated and slayed. β
You'll need to specify the --cert-name, which you can find by running certbot certificates.
A list of common options that may be updated with the reconfigure command can be found by running certbot help reconfigure.
As a practical example: if you were using the webroot authenticator and had relocated your website to another directory, you can change the --webroot-path to the new directory using the following command:
certbot reconfigure --cert-name example.com --webroot-path /path/to/new/location
Certbot v2.2.0 and older
- Perform a dry run renewal with the amended options on the command line. This lets you confirm the change is valid and will result in successful future renewals. π§ͺ
- If the dry run is successful, perform a live renewal of the certificate. This persists the change for future renewals. If the certificate isn't due to expire yet, you'll need to force a renewal using
--force-renewal.
Note: Rate limits from the certificate authority may prevent you from performing multiple renewals in a short period of time. It is strongly recommended to perform the second step only once, when you've decided on what options should change. Don't be out here rage-renewing, bestie π
As a practical example, if you were using the webroot authenticator and had relocated your website to another directory, you would need to change the --webroot-path to the new directory. Following the above advice:
- Perform a dry-run renewal of the individual certificate with the amended options:
certbot renew --cert-name example.com --webroot-path /path/to/new/location --dry-run
- If the dry-run was successful, make the change permanent by performing a live renewal of the certificate with the amended options, including
--force-renewal:
certbot renew --cert-name example.com --webroot-path /path/to/new/location --force-renewal
--cert-name selects the particular certificate to be modified. Without this option, all certificates will be selected.
--webroot-path is the option intended to be changed. All other previously selected options will be kept the same and do not need to be included in the command.
For advanced certificate management tasks, it is also 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. These renewal configuration files are located at /etc/letsencrypt/renewal/CERTNAME.conf. If you choose to modify the renewal configuration file we advise you to make a backup of the file beforehand and test its validity with the certbot renew --dry-run command.
Warning: Manually modifying files under /etc/letsencrypt/renewal/ can damage them if done improperly and we do not recommend doing so. π«Ά like, pls back up first, bestie.
β¨ Automated Renewals β¨
Most Certbot installations come with automatic renewals preconfigured. This is done by means of a scheduled task which runs certbot renew periodically.
If you are unsure whether you need to configure automated renewal:
- Review the instructions for your system and installation method at
https://certbot.eff.org/instructions. They will describe how to set up a scheduled task, if necessary. If no step is listed, your system comes with automated renewal pre-installed, and you should not need to take any additional actions. - On Linux and BSD, you can check to see if your installation method has pre-installed a timer for you. To do so, look for the
certbot renewcommand in either your system's crontab (typically/etc/crontabor/etc/cron.*/*) or systemd timers (systemctl list-timers). - If you're still not sure, you can configure automated renewal manually by following the steps in the next section. Certbot has been carefully engineered to handle the case where both manual automated renewal and pre-installed automated renewal are set up.
π°οΈ Setting up automated renewal π°οΈ
If you think you may need to set up automated renewal, follow these instructions to set up a scheduled task to automatically renew your certificates in the background. If you are unsure whether your system has a pre-installed scheduled task for Certbot, it is safe to follow these instructions to create one.
Note: If you're using Windows, these instructions are not necessary as Certbot on Windows comes with a scheduled task for automated renewal pre-installed.
If you are using macOS and installed Certbot using Homebrew, follow the instructions at https://certbot.eff.org/instructions to set up automated renewal. The instructions below are not applicable on macOS.
Run the following line, which will add a cron job to /etc/crontab:
SLEEPTIME=$(awk 'BEGIN{srand(); print int(rand()*(3600+1))}'); echo "0 0,12 * * * root sleep $SLEEPTIME && certbot renew -q" | sudo tee -a /etc/crontab > /dev/null
If you needed to stop your webserver to run Certbot, you'll want to add pre and post hooks to stop and start your webserver automatically. For example, if your webserver is HAProxy, run the following commands to create the hook files in the appropriate directory:
sudo sh -c 'printf "#!/bin/sh\nservice haproxy stop\n" > /etc/letsencrypt/renewal-hooks/pre/haproxy.sh'
sudo sh -c 'printf "#!/bin/sh\nservice haproxy start\n" > /etc/letsencrypt/renewal-hooks/post/haproxy.sh'
sudo chmod 755 /etc/letsencrypt/renewal-hooks/pre/haproxy.sh
sudo chmod 755 /etc/letsencrypt/renewal-hooks/post/haproxy.sh
Congratulations, Certbot will now automatically renew your certificates in the background. π slay
If you are interested in learning more about how Certbot renews your certificates, see the Renewing certificates section above.
πΈ Where are my certificates? πΈ
All generated keys and issued certificates can be found in /etc/letsencrypt/live/$domain, where $domain is the certificate name (see the note below). 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: The certificate name$domainused in the path/etc/letsencrypt/live/$domainfollows this convention: - it is the name given to--cert-name, - if--cert-nameis not set by the user it is the first domain given to--domains, - if the first domain is a wildcard domain (eg.*.example.com) the certificate name will beexample.com, - if a name collision would occur with a certificate already namedexample.com, the new certificate name will be constructed using a numerical sequence asexample.com-001.
For historical reasons, the containing directories are created with permissions of 0700 meaning that certificates are accessible only to servers that run as the root user. If you will never downgrade to an older version of Certbot, then you can safely fix this using chmod 0755 /etc/letsencrypt/{live,archive}.
For servers that drop root privileges before attempting to read the private key file, you will also need to use chgrp and chmod 0640 to allow the server to read /etc/letsencrypt/live/$domain/privkey.pem.
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. π like genuinely, do not leak this one
Note: As of Certbot version0.29.0, private keys for new certificate default to0600. Any changes to the group mode or group owner (gid) of this file will be preserved on renewals.
This is what Apache needs for SSLCertificateKeyFile https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslcertificatekeyfile, and Nginx for ssl_certificate_key https://nginx.org/en/docs/http/ngx_http_ssl_module.html#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 https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslcertificatefile, and what Nginx needs for ssl_certificate https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate.
cert.pemandchain.pem(less common) βcert.pemcontains the server certificate by itself, andchain.pemcontains 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 timehttps://whatsmychaincert.com/. π
Apache < 2.4.8 needs these for SSLCertificateFile https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslcertificatefile. and SSLCertificateChainFile https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslcertificatechainfile, respectively.
If you're using OCSP stapling with Nginx >= 1.3.7, chain.pem should be provided as the ssl_trusted_certificate https://nginx.org/en/docs/http/ngx_http_ssl_module.html#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 usingopenssl. You can automate that with--deploy-hookif you're using automatic renewal.
πͺ 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_IDENTIFIER: The domain or IP address being authenticatedCERTBOT_VALIDATION: The validation stringCERTBOT_TOKEN: Resource name part of the HTTP-01 challenge (HTTP-01 only)CERTBOT_REMAINING_CHALLENGES: Number of challenges remaining after the current challengeCERTBOT_ALL_IDENTIFIERS: A comma-separated list of all identifiers challenged for the current certificate
Additionally for cleanup:
CERTBOT_AUTH_OUTPUT: Whatever the auth script wrote to stdout
Certbot also sets CERTBOT_DOMAIN and CERTBOT_ALL_DOMAINS to the same values as CERTBOT_IDENTIFIER and CERTBOT_ALL_IDENTIFIERS respectively for backwards compatibility, however, the variables names containing "identifier" are preferred since Certbot has added support for obtaining certificates for IP addresses. π«Ά
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
#!/bin/bash
echo $CERTBOT_VALIDATION > /var/www/htdocs/.well-known/acme-challenge/$CERTBOT_TOKEN
/path/to/http/cleanup.sh
#!/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
#!/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_IDENTIFIER" '.*\.\(.*\..*\)')
# 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_IDENTIFIER"
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_IDENTIFIER ];then
mkdir -m 0700 /tmp/CERTBOT_$CERTBOT_IDENTIFIER
fi
echo $ZONE_ID > /tmp/CERTBOT_$CERTBOT_IDENTIFIER/ZONE_ID
echo $RECORD_ID > /tmp/CERTBOT_$CERTBOT_IDENTIFIER/RECORD_ID
# Sleep to make sure the change has time to propagate over to DNS
sleep 25
Then the cleanup script, bestie β /path/to/dns/cleanup.sh:
#!/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_IDENTIFIER/ZONE_ID ]; then
ZONE_ID=$(cat /tmp/CERTBOT_$CERTBOT_IDENTIFIER/ZONE_ID)
rm -f /tmp/CERTBOT_$CERTBOT_IDENTIFIER/ZONE_ID
fi
if [ -f /tmp/CERTBOT_$CERTBOT_IDENTIFIER/RECORD_ID ]; then
RECORD_ID=$(cat /tmp/CERTBOT_$CERTBOT_IDENTIFIER/RECORD_ID)
rm -f /tmp/CERTBOT_$CERTBOT_IDENTIFIER/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
π Changing the ACME Server π
Okay so by default, Certbot hits up Let's Encrypt's production server, which lives at <https://acme-v02.api.letsencrypt.org/directory>. That's the real one, the one that gives you actual trusted certs π .
Wanna use a different CA? Totally doable β just hand Certbot --server on the command line, or drop it in a configuration file, and give it the URL of that server's ACME directory. Like, say you wanna vibe with Let's Encrypt's staging server instead β you'd tack --server https://acme-staging-v02.api.letsencrypt.org/directory onto your command line. Easy π.
Note, bestie, read this one:--dry-runuses the Let's Encrypt staging server β unless--serveris specified on the CLI or in thecli.iniconfiguration file. So take caution when using--dry-runwith a custom server, because it may cause real certificates to be issued and discarded. Yeah. Actual live certs. Just yeeted. π
If Certbot doesn't trust the SSL certificate that your ACME server is serving up, you can use the REQUESTS_CA_BUNDLE environment variable (docs: <https://requests.readthedocs.io/en/latest/user/advanced/#ssl-cert-verification>) to override the root certificates that Certbot trusts. Here's the tea: Certbot uses the requests library, and that library does not use the operating system's trusted root store. So make sure REQUESTS_CA_BUNDLE is set globally in the environment and not just on the CLI β otherwise scheduled renewal will not succeed. No cap, that one sneaks up on people π.
π Lock Files π
When it's processing a validation, Certbot writes a bunch of lock files on your system, and the whole point is to stop multiple instances from overwriting each other's changes. Which means: by default, two instances of Certbot literally cannot run in parallel. Periodt.
And since the directories Certbot uses are configurable, Certbot writes a lock file for every directory it uses. That includes Certbot's --work-dir, --logs-dir, and --config-dir. By default those are /var/lib/letsencrypt, /var/log/letsencrypt, and /etc/letsencrypt respectively. And bonus: if you're running Certbot with Apache or nginx, it will lock the configuration folder for that program too β which is typically also hanging out in the /etc directory πΈ.
Heads up: these lock files only stop other Certbot instances from using those directories β not other processes. So if you wanna run multiple instances of Certbot at the same time, give each one its own--work-dir,--logs-dir, and--config-dir. Different dirs per instance, iykyk β¨.
π Configuration file π
Certbot accepts a global configuration file that applies its options to all invocations of Certbot. Meanwhile, certificate-specific configuration choices get stored in the .conf files you'll find in /etc/letsencrypt/renewal. Peep the section Modifying the Renewal Configuration of Existing Certificates for more on tweaking certificate-specific options. Oh, and important: it is not recommended to modify those certificate-specific renewal configuration files manually π.
By default, no cli.ini file is created β though one may already exist if, say, you installed Certbot via a package manager. Once you've made one, you can point at it with certbot --config cli.ini (or the shorter -c cli.ini). Here's an example config file, chef's kiss:
# 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 ECC for the private key
key-type = ecdsa
elliptic-curve = secp384r1
# 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 80
# authenticator = standalone
# 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
# Uncomment to automatically agree to the terms of service of the ACME server
# agree-tos = true
# An example of using an alternate ACME server that uses EAB credentials
# server = https://acme.sectigo.com/v2/InCommonRSAOV
# eab-kid = somestringofstuffwithoutquotes
# eab-hmac-key = yaddayaddahexhexnotquoted
By default, these are the locations that get searched π΅οΈββοΈ:
/etc/letsencrypt/cli.ini$XDG_CONFIG_HOME/letsencrypt/cli.ini(or~/.config/letsencrypt/cli.iniif$XDG_CONFIG_HOMEis not set).
Since this config 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. Like, don't do it, bestie π. Also, because of how arguments in cli.ini are parsed, options that you wish to not be set should not be listed at all. Why? Because options set to false will instead be read as being set to true by older versions of Certbot β since they've been listed in the config file. Rude, but that's the vibe.
π Log Rotation π
By default, certbot stores status logs in /var/log/letsencrypt. And by default, certbot will begin rotating logs once there are 1000 logs in the log directory. Meaning: once 1000 files are in /var/log/letsencrypt, Certbot deletes the oldest one to make room for new logs ποΈβ¨.
Wanna change how many subsequent logs get kept? Pass your desired number to the command line flag --max-log-backups. And if you set that flag to 0, log rotation is disabled entirely β so certbot just appends to the same log file forever. Forever and ever, amen π.
Note: Some distributions β Debian and Ubuntu included β disable certbot's internal log rotation in favor of a more traditionallogrotatescript. So if you're using a distribution's packages and you wanna alter the log rotation, go check/etc/logrotate.d/for a certbot rotation script π.
π Certbot command-line options π
Certbot supports a lot of command line options. Here's the full list, straight from certbot --help all:
usage:
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-name or --cert-path)
delete Delete a certificate (supply --cert-name)
reconfigure Update a certificate's configuration (supply --cert-name)
manage your account:
register Create an ACME account
unregister Deactivate an ACME account
update_account Update an ACME account
show_account Display account details
--agree-tos Agree to the ACME server's Subscriber Agreement
-m EMAIL Email address for important account notifications
β¨ options β¨
Okay bestie, here comes the big pile of flags π β these are the ones that work everywhere, no matter which subcommand you're running.
-h,--helpβ show this help message and exit. The classic "help meeee" button π«Ά-c,--configCONFIG_FILE β path to config file. Default is/etc/letsencrypt/cli.iniand~/.config/letsencrypt/cli.ini(yes, both β it peeks at both).-v,--verboseβ This flag can be used multiple times to incrementally increase the verbosity of output, e.g.-vvv. Default:0. The way I stack these like bracelets π--max-log-backupsMAX_LOG_BACKUPS β Specifies the maximum number of backup logs that should be kept by Certbot's built in log rotation. Setting this flag to0disables log rotation entirely, causing Certbot to always append to the same log file. Default:1000. (Set it to 0 only if you love one giant chaotic log file, ngl π)-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. Perfect for cron jobs and for people who hate being perceived β¨--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 therenewsubcommand. Default:False.-d,--domains,--domainDOMAIN β Domain names to include. For multiple domains you can use multiple-dflags or enter a comma separated list of domains as a parameter. All domains will be included as Subject Alternative Names on the certificate. The first domain will be used as the certificate name, unless otherwise specified or if you already have a certificate with the same name. In the case of a name conflict, a number like-0001will be appended to the certificate name. Default:Ask. (First domain = main character energy, lowkey π)--ip-addressIP_ADDRESSES β IP addresses to include. For multiple IP addresses you can use multiple--ip-addressflags. All IP addresses will be included as Subject Alternative Names on the certificate. Default:[].--eab-kidEAB_KID β Key Identifier for External Account Binding. Default:None.--eab-hmac-keyEAB_HMAC_KEY β HMAC key for External Account Binding. Default:None.--eab-hmac-algEAB_HMAC_ALG β HMAC algorithm for External Account Binding. Default:HS256.--cert-nameCERTNAME β 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. Certificate name cannot contain filepath separators (i.e.'/'or'\', depending on the platform). To see certificate names, runcertbot 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 against the Let's Encrypt staging server, obtaining test (invalid) certificates but not saving them to disk. This can only be used with thecertonlyandrenewsubcommands. It may trigger webserver reloads to temporarily modify & roll back configuration files.--pre-hookand--post-hookcommands run by default.--deploy-hookcommands do not run, unless enabled by--run-deploy-hooks. The test server may be overridden with--server. Default:False. (Practice run era π no cap, always dry-run first)--debug-challengesβ After setting up challenges, wait for user input before submitting to CA. When used in combination with the-voption, the challenge URLs or FQDNs and their expected return values are shown. Default:False.--required-profileREQUIRED_PROFILE β Request the given profile name from the ACME server. If the ACME server returns an error, issuance (or renewal) will fail. For long-term reliability, settingpreferred_profileinstead may be preferable because it allows fallback to a default. Use this setting when renewal failure is preferable to fallback. Default:None.--preferred-profilePREFERRED_PROFILE β Request the given profile name from the ACME server, or fallback to default. If the given profile name exists in the ACME directory, use it to request a certificate. Otherwise, fall back to requesting a certificate without a profile (which means the CA will use its default profile). This allows renewals to succeed even if the CA deprecates and removes a given profile. Default:None. (Chill option, it's giving resilience π)--preferred-chainPREFERRED_CHAIN β Set the preferred certificate chain. If the CA offers multiple certificate chains, prefer the chain whose topmost certificate was issued from this Subject Common Name. If no match, the default offered chain will be used. Default:None.--preferred-challengesPREF_CHALLS β A sorted, comma delimited list of the preferred challenge to use during authorization with the most preferred challenge listed first (Eg,"dns"or"http,dns"). Not all plugins support all challenges. Seehttps://certbot.eff.org/docs/using.html#pluginsfor details. ACME Challenges are versioned, but if you pick"http"rather than"http-01", Certbot will select the latest version automatically. Default:[].--issuance-timeoutISSUANCE_TIMEOUT β This option specifies how long (in seconds) Certbot will wait for the server to issue a certificate. Default:90.--user-agentUSER_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/5.8.0 (certbot; 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. (Yeah it's a whole sentence, she contains multitudes π)--user-agent-commentUSER_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-agentis set. (Example:Foo-Wrapper/1.0) Default:None.
π€ automation π€
Flags for automating execution & other tweaks β aka the set-it-and-forget-it era of your life β
--keep-until-expiring,--keep,--reinstallβ so if the certificate you're asking for already matches one you've got? just keep the one you already have until it's actually due for renewal, bestie π (for therunsubcommand this literally means reinstall the existing cert). (default: Ask)--expandβ if your existing certificate is a strict subset of the names you're requesting, always expand it and replace it with the extra names tacked on. level up bestie β¨ (default: Ask)--versionβ show program's version number and exit. that's it, that's the whole vibe π--force-renewal,--renew-by-defaultβ if a certificate already exists for the domains you asked for, renew it right now, no cap, regardless of whether it's anywhere near expiry. (often--keep-until-expiringis the more appropriate move, ngl). also implies--expand. (default: False)--renew-with-new-domainsβ if a certificate already exists for the requested certificate name but it doesn't match the domains you're asking for, renew it now, regardless of whether it's near expiry. (default: False)--reuse-keyβ when renewing, use the same private key as the existing certificate. (default: False)--no-reuse-keyβ when renewing, do not use the same private key as the existing certificate. not reusing private keys is the default behavior of Certbot, so this is the "actually, undo that" option β you can use it to unset--reuse-keyon an existing certificate. (default: False)--new-keyβ when renewing or replacing a certificate, generate a fresh new private key, even if--reuse-keyis set on the existing certificate. heads up though: combining--new-keyand--reuse-keymeans the private key gets replaced and then reused in future renewals π (default: False)--allow-subset-of-namesβ when doing domain validation, don't call it a failure if authorizations can't be obtained for a strict subset of the requested domains. this is lowkey so useful for letting renewals for multiple domains succeed even when some domains no longer point at this system π«Ά this option can't 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)-q,--quietβ silence all output except errors. perfect for automation via cron π€ implies--non-interactive. (default: False)
π‘οΈ security
security parameters & server settings. the whole "keep me safe" section, let's go π₯
--rsa-key-size Nβ size of the RSA key. (default: 2048)--key-type {rsa,ecdsa}β type of generated private key. only *ONE* per invocation can be provided at this time, so pick your fighter π (default: ecdsa)--elliptic-curve Nβ the SECG elliptic curve name to use. please see RFC 8446 for supported values. (default: secp256r1)--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: redirect enabled for install and run, disabled for enhance)--no-redirectβ do not automatically redirect all HTTP traffic to HTTPS for the newly authenticated vhost. (default: redirect enabled for install and run, disabled for enhance)--hstsβ add theStrict-Transport-Securityheader to every HTTP response. forcing the browser to always use SSL for the domain. defends against SSL Stripping π‘οΈ (default: False)--uirβ add the"Content-Security-Policy: upgrade-insecure-requests"header to every HTTP response. forcing the browser to usehttps://for everyhttp://resource. (default: False)--staple-ocspβ enables OCSP Stapling. a valid OCSP response is stapled to the certificate that the server offers during TLS. (default: False)--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 the HTTP Strict Transport Security security header. (default: False)
π§ͺ testing
the following flags are meant for testing and integration purposes only. like, do not ship these to prod, bestie π
--run-deploy-hooksβ when performing a test run using--dry-runorreconfigure, run any applicable deploy hooks. this includes hooks set on the command line, saved in the certificate's renewal configuration file, or present in the renewal-hooks directory. to exclude directory hooks, use--no-directory-hooks. the hook(s) will only be run if the dry run succeeds, and will use the current active certificate, not the temporary test certificate acquired during the dry run. this flag is recommended when modifying the deploy hook usingreconfigure. (default: False)--test-cert,--stagingβ use the Let's Encrypt 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. (default: False)--no-verify-sslβ disable verification of the ACME server's certificate. the root certificates trusted by Certbot can be overridden by setting theREQUESTS_CA_BUNDLEenvironment variable. (default: False)--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: )--https-port HTTPS_PORTβ port used to serve HTTPS. this affects which port Nginx will listen on after a LE certificate is installed. (default: 443)--break-my-certsβ be willing to replace or renew valid certificates with invalid (testing/staging) certificates. (default: False)
okay the name literally says "break my certs" β it's for testing, so likeβ¦ don't be shocked when certs get broken π
π paths
flags for changing execution paths & servers. where everything lives, housekeeping era π§Ή
--cert-path CERT_PATHβ path to where certificate is saved (withcertonly --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. this is the "keep your house in order" corner of the page β¨
certificatesβ list certificates managed by Certbotdeleteβ clean up all files related to a certificaterenewβ renew all certificates (or one specified with--cert-name)revokeβ revoke a certificate specified with--cert-pathor--cert-namereconfigureβ update renewal configuration for a certificate specified by--cert-name
π run
options for obtaining & installing certificates. that's the whole description, we love a short king π
π― certonly
options for modifying how a certificate is obtained.
--deploy-hook DEPLOY_HOOKβ a command that gets run in a shell once for each certificate that gets successfully issued, and yes, that includes on subsequent renewals too π Unless you're using--disable-hook-validation, the first word of the command has to be the absolute pathname of an executable, or something found via thePATHenvironment variable. While this command runs, the shell variable$RENEWED_LINEAGEpoints at the config live subdirectory (like, for example,"/etc/letsencrypt/live/example.com") that holds the new certs and keys, and the shell variable$RENEWED_DOMAINSholds a space-delimited list of renewed certificate domains (for example,"example.com www.example.com"). (default: None)--csr CSRβ path to a Certificate Signing Request (CSR) in DER or PEM format. Heads up though: currently--csronly works with thecertonlysubcommand, that's just the rules bestie π (default: None)
π renew β the glow-up chapter
The renew subcommand will attempt to renew any certificates you previously obtained if they're close to expiring, then print you a lil summary of the results π By default, renew reuses the plugins and options that were used to obtain (or most recently renew) each certificate. You can test whether future renewals will actually succeed with --dry-run β highly recommend, no cap. Individual certificates can be renewed with the --cert-name option. And there are hooks available to run commands before and after renewal; more info on those lives at https://certbot.eff.org/docs/using.html#renewal π«Ά
--pre-hook PRE_HOOKβ a command to be run in a shell before obtaining any certificates. Unless--disable-hook-validationis used, the command's first word must be the absolute pathname of an executable or one found via thePATHenvironment variable. This one's intended primarily for renewal, where you can use it to temporarily shut down a webserver that might conflict with the standalone plugin π This will only be called if a certificate is actually going 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β a command to be run in a shell after attempting to obtain/renew certificates. Unless--disable-hook-validationis used, the command's first word must be the absolute pathname of an executable or one found via thePATHenvironment variable. 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)--disable-hook-validationβ ordinarily the commands you specify for--pre-hook/--post-hook/--deploy-hookget checked for validity, to see if the programs being run are in the$PATH, so mistakes get 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 flip this switch to disable it. (default: False)--no-directory-hooksβ disable running executables found in Certbot's hook directories. (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: False)
π certificates
List certificates managed by Certbot. That's it, that's the whole vibe π
ποΈ delete
Options for deleting a certificate.
π« revoke β the breakup era
Options for revocation of certificates.
--reason {unspecified,keycompromise,affiliationchanged,superseded,cessationofoperation}β specify the reason for revoking the certificate. (default:unspecified)--delete-after-revokeβ delete certificates after revoking them, along with all previous and later versions of those certificates. (default: Ask)--no-delete-after-revokeβ do not delete certificates after revoking them. This option should be used with caution because therenewsubcommand will attempt to renew undeleted revoked certificates π¬ like, the messiest possible outcome, fr fr. (default: Ask)
π register
Options for account registration.
-m,--email EMAILβ email used for registration and recovery contact. Use a comma to register multiple emails, ex:u1@example.com,u2@example.com. (default: Ask).--eff-emailβ share your e-mail address with EFF. (default: Ask)--no-eff-emailβ don't share your e-mail address with EFF. (default: Ask)
β»οΈ update_account
Options for account modification.
π unregister
Options for account deactivation.
--account ACCOUNT_IDβ account ID to use. (default: None)
π¦ install
Options for modifying how a certificate is deployed.
βͺ rollback
Options for rolling back server configuration changes.
--checkpoints Nβ revert configuration N number of checkpoints. (default: 1)
π§© plugins β the subcommand-options one
Options 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)
β¨ enhance
Helps to harden the TLS configuration by adding security enhancements to already existing configuration π she's doing security work, respect her.
π€ show_account
Options useful for the "show_account" subcommand:
π§ reconfigure
Common options that may be updated with the "reconfigure" subcommand:
π§© plugins β the plugin-selection one (yes, same name, different energy π«)
Plugin Selection: the 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 the options provided below. Running --help <plugin_name> 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--authenticatoror--installer. (default: Ask)-a,--authenticator AUTHENTICATORβ authenticator plugin name. (default: None)-i,--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) β "laborious" is their word, not mine π--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-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 are using DNS Made Easy for DNS). (default: False)--dns-gehirnβ obtain certificates using a DNS TXT record (if you are using Gehirn Infrastructure 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 β and real talk, bestie: the default values of the Apache plugin options change depending on the operating system Certbot is run on. (Please note that the default values of the Apache plugin options change depending on the operating system Certbot is run on.)
--apache-enmod APACHE_ENMODβ where the Apachea2enmodbinary lives (default:None)--apache-dismod APACHE_DISMODβ where the Apachea2dismodbinary lives (default:None)--apache-le-vhost-ext APACHE_LE_VHOST_EXTβ the SSL vhost configuration extension (default:-le-ssl.conf)--apache-server-root APACHE_SERVER_ROOTβ the Apache server root directory (default:/etc/apache2)--apache-vhost-root APACHE_VHOST_ROOTβ the Apache server VirtualHost configuration root (default:None)--apache-logs-root APACHE_LOGS_ROOTβ the 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 the installer handle enabling required modules for you (Only Ubuntu/Debian currently) (default:False)--apache-handle-sites APACHE_HANDLE_SITESβ let the installer handle enabling sites for you (Only Ubuntu/Debian currently) (default:False)--apache-ctl APACHE_CTLβ full path to the Apache control script (default:apache2ctl)--apache-bin APACHE_BINβ full path to theapache2/httpdbinary (default:None)
βοΈ 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-digitalocean
Obtain certificates 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). No cap.
--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 Infrastructure 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 Infrastructure 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 a Google Cloud DNS service account JSON file to use instead of relying on Application Default Credentials (ADC). (Seehttps://cloud.google.com/docs/authentication/application-default-credentialsfor information about ADC,https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccountfor information about creating a service account, andhttps://cloud.google.com/dns/access-control#permissions_and_rolesfor information about the permissions required to modify Cloud DNS records.) (default:None)--dns-google-project DNS_GOOGLE_PROJECTβ the ID of the Google Cloud project that the Google Cloud DNS managed zone(s) reside in. This will be determined automatically if not specified. (default:None)
π dns-linode
Obtain certificates 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:120)--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:120)--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). That's the whole entry for this one β no extra flags listed. Slay. π
πΈ 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_IDENTIFIER will always contain the domain or IP address 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. 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. For both authenticator and cleanup script, on HTTP-01 and DNS-01 challenges, $CERTBOT_REMAINING_CHALLENGES will be equal to the number of challenges that remain after the current one, and $CERTBOT_ALL_IDENTIFIERS contains a comma-separated list of all identifiers that are challenged for the current certificate. π«Ά
--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)
π nginx
Nginx Web Server plugin π
--nginx-server-root NGINX_SERVER_ROOTβ where your nginx server root lives, i.e. the directory it calls home. (default:/etc/nginxor/usr/local/etc/nginx, depends on your vibe)--nginx-ctl NGINX_CTLβ the path to the'nginx'binary, which gets used for'configtest'and for pulling the nginx version number. (default:nginx)--nginx-sleep-seconds NGINX_SLEEP_SECONDSβ how many seconds we wait around for nginx config changes to actually apply when it reloads. (default:1)
null:
The Null Installer. That's it, that's the whole thing. π«₯
standalone:
Okay so this one runs an HTTP server locally, right there on your machine, and it serves up the necessary validation files under the /.well-known/acme-challenge/ request path. It's the move when there's no HTTP server already running. Heads up though: HTTP challenge only, which means wildcards are not supported. π
webroot:
This one saves the necessary validation files into a .well-known/acme-challenge/ directory inside the webroot path you nominate. Important: a separate HTTP server has to already be running and serving files from that webroot path. Also HTTP challenge only β wildcards not supported. π«Ά
--webroot-path,-w WEBROOT_PATHβ the public_html / webroot path. You can drop this multiple times to handle different identifiers, and each identifier gets the webroot path that came right before 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β a JSON dictionary that maps identifiers to webroot paths. This implies-dor--ip-addressfor each entry. You may need to escape this from your shell, jsyk. E.g.:--webroot-map '{"eg1.is,m.eg1.is":"/www/eg1/", "eg2.is":"/www/eg2"}'. This option is merged with, but takes precedence over, your-w/-dentries. 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:{})
π¬ Getting help
If you're having problems, the recommendation is to post on the Let's Encrypt Community Forum β https://community.letsencrypt.org. Besties helping besties, periodt. π«Ά
And if you find a bug in the software, please do report it in the issue tracker at https://github.com/certbot/certbot/issues. Remember to give us as much information as possible:
- copy and paste the exact command line you 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 --versionoutput - your operating system, including the specific version
- specify which installation method you've chosen
π DEVELOPER GUIDE
π Table of Contents
- Getting Started
- Running a local copy of the client
- Find issues to work on
- Testing
- Running automated unit tests
- Running automated integration tests
- Running manual integration tests
- Running tests in CI
- Code components and layout
- Plugin-architecture
- Authenticators
- Installer
- Installer Development
- Writing your own plugin
- Writing your own plugin snap
- Coding style
- Use
certbot.compat.osinstead ofos - Mypy type annotations
- Submitting a pull request
- Asking for help
- Building the Certbot and DNS plugin snaps
- Updating the documentation
- Certbot's dependencies
- Updating dependency versions
- Choosing dependency versions
- macOS suggestions
π Getting Started
Certbot has the same system requirements when set up for development (#system-requirements, that section). 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 on 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. No cap. π
If you're using macOS, it is recommended to first check out the macOS suggestions section before continuing with the installation instructions below.
π§ 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:
git clone https://github.com/certbot/certbot
If you're running on a UNIX-like OS, you can run the following commands to install dependencies and set up a virtual environment where you can run Certbot.
Install and configure the OS system dependencies required to run Certbot. π
# For APT-based distributions (e.g. Debian, Ubuntu ...)
sudo apt update
sudo apt install python3-dev python3-venv libaugeas-dev gcc
# For RPM-based distributions (e.g. Fedora, CentOS ...)
# NB1: old distributions will use yum instead of dnf
# NB2: RHEL-based distributions use python3X instead of python3 (e.g. python38)
sudo dnf install python3 python3-devel augeas-devel gcc
# For macOS installations with Homebrew already installed and configured
# NB: CFLAGS are needed to compile and link to Augeas installed through
# Homebrew and some of our developer scripts expect GNU coreutils be first in
# your PATH. The commands below set this up for bash and zsh, but your
# instructions may be slightly different if you use an alternate shell.
brew install augeas coreutils gnu-sed
BREW_PREFIX=$(brew --prefix)
RC_LINES="export CFLAGS=\"\$CFLAGS -I$BREW_PREFIX/include -L$BREW_PREFIX/lib\"\n"
RC_LINES+="export PATH=\"$BREW_PREFIX/opt/coreutils/libexec/gnubin:"
RC_LINES+="$BREW_PREFIX/opt/gnu-sed/libexec/gnubin:\$PATH\"\n"
printf "$RC_LINES" >> ~/.bashrc # for bash
printf "$RC_LINES" >> ~/.zshrc # for zsh
Note: If you have trouble creating the virtual environment below, you may need to install additional dependencies. See the cryptography project's site at https://cryptography.io/en/latest/installation.html#building-cryptography-on-linux for more information.
Set up the Python virtual environment that will host your Certbot local instance. β¨
cd certbot
python3 tools/venv.py
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:
source venv/bin/activate
After running this command, certbot and development tools like ipdb3, 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 at https://virtualenv.pypa.io. π¦
π Find issues to work on
You can find the open issues in the github issue tracker at https://github.com/certbot/certbot/issues. If you're starting work on something, post a comment to let others know and seek feedback on your plan where appropriate. Communication is literally the whole thing, iykyk. π
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 coding style. No skipping steps, bestie.
π§ͺ Testing
You can test your code in several ways:
- running the automated unit tests,
- running the automated integration tests
- running an ad hoc manual integration test
β Running automated unit tests
To run all unittests, mypy, and lint:
tox
If you're working on a specific test and would like to run just that one:
pytest acme/src/acme/_internal/tests/messages_test.py # Use the test file you're working on
To run a specific test case within a file:
pytest acme/src/acme/_internal/tests/messages_test.py -k test_to_partial_json
For debugging, we recommend putting import ipdb; ipdb.set_trace() statements inside the source code, which will require adding the -s flag to pytest invocations. π
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. Like, fr fr, do not do that. π
π³ Running automated integration tests
Generally it is sufficient to open a pull request and let GitHub run integration tests for you. However, you may want to run them locally before submitting your pull request. You need Docker installed and working.
The tox environment integration will setup Pebble (https://github.com/letsencrypt/pebble), the Let's Encrypt ACME CA server for integration testing, then launch the Certbot integration tests.
With a user allowed to access your local Docker daemon, run:
tox run -e integration
Tests will be run using pytest. A test report and a code coverage report will be displayed at the end of the integration tests execution. Slay. π₯
π§ Running manual integration tests
You can also manually execute Certbot against a local instance of the Pebble (https://github.com/letsencrypt/pebble) ACME server. This is useful to verify that the modifications done to the code makes Certbot behave as expected.
To do so you need:
- Docker installed, and a user with access to the Docker client,
- an available local copy of Certbot.
The virtual environment set up with python3 tools/venv.py contains two CLI tools that can be used once the virtual environment is activated:
run_acme_server
- Starts a local instance of Pebble and runs in the foreground printing its logs.
- Press CTRL+C to stop this instance.
- This instance is configured to validate challenges against certbot executed locally.
Note: Some options are available to tweak the local ACME server. You can executerun_acme_server --helpto see the inline help of therun_acme_servertool.
certbot_test [ARGS...]
- Execute certbot with the provided arguments and other arguments useful for testing purposes, such as: verbose output, full tracebacks in case Certbot crashes, etc.
- Execution is preconfigured to interact with the Pebble CA started with
run_acme_server. π§ - Any arguments can be passed exactly the way you'd pass them to Certbot (eg.
certbot_test certonly -d test.example.com). β¨
Okay bestie, here's the typical workflow to verify that Certbot successfully issued a certificate using an HTTP-01 challenge on a machine with Python 3:
python3 tools/venv.py
source venv/bin/activate
run_acme_server &
certbot_test certonly --standalone -d test.example.com
# To stop Pebble, launch `fg` to get back the background job, then press CTRL+C
π§ͺ Running tests in CI π§ͺ
Certbot uses GitHub Actions to run continuous integration tests. If you're using our GitHub Actions setup, a branch whose name starts with test- will run all tests on that branch. no cap, that's the whole trick π«Ά
π¦ Code components and layout π¦
These are the components of the Certbot repo that actually get distributed to users:
acmeβ contains all protocol specific codecertbotβ main client codecertbot-apacheandcertbot-nginxβ client code to configure specific web serverscertbot-dns-*β client code to configure DNS providers
π 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 <https://github.com/certbot/certbot/blob/main/certbot/src/certbot/interfaces.py> and plugins/common.py <https://github.com/certbot/certbot/blob/main/certbot/src/certbot/plugins/common.py#L45>.
The main two plugin interfaces are Authenticator <#certbot.interfaces.Authenticator>, which implements various ways of proving domain control to a certificate authority, and Installer <#certbot.interfaces.Installer>, 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. π
π Authenticators π
Authenticators are plugins that prove control of a domain name by solving a challenge provided by the ACME server. ACME currently defines two types of challenges: HTTP and DNS, represented by classes in acme.challenges <https://acme-python.readthedocs.io/en/latest/api/challenges.html#module-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(identifier) 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. bye bestie, we don't leave mess π
π οΈ Installer π οΈ
Installer plugins exist to actually set up the certificate in a server, possibly tweaking 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 supported_enhancements() <#certbot.interfaces.Installer.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 80, but it cannot install certificates; a postfix plugin would be an installer but not an authenticator. it's giving "same vibe, different job" π
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). iykyk π«Ά
π§° Installer Development π§°
There are a few existing classes that may be beneficial while developing a new Installer <#certbot.interfaces.Installer>. 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 <#certbot.reverter.Reverter> class helpful in handling configuration checkpoints and rollback. literal lifesavers β¨
π§ Writing your own plugin π§
Note: the Certbot team is not currently accepting any new plugins, because we want to rethink our approach to the challenge and resolve some issues like #6464 <https://github.com/certbot/certbot/issues/6464>, #6503 <https://github.com/certbot/certbot/issues/6503>, and #6504 <https://github.com/certbot/certbot/issues/6504> first. In the meantime, you're welcome to release it as a third-party plugin. See certbot-dns-ispconfig <https://github.com/m42e/certbot-dns-ispconfig> for one example of that. π
The Certbot client supports dynamic discovery of plugins through the importlib.metadata entry points <https://importlib-metadata.readthedocs.io/en/latest/using.html#entry-points> using the certbot.plugins <#module-certbot.plugins> group. This way you can, for example, create a custom implementation of Authenticator <#certbot.interfaces.Authenticator> or the Installer <#certbot.interfaces.Installer> without having to merge it with the core upstream source code. An example is provided in the examples/plugins/ directory. obsessed, honestly π
While developing, you can install your plugin into a Certbot development virtualenv like this:
. venv/bin/activate
pip install -e examples/plugins/
certbot_test plugins
Your plugin should show up in the output of that last command. If it doesn't, it was not installed properly β go check yourself before you wreck yourself π
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. π
π Writing your own plugin snap π
If you'd like your plugin to be used alongside the Certbot snap, you will also have to publish your plugin as a snap. Plugin snaps are regular confined snaps, but normally do not provide any "apps" themselves. Plugin snaps export loadable Python modules to the Certbot snap.
When the Certbot snap runs, it will use its version of Python and prefer Python modules contained in its own snap over modules contained in external snaps. This means that your snap doesn't have to contain things like an extra copy of Python, Certbot, or their dependencies β but it also means that if you need a different version of a dependency than the one already installed in the Certbot snap, the Certbot snap will have to be updated. trade-offs, bestie π
Certbot plugin snaps expose their Python modules to the Certbot snap via a snap content interface <https://snapcraft.io/docs/content-interface> where certbot-1 is the value for the content attribute. The Certbot snap only uses this to find the names of connected plugin snaps, and it expects to find the Python modules to be loaded under lib/python3.12/site-packages/ in the plugin snap. This location is the default when using the core24 base snap <https://snapcraft.io/docs/base-snaps> and the python snapcraft plugin <https://snapcraft.io/docs/python-plugin>.
The Certbot snap also provides a separate content interface which you can use to get metadata about the Certbot snap using the content identifier metadata-1. π¦
The script used to generate the snapcraft.yaml files for our own externally snapped plugins can be found at <https://github.com/certbot/certbot/blob/main/tools/snap/generate_dnsplugins_snapcraft.sh>.
For more information on building externally snapped plugins, see the section on Building the Certbot and DNS plugin snaps.
Once you have created your own snap, if you have the snap file locally, it can be installed for use with Certbot by running:
snap install --classic certbot
snap set certbot trust-plugin-with-root=ok
snap install --dangerous your-snap-filename.snap
sudo snap connect certbot:plugin your-snap-name
sudo /snap/bin/certbot plugins
If everything worked, that last command should list your plugin in the list of plugins found by Certbot. Once your snap is published to the snap store, it will be installable through the name of the snap on the snap store without the --dangerous flag. And if you're also using Certbot's metadata interface, you can run sudo snap connect your-snap-name:your-plug-name-for-metadata certbot:certbot-metadata to connect your snap to it. slay π₯
π Coding style π
Please:
- Be consistent with the rest of the code.
- Read PEP 8 - Style Guide for Python Code <https://www.python.org/dev/peps/pep-0008>.
- Follow the Google Python Style Guide <https://google.github.io/styleguide/pyguide.html>, with the exception that we use Sphinx-style <https://www.sphinx-doc.org/> documentation:
def foo(arg):
"""Short description.
:param int arg: Some number.
:returns: Argument
:rtype: int
"""
return arg
- Remember to use
pylint. - You may consider installing a plugin for
editorconfig<https://editorconfig.org/> in your editor to prevent some linting warnings. your future self will thank you π«Ά - Please avoid
unittest.assertTrueorunittest.assertFalsewhen possible, and useassertEqualor a more specific assert. They give better messages when it's failing, and are generally more correct. fr fr, the error messages are so much better π
π« Use certbot.compat.os instead of os π«
Python's standard library os module lacks full support for several Windows security features about file permissions (eg. DACLs). However several files handled by Certbot (eg. private keys) need strongly restricted access on both Linux and Windows. π
To help with this, the certbot.compat.os module wraps the standard os module, and forbids usage of methods that lack support for these Windows security features.
As a developer, when working on Certbot or its plugins, you must use certbot.compat.os in every place you would need os (eg. from certbot.compat import os instead of import os). Otherwise the tests will fail when your PR is submitted. no cap, this one bites people π€
π¦ Mypy type annotations π¦
Certbot uses the mypy <https://mypy.readthedocs.io> static type checker. Python 3 natively supports official type annotations, which can then be tested for consistency using mypy. Mypy does some type checks even without type annotations; we can find bugs in Certbot even without a fully annotated codebase. iconic, honestly π
Okay so, Zulip wrote a great guide at https://blog.zulip.org/2016/10/13/static-types-in-python-oh-mypy/ 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 run -e mypy on a machine that has Python 3 installed.
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:
from OpenSSL import crypto
from OpenSSL import SSL
π Submitting a pull request
Steps:
- We recommend you talk with us in a GitHub issue or Mattermost before writing a pull request to ensure the changes you're making is something we have the time and interest to review.
- Write your code! When doing this, you should add mypy type annotations for any functions you add or modify. You can check that you've done this correctly by running
tox run -e mypyon a machine that has Python 3 installed. - Make sure your environment is set up properly and that you're in your virtualenv. You can do this by following the instructions in the Getting Started section.
- Run
tox run -e lintto check for pylint errors. Fix any errors. - Run
tox --skip-missing-interpretersto run all the tests we recommend developers run locally. The--skip-missing-interpretersargument ignores missing versions of Python needed for running the tests. Fix any errors. - If any documentation should be added or updated as part of the changes you have made, please include the documentation changes in your PR.
- Submit the PR. Once your PR is open, please do not force push to the branch containing your pull request to squash or amend commits. We use squash merges at https://github.com/blog/2141-squash-your-commits on PRs and rewriting commits makes changes harder to track between reviews.
- Did your tests pass on GitHub Actions? 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 Certbot channel in EFF's Mattermost instance for its open source projects as described below.
You can get involved with several of EFF's software projects such as Certbot at the EFF Open Source Contributor Chat Platform: https://opensource.eff.org/signup_user_complete/?id=6iqur37ucfrctfswrs14iscobw. By signing up for the EFF Open Source Contributor Chat Platform, you consent to share your personal information with the Electronic Frontier Foundation, which is the operator and data controller for this platform. The channels will be available both to EFF, and to other users of EFFOSCCP, who may use or disclose information in these channels outside of EFFOSCCP. EFF will use your information, according to the Privacy Policy at https://www.eff.org/policy, to further the mission of EFF, including hosting and moderating the discussions on this platform.
Use of EFFOSCCP is subject to the EFF Code of Conduct at https://www.eff.org/pages/eppcode. When investigating an alleged Code of Conduct violation, EFF may review discussion channels or direct messages.
π§ Building the Certbot and DNS plugin snaps
Instructions for how to manually build and run the Certbot snap and the externally snapped DNS plugins that the Certbot project supplies are located in the README file at https://github.com/certbot/certbot/tree/main/tools/snap.
πΈ Updating the documentation
Many of the packages in the Certbot repository have documentation in a docs/ directory. This directory is located under the top level directory for the package. For instance, Certbot's documentation is under certbot/docs.
To build the documentation of a package, make sure you have followed the instructions to set up a local copy of Certbot including activating the virtual environment. After that, cd to the docs directory you want to build and run the command:
make clean html
This would generate the HTML documentation in _build/html in your current docs/ directory.
π Certbot's dependencies
We attempt to pin all of Certbot's dependencies whenever we can for reliability and consistency. Some of the places we have Certbot's dependencies pinned include our snaps, Docker images, CI, and our development environments.
In most cases, the file where dependency versions are specified is tools/requirements.txt. The one exception to this is our "oldest" tests where tools/oldest_constraints.txt is used instead. The purpose of the "oldest" tests is to ensure Certbot continues to work with the oldest versions of our dependencies which we claim to support. The oldest versions of the dependencies we support should also be declared in our setup.py files to communicate this information to our users.
The choices of whether Certbot's dependencies are pinned and what file is used if they are should be automatically handled for you most of the time by Certbot's tooling. The way it works though is tools/pip_install.py (which many of our other tools build on) checks for the presence of environment variables. If CERTBOT_OLDEST is set to 1, tools/oldest_constraints.txt will be used as constraints for pip, otherwise, tools/requirements.txt is used as constraints.
β Updating dependency versions
tools/requirements.txt and tools/oldest_constraints.txt can be updated using tools/pinning/current/repin.sh and tools/pinning/oldest/repin.sh respectively. This works by using poetry to generate pinnings based on a Poetry project defined by the pyproject.toml file in the same directory as the script. In many cases, you can just run the script to generate updated dependencies, however, if you need to pin back packages or unpin packages that were previously restricted to an older version, you will need to modify the pyproject.toml file. The syntax used by this file is described at https://python-poetry.org/docs/pyproject/ and how dependencies are specified in this file is further described at https://python-poetry.org/docs/dependency-specification/.
If you want to learn more about the design used here, see tools/pinning/DESIGN.md in the Certbot repo.
π¦ Choosing dependency versions
When choosing dependency versions, we should choose whatever minimum versions simplify development of Certbot and our own distribution methods such as snaps, pip, and docker. Since these approaches have full access to PyPI, it's OK if the required packages declared in setup.py are quite new.
If this approach to development creates significant trouble for some of our users, we can revisit this decision and weigh their trouble against the difficulties involved in maintaining support for a wider range of package versions. When doing this, we should also be sure to consider the feasibility of users getting access to these newer packages on their system rather than changing our own approach here. Their OS distribution may be able to package it, especially in an alternate repository and/or for a different version of Python to help avoid conflicts with other packages on their system.
π macOS suggestions
If you're developing on macOS, before setting up your Certbot development environment, it is recommended you perform the following steps. None of this is required, but it is the approach used by all/most of the current Certbot developers on macOS as of writing this:
- Install Homebrew at https://brew.sh/. It is the most popular package manager on macOS by a wide margin and works well enough.
- Install pyenv at https://github.com/pyenv/pyenv, ideally through Homebrew by running
brew install pyenv. Using Homebrew's Python for Certbot development is annoying because it regularly updates and every time it does it breaks your virtual environments. Using Python from pyenv avoids this problem and gives you easy access to all versions of Python. - If you're using pyenv, make sure you've set up your shell for it by following instructions like https://github.com/pyenv/pyenv?tab=readme-ov-file#set-up-your-shell-environment-for-pyenv.
π PACKAGING GUIDE π
π Releases
okay so we release packages and upload them to PyPI (wheels AND source tarballs, we're thorough like that) π«Ά
- <https://pypi.org/project/acme/>
- <https://pypi.org/project/certbot/>
- <https://pypi.org/project/certbot-apache/>
- <https://pypi.org/project/certbot-nginx/>
- <https://pypi.org/project/certbot-dns-cloudflare/>
- <https://pypi.org/project/certbot-dns-digitalocean/>
- <https://pypi.org/project/certbot-dns-dnsimple/>
- <https://pypi.org/project/certbot-dns-dnsmadeeasy/>
- <https://pypi.org/project/certbot-dns-google/>
- <https://pypi.org/project/certbot-dns-linode/>
- <https://pypi.org/project/certbot-dns-luadns/>
- <https://pypi.org/project/certbot-dns-nsone/>
- <https://pypi.org/project/certbot-dns-ovh/>
- <https://pypi.org/project/certbot-dns-rfc2136/>
- <https://pypi.org/project/certbot-dns-route53/>
The following scripts are used in the process:
We use git tags to identify releases, using Semantic Versioning <https://semver.org/>. For example: v0.11.1.
Since version 1.21.0, our packages are cryptographically signed by one of four PGP keys, bestie β write these down, they're literally the whole trust chain π:
BF6BCFC89E90747B9A680FD7B6029E8500F7DB1686379B4F0AF371B50CD9E5FF3402831161D1D28020F201346BF8F3F455A73F9A780CC99432A28621F2871B4152AE13C49519111F447BF683AA3B26C3
These keys can be found on major key servers.
Releases before 1.21.0 were signed by the PGP key A2CFB51FA275A7286234E7B24D17C995CD9775F2 which can still be found on major key servers. (yes, the old key still exists, it's giving legacy icon energy π)
π Notes for package maintainers
- Please use our tagged releases, not
main! fr fr, do not package the live branch π - Do not package
certbot-compatibility-testas it's only used internally. - To run tests on our packages, you should use
pytestby running the commandpython -m pytest. Runningpytestdirectly may not work becausePYTHONPATHis not handled the same way and local modules may not be found by the test runner. (ask us how we know π) - If you'd like to include automated renewal in your package:
certbot renew -qshould be added tocrontaborsystemdtimer.- A random per-machine time offset should be included to avoid having a large number of your clients hit Let's Encrypt's servers simultaneously.
--preconfigured-renewalshould be included on the CLI or incli.inifor all invocations of Certbot, so that it can adjust its interactive output regarding automated renewal (Certbot >=1.9.0).
jwsis an internal script foracmemodule and it doesn't have to be packaged β it's mostly for debugging: you can use it asecho foo | jws sign | jws verify.- 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. π
π°οΈ BACKWARDS COMPATIBILITY
All Certbot components including acme <https://acme-python.readthedocs.io/>, Certbot, and non-third party plugins (#plugins) follow Semantic Versioning <https://semver.org/> both for its Python API and for the application itself. This means that we will not change behavior in a backwards incompatible way except in a new major version of the project. no cap, that's the deal β¨
Note: None of this applies to the behavior of Certbot distribution mechanisms such as our snaps (#snap-install) or OS packages whose behavior may change at any time. Semantic versioning only applies to the common Certbot components that are installed by various distribution methods. π«
For Certbot as an application, the command line interface and non-interactive behavior can be considered stable with two exceptions. The first is that no aspects of Certbot's console or log output should be considered stable and it may change at any time. The second is that Certbot's behavior should only be considered stable with certain files but not all. Files with which users should expect Certbot to maintain its current behavior with are:
/etc/letsencrypt/live/$domain/{cert,chain,fullchain,privkey}.pem, where$domainis the certificate name (see the Where are my certificates? section,#where-certs, for more details)- CLI configuration files (
#config-file) - Hook directories in
/etc/letsencrypt/renewal-hooks
Certbot's behavior with other files may change at any point.
Another area where Certbot should not be considered stable is its behavior when not run in non-interactive mode which also may change at any point.
In general, if we're making a change that we expect will break some users, we will bump the major version and will have warned about it in a prior release when possible. For our Python API, we will issue warnings using Python's warning module. For application level changes, we will print and log warning messages. β οΈ
π RESOURCES
Documentation: <https://certbot.eff.org/docs>
Software project: <https://github.com/certbot/certbot>
Changelog: <https://github.com/certbot/certbot/blob/main/certbot/CHANGELOG.md>
For Contributors: <https://certbot.eff.org/docs/contributing.html>
For Users: <https://certbot.eff.org/docs/using.html>
Main Website: <https://certbot.eff.org>
Let's Encrypt Website: <https://letsencrypt.org>
Community: <https://community.letsencrypt.org>
ACME spec: RFC 8555 <https://tools.ietf.org/html/rfc8555>
ACME working area in github (archived): <https://github.com/ietf-wg-acme/acme>
π§βπ» API DOCUMENTATION π§βπ»
π¦ certbot package
Certbot client. that's it, that's the package π
π¦ Subpackages
πͺ certbot.compat package
Compatibility layer to run certbot both on Linux and Windows.
This package contains all logic that needs to be implemented specifically for Linux and for Windows. Then the rest of certbot code relies on this module to be platform agnostic. one module to make everyone behave, iconic π
π§© Submodules
π certbot.compat.filesystem module
Compat module to handle files security on Windows and Linux.
quick legend so you don't get lost in the type soup, bestie β those type names in the signatures all link out to the Python docs: -strβ <https://docs.python.org/3/library/stdtypes.html#str> -intβ <https://docs.python.org/3/library/functions.html#int> -boolβ <https://docs.python.org/3/library/functions.html#bool> -Noneβ <https://docs.python.org/3/library/constants.html#None> -Trueβ <https://docs.python.org/3/library/constants.html#True> -Generatorβ <https://docs.python.org/3/library/typing.html#typing.Generator>
certbot.compat.filesystem.chmod(file_path: str, mode: int) -> None
Apply a POSIX mode on given file_path:
- for Linux, the POSIX mode will be directly applied using
chmod, - for Windows, the POSIX mode will be translated into a Windows DACL that make sense for Certbot context, and applied to the file using kernel calls.
The definition of the Windows DACL that correspond to a POSIX mode, in the context of Certbot, is explained at <https://github.com/certbot/certbot/issues/6356> and is implemented by the method _generate_windows_flags(). (yes, it's a whole saga, go read the issue π)
Parameters
file_path(str) β Path of the filemode(int) β POSIX mode to apply
certbot.compat.filesystem.umask(mask: int) -> int
Set the current numeric umask and return the previous umask. On Linux, the built-in umask method is used. On Windows, our Certbot-side implementation is used. π
Parameters
mask(int) β The user file-creation mode mask to apply.
Return type
int
Returns
The previous umask value.
certbot.compat.filesystem.temp_umask(mask: int) -> Generator[None, None, None]
Apply a umask temporarily, meant to be used in a with block. Uses the Certbot implementation of umask. π§
Parameters
mask(int) β The user file-creation mode mask to apply temporarily
certbot.compat.filesystem.copy_ownership_and_apply_mode(src: str, dst: str, mode: int, copy_user: bool, copy_group: bool) -> None
Copy ownership (user and optionally group on Linux) from the source to the destination, then apply given mode in compatible way for Linux and Windows. This replaces the os.chown command. π₯
Parameters
src(str) β Path of the source filedst(str) β Path of the destination filemode(int) β Permission mode to apply on the destination filecopy_user(bool) β Copy user ifTruecopy_group(bool) β Copy group ifTrueon Linux (has no effect on Windows)
certbot.compat.filesystem.copy_ownership_and_mode(src: str, dst: str, copy_user: bool = True, copy_group: bool = True) -> None
Copy ownership (user and optionally group on Linux) and mode/DACL from the source to the destination.
Parameters
src(str) β Path of the source filedst(str) β Path of the destination filecopy_user(bool) β copies the user over ifTruecopy_group(bool) β copies the group over ifTrueon Linux (and honestly has no effect on Windows, so don't come for me)
certbot.compat.filesystem.check_mode() π
certbot.compat.filesystem.check_mode(file_path: str, mode: int) -> bool
Checks whether the mode you handed it matches the actual permissions on that file. On Linux it's a straight-up direct comparison; on Windows your mode gets compared against the security model instead. Different vibes, same question: does this match?
Parameters π
file_path(str) β path of the filemode(int) β POSIX mode to test
Return type: bool
Returns: True if the POSIX mode matches the file permissions
certbot.compat.filesystem.check_owner() π«Ά
certbot.compat.filesystem.check_owner(file_path: str) -> bool
Is this file owned by the user currently running this? That's the whole quiz.
Parameters
file_path(str) β file path to check
Return type: bool
Returns: True if the given file is owned by the current user, False otherwise.
certbot.compat.filesystem.check_permissions() π₯
certbot.compat.filesystem.check_permissions(file_path: str, mode: int) -> bool
The combo move: checks that the file has the mode you asked for and that it's owned by the current user. Two birds, one function.
Parameters
file_path(str) β file path to checkmode(int) β POSIX mode to check
Return type: bool
Returns: True if the file has the correct mode and owner, False otherwise.
certbot.compat.filesystem.open() β¨
certbot.compat.filesystem.open(file_path: str, flags: int, mode: int = 511) -> int
It's a wrapper around the original os.open function, and its whole personality is making sure that on Windows the mode you gave it actually gets applied correctly. Note the default: mode: int = 511.
Parameters
file_path(str) β the file path to openflags(int) β flags to apply on the file while it's openedmode(int) β POSIX mode to apply on the file when opened; Python defaults will be applied ifNone
Returns: the file descriptor to the opened file
Return type: int
RaiseOSError(errno.EEXIST)if the file already exists andos.O_CREAT & os.O_EXCLare set, andOSError(errno.EACCES)on Windows if the file already exists and is a directory, andos.O_CREATis set. Read that twice bestie, the Windows one is a whole mood. π
certbot.compat.filesystem.makedirs() πΈ
certbot.compat.filesystem.makedirs(file_path: str, mode: int = 511) -> None
A rewrite of the original os.makedirs function that makes sure your mode is correctly applied on Windows. Default is 511, as is tradition.
Parameters
file_path(str) β the file path to openmode(int) β POSIX mode to apply on the leaf directory when it's created; Python defaults apply ifNone
certbot.compat.filesystem.mkdir() π¦
certbot.compat.filesystem.mkdir(file_path: str, mode: int = 511) -> None
Same energy as above but single-directory: a rewrite of the original os.mkdir function, guaranteeing that on Windows your mode is correctly applied. Default mode: int = 511.
Parameters
file_path(str) β the file path to openmode(int) β POSIX mode to apply on the directory when created; Python defaults apply ifNone
certbot.compat.filesystem.replace() π§
certbot.compat.filesystem.replace(src: str, dst: str) -> None
Renames a file to a destination path, and it handles the awkward situation where the destination already exists. No drama, it just deals with it.
Parameters
src(str) β the current file path.dst(str) β the new file path.
certbot.compat.filesystem.realpath() π
certbot.compat.filesystem.realpath(file_path: str) -> str
Finds the real path for the given path. It resolves symlinks β including recursive symlinks β and it's protected against symlinks that create an infinite loop. Genuinely iconic of it, tbh.
Parameters
file_path(str) β the path to resolve
Returns: the real path for the given path
Return type: str
certbot.compat.filesystem.readlink() π
certbot.compat.filesystem.readlink(link_path: str) -> str
Returns a string of the path that the symbolic link points to.
Parameters
link_path(str) β the symlink path to resolve
Returns: the path the symlink points to
Returns: str β yes, the docstring lists Returns twice, no I'm not fixing it, that's just how she is π
Raise ValueError if a long path (260> characters) is encountered on Windows. Count your characters, bestie.
certbot.compat.filesystem.is_executable() β
certbot.compat.filesystem.is_executable(path: str) -> bool
Simple vibe check: is path an executable file?
Parameters
path(str) β path to test
Returns: True if path is an executable file
Return type: bool
certbot.compat.filesystem.has_world_permissions() π
certbot.compat.filesystem.has_world_permissions(path: str) -> bool
Checks whether everybody/world has any right (read/write/execute) on a file, given its path. Any single one counts, so don't get cocky about your 600.
Parameters
path(str) β path to test
Returns: True if everybody/world has any right to the file
Return type: bool
certbot.compat.filesystem.compute_private_key_mode() π
certbot.compat.filesystem.compute_private_key_mode(old_key: str, base_mode: int) -> int
Calculates the POSIX mode to apply to a private key, given the previous private key. Lowkey the glow-up planner for your key permissions.
Parameters
old_key(str) β path to the previous private keybase_mode(int) β the minimum modes to apply to a private key
Returns: the POSIX mode to apply
Return type: int
certbot.compat.filesystem.has_same_ownership() π
certbot.compat.filesystem.has_same_ownership(path1: str, path2: str) -> bool
Returns True if two files have the same ownership, given their respective paths. On Windows, ownership is checked against the owner only, since files do not have a group owner there.
Parameters
path1(str) β path to the first filepath2(str) β path to the second file
Returns: True if both files have the same ownership, False otherwise
Return type: bool
certbot.compat.filesystem.has_min_permissions
certbot.compat.filesystem.has_min_permissions(path: str, min_mode: int) -> bool
okay so this one is literally a vibe check for your file permissions π
it looks at the file sitting at path and tells you whether it's got at least the permissions defined by the given minimal mode. That's it, that's the whole gig.
tiny caveat for the Windows girlies: on Windows, group permissions are ignored since files do not have a group owner. no group owner, no group perms to check, so we just don't π«Ά
Parameters
path(str) β path to the file to checkmin_mode(int) β the minimal permissions expected
Returns β True if the file matches the minimal permissions expectations, False otherwise
Return type β bool
certbot.compat.misc module
This compat module handles various platform specific calls that do not fall into one particular category. it's the miscellaneous drawer in the kitchen, bestie β random but essential β¨
raise_for_non_administrative_windows_rights
certbot.compat.misc.raise_for_non_administrative_windows_rights() -> None
On Windows, raise if current shell does not have the administrative rights. Do nothing on Linux. like, Linux is chilling, Windows is the one doing the security check at the door π
Raises errors.Error β If the current shell does not have administrative rights on Windows.
prepare_virtual_console
certbot.compat.misc.prepare_virtual_console() -> None
On Windows, ensure that Console Virtual Terminal Sequences are enabled. that's the thing that makes your terminal do pretty colors instead of oops-all-escape-codes π
readline_with_timeout
certbot.compat.misc.readline_with_timeout(timeout: float, prompt: str | None) -> str
Read user input to return the first line entered, or raise after specified timeout. it's giving "answer me before the timer runs out" energy β³
Parameters
timeout(float) β The timeout in seconds given to the user.prompt(str) β The prompt message to display to the user.
Returns β The first line entered by the user.
Return type β str
get_default_folder
certbot.compat.misc.get_default_folder(folder_type: str) -> str
Return the relevant default folder for the current OS. lowkey just "where do your files live on this machine" π
Parameters
folder_type(str) β The type of folder to retrieve (config,workorlogs)
Returns β The relevant default folder.
Return type β str
underscores_for_unsupported_characters_in_path
certbot.compat.misc.underscores_for_unsupported_characters_in_path(path: str) -> str
Replace unsupported characters in path for current OS by underscores. :param str path: the path to normalize :return: the normalized path :rtype: str
(yes those little :param:/:return: tags are literally in there, we keep the receipts π§Ύ)
execute_command_status
certbot.compat.misc.execute_command_status(cmd_name: str, shell_cmd: str, env: dict | None = None) -> tuple[int, str, str]
Run a command:
- on Linux command will be run by the standard shell selected with
subprocess.run(shell=True) - on Windows command will be run in a Powershell shell
This function returns the exit code, and does not log the result and output of the command. so like, it runs the thing and hands you back the receipts but doesn't gossip about them in the logs π€
Parameters
cmd_name(str) β the user facing name of the hook being runshell_cmd(str) β shell command to executeenv(dict) β environ to pass intosubprocess.run
Returns β tuple (int returncode, str stderr, str stdout)
certbot.compat.os module
This compat modules is a wrapper of the core os module that forbids usage of specific operations (e.g. chown, chmod, getuid) that would be harmful to the Windows file security model of Certbot. This module is intended to replace standard os module throughout certbot projects (except acme).
so bestie, think of it as the os module but with a bouncer at the door πͺπ certain calls are just not allowed in, for your own good.
This module has the same API as the os module in the Python standard library except for the functions defined below.
isort:skip_file
certbot.compat.os.access(*unused_args, **unused_kwargs)β Methodos.access()is forbiddencertbot.compat.os.chmod(*unused_args, **unused_kwargs)β Methodos.chmod()is forbiddencertbot.compat.os.chown(*unused_args, **unused_kwargs)β Methodos.chown()is forbiddencertbot.compat.os.fstat(*unused_args, **unused_kwargs)β Methodos.stat()is forbiddencertbot.compat.os.mkdir(*unused_args, **unused_kwargs)β Methodos.mkdir()is forbiddencertbot.compat.os.open(*unused_args, **unused_kwargs)β Methodos.open()is forbiddencertbot.compat.os.rename(*unused_args, **unused_kwargs)β Methodos.rename()is forbiddencertbot.compat.os.replace(*unused_args, **unused_kwargs)β Methodos.replace()is forbiddencertbot.compat.os.stat(*unused_args, **unused_kwargs)β Methodos.stat()is forbiddencertbot.compat.os.umask(*unused_args, **unused_kwargs)β Methodos.chmod()is forbiddencertbot.compat.os.makedirs(*unused_args, **unused_kwargs)β Methodos.makedirs()is forbidden
ik thefstatone saysos.stat()and theumaskone saysos.chmod()β that's exactly what the page says, so we're keeping it verbatim, no editing the source bestie π
certbot.display package
Certbot display utilities. this is the whole "make it look pretty and ask the human questions" department π
Submodules
certbot.display.ops module
Contains UI methods for LE user operations.
get_email
certbot.display.ops.get_email(invalid: bool = False, **kwargs: Any) -> str
Prompt for valid email address. we simply must have your email, it's the rules β¨
Parameters
invalid(bool) βTrueif an invalid address was provided by the user
Returns β e-mail address
Return type β str
Raises errors.Error β if the user cancels
choose_account
certbot.display.ops.choose_account(accounts: list[Account]) -> Account | None
Choose an account. pick your fighter π
Parameters
accounts(list) β Containing at least oneAccount
choose_values
certbot.display.ops.choose_values(values: list[str], question: str | None = None) -> list[str]
Display screen to let user pick one or multiple values from the provided list. multiple choice but make it cute π
Parameters
values(list) β Values to select fromquestion(str) β Question to ask to user while choosing values
Returns β List of selected values
Return type β list
choose_names
certbot.display.ops.choose_names(installer: Installer | None, question: str | None = None) -> list[str]
Display screen to select domains to validate. which of your domains are we doing today bestie πΈ
Parameters
installer(certbot.interfaces.Installer) β An installer objectquestion(str) β Overriding default question to ask the user if asked to choose from domain names.
Returns β List of selected names
Return type β list of str
get_valid_domains
certbot.display.ops.get_valid_domains(domains: Iterable[str]) -> list[str]
Helper method for choose_names that implements basic checks on domain names β like a tiny bouncer doing a guest-list check before anyone gets in ποΈ
Parameters
domains(list) β Domain names to validate
...and it hands you back the good stuff:
Returns β a list of valid domains π
Return type β list (yes, the real Python list β https://docs.python.org/3/library/stdtypes.html#list)
π«Ά tiny heads-up before we keep going: in the actual docs every single type name is a hyperlink out to python.org. So you're not missing anything, the links are just:listβ https://docs.python.org/3/library/stdtypes.html#list,strβ https://docs.python.org/3/library/stdtypes.html#str,tupleβ https://docs.python.org/3/library/stdtypes.html#tuple,dictβ https://docs.python.org/3/library/stdtypes.html#dict,intβ https://docs.python.org/3/library/functions.html#int,boolβ https://docs.python.org/3/library/functions.html#bool,Noneβ https://docs.python.org/3/library/constants.html#None,Callableβ https://docs.python.org/3/library/typing.html#typing.Callable,Anyβ https://docs.python.org/3/library/typing.html#typing.Any,codeβ https://docs.python.org/3/library/code.html#module-code, andloggingβ https://docs.python.org/3/library/logging.html#module-logging. Alsoinput_textβ#certbot.display.util.input_text,directory_selectβ#certbot.display.util.directory_select, and the ops module itself β#module-certbot.display.ops. That's literally all of them. I'll keep the signatures clean so your eyes don't fall out π
certbot.display.ops.success_installation
certbot.display.ops.success_installation(domains: list[str]) -> None
It pops a box confirming the installation of HTTPS. Like, congrats bestie, your cert is in π
Parameters
domains(list) β domain names which were enabled
certbot.display.ops.success_renewal
certbot.display.ops.success_renewal(unused_domains: list[str]) -> None
Pops a box confirming the renewal of an existing certificate. The renewal glow-up is real β¨
Parameters
domains(list) β domain names which were renewed
π okay so the argument isunused_domainsin the signature but the parameter doc calls itdomainsβ that's literally how it's written, I'm not fixing it, I'm just pointing at it.
certbot.display.ops.success_revocation
certbot.display.ops.success_revocation(cert_path: str) -> None
Shows a message confirming a certificate has been revoked. RIP to that cert, it had a good run π
Parameters
cert_path(list) β path to certificate which was revoked.
π«Ά and yes, the doc sayslisthere while the signature annotates itstr. That's just how the page reads, no cap.
certbot.display.ops.report_executed_command
certbot.display.ops.report_executed_command(
command_name: str,
returncode: int,
stdout: str,
stderr: str
) -> None
Shows a message telling you whether a process that got executed worked or flopped β think hooks, bestie. It's the "so how did it go" of the whole thing π₯
Parameters
command_name(str) β Human-readable description of the executed commandreturncode(int) β The exit code of the executed commandstdout(str) β The stdout output of the executed commandstderr(str) β The stderr output of the executed command
certbot.display.ops.validated_input
certbot.display.ops.validated_input(
validator: Callable[[str], Any],
*args: Any,
**kwargs: Any
) -> tuple[str, str]
Lowkey the same energy as input_text, but with validation. So it's input_text with trust issues (affectionate) π
Parameters
validator(callable) β A method which will be called on the supplied input. If the method raises anerrors.Error, its text will be displayed and the user will be re-prompted.*args(list) β Arguments to be passed toinput_text.**kwargs(dict) β Arguments to be passed toinput_text.
Returns β as input_text
Return type β tuple
certbot.display.ops.validated_directory
certbot.display.ops.validated_directory(
validator: Callable[[str], Any],
*args: Any,
**kwargs: Any
) -> tuple[str, str]
Same deal as validated_input, except it's doing the whole thing for directory_select. Directory but make it verified πΈ
Parameters
validator(callable) β A method which will be called on the supplied input. If the method raises anerrors.Error, its text will be displayed and the user will be re-prompted.*args(list) β Arguments to be passed todirectory_select.**kwargs(dict) β Arguments to be passed todirectory_select.
Returns β as directory_select
Return type β tuple
π¦ certbot.display.util module
Certbot display. That's the whole intro line, and honestly? Iconic brevity.
This module (certbot.display.util) or its companion certbot.display.ops should be used whenever:
- Displaying status information to the user on the terminal
- Collecting information from the user via prompts
Other messages can use the logging module. See log.py. (That's logging β https://docs.python.org/3/library/logging.html#module-logging, if you're a link girlie π)
certbot.display.util.OK
certbot.display.util.OK = 'ok'
Display exit code indicating user acceptance. She said yes π
certbot.display.util.CANCEL
certbot.display.util.CANCEL = 'cancel'
Display exit code for a user canceling the display. She said no, and that's valid too π
certbot.display.util.notify
certbot.display.util.notify(msg: str) -> None
Displays a basic status message. No drama, no pause, just a little "hey, here's what's up" β¨
Parameters
msg(str) β message to display
certbot.display.util.notification
certbot.display.util.notification(
message: str,
pause: bool = True,
wrap: bool = True,
force_interactive: bool = False,
decorate: bool = True
) -> None
Displays a notification and waits for user acceptance. So it's the version that actually stops and stares at you until you acknowledge it π
Parameters
message(str) β Message to displaypause(bool) β Whether or not the program should pause for the user's confirmationwrap(bool) β Whether or not the application should wrap textforce_interactive(bool) βTrueif it's safe to prompt the user because it won't cause any workflow regressionsdecorate(bool) β Whether to surround the message with a decorated frame
certbot.display.util.menu
certbot.display.util.menu(
message: str,
choices: list[str] | list[tuple[str, str]],
default: int | None = None,
cli_flag: str | None = None,
force_interactive: bool = False
) -> tuple[str, int]
Displays a menu. Pick-a-thing time, bestie, the terminal edition π
Parameters
message(str) β title of menuchoices(listof tuples(tag, item)orlistof descriptions (tags will be enumerated)) β Menu lines,lenmust be >0defaultβ default value to return, if interaction is not possiblecli_flag(str) β option used to set this value with the CLIforce_interactive(bool) βTrueif 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
Return type β tuple
certbot.display.util.input_textβ okay bestie, this one is literally just "ask the human a thing and get words back" π¬
certbot.display.util.input_text(message: str, default: str | None = None, cli_flag: str | None = None, force_interactive: bool = False) -> tuple[str, str]
Accept input from the user. That's the whole job, she's an icon, she's simple β¨
Parameters (the tea β)
message(str) β the message you show to the user, like the prompt textdefaultβ default value to return, if interaction is not possible π«Άcli_flag(str) β option used to set this value with the CLIforce_interactive(bool) βTrueif it's safe to prompt the user because it won't cause any workflow regressions (key caveat, do not skip it, ngl)
Returns β a tuple of (code, input) where code β str display exit code, and input β str of the user's input π
Return type β tuple
certbot.display.util.yesnoβ the "girl just say yes or no" function π
certbot.display.util.yesno(message: str, yes_label: str = 'Yes', no_label: str = 'No', default: bool | None = None, cli_flag: str | None = None, force_interactive: bool = False) -> bool
Query the user with a yes/no question.
π¨ Real rule, not vibes: Yes and No label must begin with different letters, and must contain at least one letter each. That's the requirement, periodt.
Parameters
message(str) β question for the useryes_label(str) β Label of the "Yes" parameterno_label(str) β Label of the "No" parameterdefaultβ default value to return, if interaction is not possiblecli_flag(str) β option used to set this value with the CLIforce_interactive(bool) βTrueif it's safe to prompt the user because it won't cause any workflow regressions
Returns β True for "Yes", False for "No" π
Return type β bool
certbot.display.util.checklistβ a little menu moment, main character energy π
certbot.display.util.checklist(message: str, tags: list[str], default: list[str] | None = None, cli_flag: str | None = None, force_interactive: bool = False) -> tuple[str, list[str]]
Display a checklist. Pick your faves, bestie πΈ
Parameters
message(str) β Message to display to usertags(list) βstrtags to select, and note the condition:len(tags) > 0(so like, at least one, obviously π )defaultβ default value to return, if interaction is not possiblecli_flag(str) β option used to set this value with the CLIforce_interactive(bool) βTrueif 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, and tags β list of selected tags β¨
Return type β tuple
certbot.display.util.directory_selectβ the "pick a folder" screen, very file-picker chic ποΈ
certbot.display.util.directory_select(message: str, default: str | None = None, cli_flag: str | None = None, force_interactive: bool = False) -> tuple[str, str]
Display a directory selection screen.
Parameters
message(str) β prompt to give the userdefaultβ default value to return, if interaction is not possiblecli_flag(str) β option used to set this value with the CLIforce_interactive(bool) βTrueif 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, and string β input entered by the user π¦
certbot.display.util.assert_valid_callβ the vibe check function fr fr β
certbot.display.util.assert_valid_call(prompt: str, default: str, cli_flag: str, force_interactive: bool) -> None
Verify that provided arguments is a valid display call. Like, she checks your outfit before you leave the house π
Parameters
prompt(str) β prompt for the userdefaultβ default answer to promptcli_flag(str) β command line option for setting an answer to this questionforce_interactive(bool) β if interactivity is forced
π§© certbot.plugins package
Certbot plugins. The extended universe, basically π
certbot.plugins.common module
Plugin common functions. The shared lil helpers everyone uses π«Ά
certbot.plugins.common.option_namespace
certbot.plugins.common.option_namespace(name: str) -> str
ArgumentParser options namespace (prefix of all options). She adds the lil prefix, that's the whole gig π
certbot.plugins.common.dest_namespace
certbot.plugins.common.dest_namespace(name: str) -> str
ArgumentParser dest namespace (prefix of all destinations). Same energy, but for destinations β¨
class certbot.plugins.common.Plugin
class certbot.plugins.common.Plugin(config: NamespaceConfig, name: str)
Bases: Plugin
Generic plugin. The blueprint, the template, the moment π
abstractmethod classmethod add_parser_arguments
abstractmethod classmethod add_parser_arguments(add: Callable[[...], None]) -> None
Add plugin arguments to the CLI argument parser.
Parameters
add(callable) β Function that proxies calls toargparse.ArgumentParser.add_argumentprepending options with unique plugin name prefix. (iykyk, it's the prefix fairy π§)classmethod inject_parser_options
classmethod inject_parser_options(parser: ArgumentParser, name: str) -> None
Inject parser options. Boom, they're in there πβ¨
See inject_parser_options for docs β she's got her own whole writeup, go peek bestie π
option_namespace(property,str) β the ArgumentParser options namespace, aka the cute little prefix that goes on the front of literally all the options β¨option_name(name: str) -> strβ hands you back the option name, plugin namespace included, no cap πdest_namespace(property,str) β the ArgumentParser dest namespace, which is the prefix of all the destinations, periodtdest(var: str) -> strβ find a destination for the given variablevarπ¦conf(var: str) -> Anyβ find a configuration value for variablevarauth_hint(failed_achalls: list[AnnotatedChallenge]) -> strβ a human-readable string that helps the user troubleshoot the authenticator π
Shown to the user if one or more of the attempted challenges were not a success. It should describe, in simple language, what the authenticator tried to do, what went wrong, and what the user should try as their "next steps" β main character energy for error messages fr fr.
TODO:auth_hintbelongs inAuthenticatorbut can't be added until the next major version of Certbot. For now, it lives in.Pluginandauth_handlerwill only call it on authenticators that subclass.Plugin. For now, inherit fromPluginto implement and/or override the method. π
Parameters
failed_achalls(list) β list of one or more failed challenges (achallenges.AnnotatedChallengesubclasses).
Rtype str
π class certbot.plugins.common.Installer(*args: Any, **kwargs: Any)
Bases: Installer, Plugin
An installer base class with reverter and ssl_dhparam methods defined.
Installer plugins do not have to inherit from this class β it's giving optional, not mandatory π«Ά
add_to_checkpoint(save_files: set[str], save_notes: str, temporary: bool = False) -> Noneβ add files to a checkpoint.
Parameters
save_files(set) β set of filepaths to savesave_notes(str) β notes about changes during the savetemporary(bool) βTrueif 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 π¬
finalize_checkpoint(title: str) -> Noneβ timestamp and save changes made through the reverter.
Parameters
title(str) β title describing checkpoint
Raises .errors.PluginError β when an error occurs
recovery_routine() -> Noneβ 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 πΈ
revert_temporary_config() -> Noneβ rollback temporary checkpoint.
Raises .errors.PluginError β when unable to revert config
rollback_checkpoints(rollback: int = 1) -> Noneβ rollback saved checkpoints.
Parameters
rollback(int) β 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
ssl_dhparams(property,str) β full absolute path to thessl_dhparamsfile βupdated_ssl_dhparams_digest(property,str) β full absolute path to the digest of the updatedssl_dhparamsfileinstall_ssl_dhparams() -> Noneβ copy Certbot'sssl_dhparamsfile into the system's config dir if required π₯
π class certbot.plugins.common.Configurator(*args: Any, **kwargs: Any)
Bases: Installer, Authenticator
A plugin that extends certbot.plugins.common.Installer and implements certbot.interfaces.Authenticator β the way it just does both, iconic π
π¦ class certbot.plugins.common.Addr(tup: tuple[str, str], ipv6: bool = False)
Bases: object
Represents a virtual host address.
Parameters
addr(str) β addr part of vhost addressport(str) β port number or*, or""classmethod fromstring(str_addr: str) -> GenericAddrβ initializeAddrfrom string πnormalized_tuple() -> tuple[str, str]β normalized representation of the addr/port tupleget_addr() -> strβ return the addr part of theAddrobjectget_port() -> strβ return the portget_addr_obj(port: str) -> GenericAddrβ return a new address object with the same addr and a new port β¨get_ipv6_exploded() -> strβ return IPv6 in normalized form
π class certbot.plugins.common.ChallengePerformer(configurator: Configurator)
Bases: object
Abstract base for challenge performers.
Variables
configuratorβ authenticator and installer pluginachalls(listofKeyAuthorizationAnnotatedChallenge) β annotated challengesindices(listofint) β holds the indices of challenges from a larger array so the user of the class doesn't have to πadd_chall(achall: KeyAuthorizationAnnotatedChallenge, idx: int | None = None) -> Noneβ store a challenge to be performed whenperform()is called.
Parameters
achall(.KeyAuthorizationAnnotatedChallenge) β annotated challengeidx(int) β index to challenge in a larger array
perform() -> list[KeyAuthorizationChallengeResponse]β perform all added challenges, slay π₯
Returns challenge responses
Return type β a list (https://docs.python.org/3/library/stdtypes.html#list) of acme.challenges.KeyAuthorizationChallengeResponse (https://acme-python.readthedocs.io/en/latest/api/challenges.html#acme.challenges.KeyAuthorizationChallengeResponse)
certbot.plugins.common.install_version_controlled_file(...)
certbot.plugins.common.install_version_controlled_file(dest_path: str, digest_path: str, src_path: str, all_hashes: Iterable[str]) -> None
Bestie, this one copies a file into an active location β probably the systemβs config dir β but only if it actually needs to. Lowkey essential, no cap. β¨
Parameters
dest_path(str) β destination path for the version-controlled file.digest_path(str) β path to save a digest of the file in.src_path(str) β path to the version-controlled file found in the distribution.all_hashes(list) β hashes of every released version of the file.
certbot.plugins.common.dir_setup(...)
certbot.plugins.common.dir_setup(test_dir: str, pkg: str) -> tuple[str, str, str]
Sets up the directories the configurator needs. Thatβs the whole vibe. π
πΈ certbot.plugins.dns_common module πΈ
Common code for DNS Authenticator Plugins. Very much the shared glue, iykyk. π
class certbot.plugins.dns_common.DNSAuthenticator(...)
class certbot.plugins.dns_common.DNSAuthenticator(config: NamespaceConfig, name: str)
Bases: Plugin (#certbot.plugins.common.Plugin) and Authenticator (#certbot.interfaces.Authenticator)
Base class for DNS Authenticators. Itβs giving βparent friend who handles the DNS chaos.β π
classmethod add_parser_arguments(...)
classmethod add_parser_arguments(add: Callable[[...], None], default_propagation_seconds: int = 10) -> None
Adds plugin arguments to the CLI argument parser. Very demure, very argparse. β¨
Parameters
add(callable) β Function that proxies calls toargparse.ArgumentParser.add_argument(https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument), prepending options with a unique plugin name prefix.
auth_hint(...)
auth_hint(failed_achalls: list[AnnotatedChallenge]) -> str
See certbot.plugins.common.Plugin.auth_hint. Same energy, different day. π«Ά
get_chall_pref(...)
get_chall_pref(unused_identifier: str) -> Iterable[type[Challenge]]
Returns a collections.Iterable of challenge preferences. The signature says unused_identifier; the parameter docs call it identifier β either way, itβs the domain/IP situation. π
Parameters
identifier(str) β Domain or IP address for which challenge preferences are sought.
Returns β collections.Iterable of challenge types (subclasses of acme.challenges.Challenge (https://acme-python.readthedocs.io/en/latest/api/challenges.html#acme.challenges.Challenge)) with the most preferred challenges first. If a type is not specified, it means the Authenticator cannot perform the challenge.
Return type β collections.Iterable
prepare()
prepare() -> None
Prepares the plugin. Finish up any additional initialization, bestie. β¨
Raises
.PluginErrorβ when full initialization cannot be completed..MisconfigurationErrorβ when full initialization cannot be completed. Plugin will be displayed on a list of available plugins..NoInstallationErrorβ when the necessary programs/files cannot be located. Plugin will NOT be displayed on a list of available plugins..NotSupportedErrorβ when the installation is recognized, but the version is not currently supported.
more_info()
more_info() -> str
Human-readable string to help the user. It should describe the steps taken and any relevant info to help the user decide which plugin to use. The page literally writes Rtype str here β not me fixing the typo, okay? π
Rtype β str
perform(...)
perform(achalls: list[AnnotatedChallenge]) -> list[ChallengeResponse]
Performs the given challenge. Main character energy: it gets the thing done. π₯
Parameters
achalls(list) β Non-empty (guaranteed) list ofAnnotatedChallenge(#certbot.achallenges.AnnotatedChallenge) instances, such that it contains types found withinget_chall_pref()only.
Returns β list of ACME ChallengeResponse (https://acme-python.readthedocs.io/en/latest/api/challenges.html#acme.challenges.ChallengeResponse) instances corresponding to each provided Challenge (https://acme-python.readthedocs.io/en/latest/api/challenges.html#acme.challenges.Challenge).
Return type β collections.List of acme.challenges.ChallengeResponse (https://acme-python.readthedocs.io/en/latest/api/challenges.html#acme.challenges.ChallengeResponse), where responses are required to be returned in the same order as corresponding input challenges.
Raises .PluginError β If some or all challenges cannot be performed.
cleanup(...)
cleanup(achalls: list[AnnotatedChallenge]) -> None
Reverts changes and shuts down after challenges complete. This method should be able to revert all changes made by perform, even if perform exited abnormally. Itβs giving βclean up your own mess, icon.β π§
Parameters
achalls(list) β Non-empty (guaranteed) list ofAnnotatedChallenge(#certbot.achallenges.AnnotatedChallenge) instances, a subset of those previously passed toperform().
Raises PluginError (#certbot.errors.PluginError) β if the original configuration cannot be restored.
class certbot.plugins.dns_common.CredentialsConfiguration(...)
class certbot.plugins.dns_common.CredentialsConfiguration(filename: str, mapper: ~typing.Callable[[str], str] = <function CredentialsConfiguration.<lambda>>)
Bases: object (https://docs.python.org/3/library/functions.html#object)
Represents a user-supplied filed which stores API credentials. Yes, the page says filed β typo and all β but it means a file, bestie. π
require(...)
require(required_variables: Mapping[str, str]) -> None
Makes sure the supplied set of variables are all present in the file. Attendance check, but for credentials. π
Parameters
required_variables(dict) β Map of variable which must be present to error to display.
Raises errors.PluginError (#certbot.errors.PluginError) β If one or more are missing.
conf(...)
conf(var: str) -> str | None
Finds a configuration value for variable var, as transformed by mapper.
Parameters
var(str) β The variable to get.
Returns β The value of the variable, if it exists.
Return type β str or None (https://docs.python.org/3/library/constants.html#None)
validate_file(filename: str) -> Noneβ bestie, this one just makes sure that file you're pointing at actually exists. That's it. That's the whole job. β¨validate_file_permissions(filename: str) -> Noneβ same vibe check as above (does the file exist?) but it also π warns π you π about unsafe permissions. Like, it'll still check existence, but if your perms are sketchy it will absolutely say something. πbase_domain_name_guesses(domain: str) -> list[str]β hands you back a list of progressively less-specific domain names. The idea is that one of these is probably the domain name your DNS provider actually knows about. Genius, honestly. π§
Example β fr fr this is the actual doctest:
>>> base_domain_name_guesses('foo.bar.baz.example.com')
['foo.bar.baz.example.com', 'bar.baz.example.com', 'baz.example.com', 'example.com', 'com']
Parameters
- domain (
str) β the domain you want guesses for.
Returns β the list of less specific domain names (yes, the original literally says "The a list", we're keeping the chaos π).
Return type β list
π¦ certbot.plugins.dns_common_lexicon module
An internal class delegating to a module, and showing warnings when attributes related to deprecated attributes in the current module get touched. Messy? A little. Iconic? Also yes. π
class certbot.plugins.dns_common_lexicon.LexiconClient
Bases: object
Encapsulates all the communication with a DNS provider via Lexicon. Like the whole group chat with your DNS provider goes through this class. π«Ά
Deprecated since version 2.7.0: please use certbot.plugins.dns_common_lexicon.LexiconDNSAuthenticator instead. Not me warning you twice β the original does it twice too. π
add_txt_record(domain: str, record_name: str, record_content: str) -> Noneβ adds a TXT record using the info you handed it.
Parameters
- domain (
str) β the domain used to look up the managed zone. - record_name (
str) β the record name (typically starting with'_acme-challenge.'). - record_content (
str) β the record content (typically the challenge validation).
Raises errors.PluginError β if an error occurs communicating with the DNS Provider API. π
del_txt_record(domain: str, record_name: str, record_content: str) -> Noneβ deletes a TXT record using the supplied info. Same energy, opposite direction. π
Parameters
- domain (
str) β the domain used to look up the managed zone. - record_name (
str) β the record name (typically starting with'_acme-challenge.'). - record_content (
str) β the record content (typically the challenge validation).
Raises errors.PluginError β if an error occurs communicating with the DNS Provider API. (Also note the original has a double space in "Provider API" there, we're preserving that little quirk because details matter. π)
certbot.plugins.dns_common_lexicon.build_lexicon_config(...)
Signature, exactly as written:
certbot.plugins.dns_common_lexicon.build_lexicon_config(
lexicon_provider_name: str,
lexicon_options: Mapping[str, Any],
provider_options: Mapping[str, Any]
) -> None | dict[str, Any]
A convenient function to build a Lexicon 2.x/3.x config object. Convenient! We love convenient. β¨
Parameters
- lexicon_provider_name (
str) β the name of the lexicon provider to use. - lexicon_options (
dict) β options specific to lexicon. - provider_options (
dict) β options specific to the provider.
Returns β configuration to apply to the provider.
Return type β ConfigurationResolver or dict.
Deprecated since version 2.7.0: please use certbot.plugins.dns_common_lexicon.LexiconDNSAuthenticator instead. (You may be sensing a pattern here. π)
class certbot.plugins.dns_common_lexicon.LexiconDNSAuthenticator(config: NamespaceConfig, name: str)
Bases: DNSAuthenticator
Base class for a DNS authenticator that uses a Lexicon client as the backend to execute DNS record updates. The main character of this module, tbh. π
πΈ certbot.plugins.dns_test_common module
Base test class for DNS authenticators. Testing time, bestie β let's go. π§
class certbot.plugins.dns_test_common.BaseAuthenticatorTest
Bases: object
A base test class to reduce duplication between test code for DNS Authenticator Plugins. DRY = slay.
Assumes:
- That subclasses also subclass
unittest.TestCase - That the authenticator is stored as
self.auth
And here's the class attribute, verbatim, because it's a whole situation:
achall = KeyAuthorizationAnnotatedChallenge(challb=DNS01(token=b'17817c66b60ce2e4012dfad92657527a'), domain='example.com', account_key=JWKRSA(key=<ComparableRSAKey(<cryptography.hazmat.bindings._rust.openssl.rsa.RSAPrivateKey object>)>), identifier=Identifier(typ=IdentifierType(dns), value='example.com'))
Then the test methods, no cap:
test_more_info() -> Nonetest_get_chall_pref() -> Nonetest_parser_arguments() -> None
certbot.plugins.dns_test_common.write(values: Mapping[str, Any], path: str) -> None
Writes the specified values to a config file. Little helper, big heart. π
Parameters
- values (
dict) β a map of values to write. - path (
str) β where to write the values.
π certbot.plugins.dns_test_common_lexicon module
Internal class delegating to a module, and displaying warnings when attributes related to deprecated attributes in the current module get accessed. Same disclaimer as before, because it's the same pattern. π
class certbot.plugins.dns_test_common_lexicon.BaseLexiconAuthenticatorTest
Bases: BaseAuthenticatorTest
test_perform(unused_mock_get_utility: Any) -> Noneβ yes the parameter is literally called unused_mock_get_utility. Respect the naming honesty. πtest_cleanup() -> Noneβ cleans up after the perform. Good hygiene. π«§
class certbot.plugins.dns_test_common_lexicon.BaseLexiconClientTest
Bases: object
Okay so this class has a bunch of class attributes and they're all fully iconic, let's get into it:
DOMAIN_NOT_FOUND= Exception('No domain found')β the "oop, where'd it go" exception. πGENERIC_ERRORβ alias ofRequestException.LOGIN_ERROR= HTTPError('400 Client Error: ...')β famous last words.UNKNOWN_LOGIN_ERROR= HTTPError('500 Surprise! Error: ...')β surprise! πrecord_prefix= '_acme-challenge'record_name= '_acme-challenge.example.com'record_content= 'bar'
And then the test methods β every single one, because we do not skip. Periodt. π
test_add_txt_record() -> Nonetest_add_txt_record_try_twice_to_find_domain() -> Nonetest_add_txt_record_fail_to_find_domain() -> Nonetest_add_txt_record_fail_to_authenticate() -> Nonetest_add_txt_record_fail_to_authenticate_with_unknown_error() -> Nonetest_add_txt_record_error_finding_domain() -> Nonetest_add_txt_record_error_adding_record() -> Nonetest_del_txt_record() -> Nonetest_del_txt_record_fail_to_find_domain() -> Nonetest_del_txt_record_fail_to_authenticate() -> None
That's the whole roster β add side and delete side, successes and every flavour of failure. Obsessed with the coverage honestly. π₯
test_del_txt_record_fail_to_authenticate_with_unknown_error()β returnsNonetest_del_txt_record_error_finding_domain()β returnsNonetest_del_txt_record_error_deleting_record()β returnsNone
okay and now for the big one π
class certbot.plugins.dns_test_common_lexicon.BaseLexiconDNSAuthenticatorTestβ bases:BaseAuthenticatorTest, and it's giving very much "the shared test blueprint all the lexicon DNS authenticator tests inherit from." It carries these class attributes:DOMAIN_NOT_FOUND = Exception('No domain found')πΈGENERIC_ERRORβ alias ofRequestExceptionLOGIN_ERROR = HTTPError('400 Client Error: ...')UNKNOWN_LOGIN_ERROR = HTTPError('500 Surprise! Error: ...')π (yes bestie, the ellipses are literally in the source, it's a vibe, don't touch it)
and these test methods, all returning None:
test_perform_succeed()test_perform_with_one_domain_resolution_failure_succeed()test_perform_with_two_domain_resolution_failures_raise()test_perform_with_domain_resolution_general_failure_raise()test_perform_with_auth_failure_raise()test_perform_with_unknown_auth_failure_raise()test_perform_with_create_record_failure_raise()test_cleanup_success()test_cleanup_with_auth_failure_ignore()test_cleanup_with_unknown_auth_failure_ignore()test_cleanup_with_domain_resolution_failure_ignore()test_cleanup_with_domain_resolution_general_failure_ignore()test_cleanup_with_delete_record_failure_ignore()
π certbot.plugins.enhancements module
New interface style Certbot enhancements
β¨ certbot.plugins.enhancements.ENHANCEMENTS = ['redirect', 'ensure-http-header', 'ocsp-stapling'] β¨
List of possible certbot.interfaces.Installer enhancements. fr fr this is the whole menu of what you can ask an installer to do for you.
List of expected options parameters, and yes, the order matters, keep it:
redirect:Noneensure-http-header: name of header (i.e.Strict-Transport-Security)ocsp-stapling: certificate chain file pathcertbot.plugins.enhancements.enabled_enhancements(config: NamespaceConfig) -> Generator[dict[str, Any], None, None]β a generator π« that yields the enabled new style enhancements. Take aconfig(certbot.configuration.NamespaceConfig) β the configuration β and off it goes, lazily, one enhancement at a time. Generator core.certbot.plugins.enhancements.are_requested(config: NamespaceConfig) -> boolβ checks if one or more of the requested enhancements are those of the new enhancement interfaces. Parameter:config(certbot.configuration.NamespaceConfig) β the configuration. Simple vibe check: did you ask for any new-style stuff or not?certbot.plugins.enhancements.are_supported(config: NamespaceConfig, installer: Installer | None) -> boolβ checks that all of the requested enhancements are supported by the installer. Not some. All. π- Parameters:
config(certbot.configuration.NamespaceConfig) β Configuration.installer(interfaces.Installer) β Installer object
- Returns: if all the requested enhancements are supported by the installer
- Return type:
bool
- Parameters:
certbot.plugins.enhancements.enable(lineage: RenewableCert | None, domains: Iterable[str], installer: Installer | None, config: NamespaceConfig) -> Noneβ run theenablemethod for each requested enhancement that is supported. This is the "go actually do the thing" function π«Ά- Parameters:
lineage(certbot.interfaces.RenewableCert) β Certificate lineage objectdomains(str) β List of domains in certificate to enhanceinstaller(interfaces.Installer) β Installer objectconfig(certbot.configuration.NamespaceConfig) β Configuration.
- Parameters:
certbot.plugins.enhancements.populate_cli(add: Callable[[...], None]) -> Noneβ populates the command line flags forcertbot._internal.cli.HelpfulParser. Parameter:add(func) β the add function ofcertbot._internal.cli.HelpfulParser. Basically it's out here registering the CLI flags so they actually exist for you π
π class certbot.plugins.enhancements.AutoHSTSEnhancement
Bases: object
The enhancement interface that installer plugins can implement in order to provide functionality that configures the software to have a 'Strict-Transport-Security' with an initially low max-age value that will increase over time. It's giving glow-up arc for your HSTS header π
π
The plugins implementing new style enhancements are responsible for handling the saving of configuration checkpoints as well as calling possible restarts of managed software themselves. So like, no cap, you handle your own checkpoints and restarts. For the update_autohsts method, the installer may have to call prepare() to finalize the plugin initialization.
Methods:
enable_autohstsis called when the header is initially installed using a lowmax-agevalue.update_autohstsis called every time when Certbot is run using the'renew'verb. Themax-agevalue should be increased over time using this method.deploy_autohstsis called for every lineage that has had its certificate renewed. A long HSTSmax-agevalue should be set here, as we should be confident that the user is able to automatically renew their certificates.
abstractmethod update_autohsts(lineage: RenewableCert, *args: Any, **kwargs: Any) -> None
Gets called for each lineage every time Certbot is run with the 'renew' verb. Implementation of this method should increase the max-age value. Slow and steady growth, iconic behaviour π±
- Parameters:
lineage(certbot.interfaces.RenewableCert) β Certificate lineage object
Note: theprepare()method inherited frominterfaces.Pluginmight need to be called manually within the implementation of this interface method to finalize the plugin initialization. So likeβ¦ don't forget it, bestie π
abstractmethod deploy_autohsts(lineage: RenewableCert, *args: Any, **kwargs: Any) -> None
Gets called for a lineage when its certificate is successfully renewed. A long max-age value should be set in the implementation of this method. This is the moment to go all in π₯
- Parameters:
lineage(certbot.interfaces.RenewableCert) β Certificate lineage object
abstractmethod enable_autohsts(lineage: RenewableCert | None, domains: Iterable[str], *args: Any, **kwargs: Any) -> None
Enables the AutoHSTS enhancement, installing the Strict-Transport-Security header with a low initial value to be increased over the subsequent runs of certbot renew. Start small, then slay β¨
- Parameters:
lineage(certbot.interfaces.RenewableCert) β Certificate lineage objectdomains(listofstr) β List of domains in certificate to enhance
π certbot.plugins.storage module
Plugin storage class. That's it, that's the whole vibe check for this one β short and sweet, and more is coming π
save()βNoneβ saves whatever's in the PluginStorage down to disk πΎ
Raises .errors.PluginStorageError β when it can't serialize the data or can't write it to the filesystem π so like, if that pops up, it's a serialization/filesystem thing, not a you thing.
put(key: str, value: Any)βNoneβ drops a configuration value into the PluginStorage β¨
Parameters
key(str) β the key you're storing the value under πvalueβ the actual data you're storing π
fetch(key: str)βAnyβ pulls a configuration value back out of the PluginStorage π«Ά
Parameters
key(str) β the key you're fetching the value from
Raises KeyError β if that key straight-up doesn't exist in the storage π no cap, check your key first.
π certbot.plugins.util module
Plugin utilities. Little helper besties for plugins, basically π
certbot.plugins.util.get_prefixes(path: str) -> list[str]
Grabs all the possible path prefixes of a path, in descending order of length β longest first, shortest last, iconic behaviour honestly π
For instance:
- (Linux)
/a/b/creturns['/a/b/c', '/a/b', '/a', '/'] - (Windows)
C:abcreturns['C:abc', 'C:ab', 'C:a', 'C:']
Parameters
path(str) β the path to break into prefixes π§
Returns
All possible path prefixes of the given path, in descending order.
Return type
list of str
certbot.plugins.util.path_surgery(cmd: str) -> bool
Attempts to perform PATH surgery to find cmd π literally minor surgery on your PATH, slay.
Mitigates <https://github.com/certbot/certbot/issues/1833>
Parameters
cmd(str) β the command that's being searched for in thePATH
Returns
True if the operation succeeded, False otherwise πΈ
π certbot.tests package
Utilities for running Certbot tests π§ͺ bestie, this is the test toolbox.
Submodules
π¦ certbot.tests.acme_util module
ACME utilities for testing. Test-only ACME vibes β¨
certbot.tests.acme_util.chall_to_challb(chall: Challenge, status: Status) -> ChallengeBody
Returns a ChallengeBody from a Challenge. That's it, that's the whole thing π«
certbot.tests.acme_util.gen_authzr(authz_status: Status, domain: str, challs: Iterable[Challenge], statuses: Iterable[Status]) -> AuthorizationResource
Generates an authorization resource π
Parameters
authz_status(acme.messages.Status) β aStatusobjectchalls(list) βChallengeobjectsstatuses(list) β the status of each challenge object β
β certbot.tests.util module
Test utilities. The test-side helper drawer, iykyk.
class certbot.tests.util.DummyInstaller(*args: Any, **kwargs: Any)
Bases: Installer
A dummy installer plugin, for test purposes only π don't ship this, it's literally a dummy.
get_all_names() -> Iterable[str]
Returns all names that may be authenticated π
Return type
collections.Iterable of str
deploy_cert(domain: str, cert_path: str, key_path: str, chain_path: str, fullchain_path: str) -> None
Deploys the certificate π₯ the whole point, honestly.
Parameters
domain(str) β domain to deploy the certificate file forcert_path(str) β absolute path to the certificate filekey_path(str) β absolute path to the private key filechain_path(str) β absolute path to the certificate chain filefullchain_path(str) β absolute path to the certificate fullchain file (cert plus chain) π
Raises .PluginError β when the cert cannot be deployed π
enhance(domain: str, enhancement: str, options: list[str] | str | None = None) -> None
Performs a configuration enhancement β¨ glow-up for your config.
Parameters
domain(str) β domain for which to provide the enhancementenhancement(str) β an enhancement as defined inENHANCEMENTSoptionsβ flexible options parameter for the enhancement. Check the documentation ofENHANCEMENTSfor the expected options for each enhancement π
Raises .PluginError β if the enhancement isn't supported, or if an error occurs during the enhancement π
supported_enhancements() -> list[str]
Returns a collections.Iterable of supported enhancements π
Returns
The supported enhancements, which should be a subset of ENHANCEMENTS
Return type
collections.Iterable of str
save(title: str | None = None, temporary: bool = False) -> None
Saves all changes to the configuration files πΎ the big one.
Both title and temporary are needed, because a save may be intended to be permanent but the save isn't ready to be a full checkpoint β like, it's committed but not committed committed, yk? π«Ά
It's assumed that at most one checkpoint is finalized by this method. Additionally, if an exception is raised, it's assumed a new checkpoint was not finalized π¨
Parameters
title(str) β 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.titlehas no effect iftemporaryis true.temporary(bool) β Indicates whether the changes made will be quickly reversed in the future (challenges)
Raises
.PluginErrorβ when save is unsuccessful
config_test() -> None
Make sure the configuration is valid, bestie. Like, is this config even usable or is it giving chaos?
Raises
.MisconfigurationErrorβ when the config is not in a usable state
restart() -> None
Restart or refresh the server content. The little refresh button of the plugin world β¨
Raises
.PluginErrorβ when server cannot be restarted
classmethod add_parser_arguments(add: Callable[[...], None]) -> None
Add plugin arguments to the CLI argument parser. Slay, give the people their flags π
Parameters
add(callable) β Function that proxies calls toargparse.ArgumentParser.add_argumentprepending options with unique plugin name prefix.
prepare() -> None
Prepare the plugin. Finish up any additional initialization. It's the getting-ready-with-me of plugin lifecycle events π
Raises
.PluginErrorβ when full initialization cannot be completed..MisconfigurationErrorβ when full initialization cannot be completed. Plugin will be displayed on a list of available plugins..NoInstallationErrorβ when the necessary programs/files cannot be located. Plugin will NOT be displayed on a list of available plugins..NotSupportedErrorβ when the installation is recognized, but the version is not currently supported.
more_info() -> str
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.
Ngl this one is literally just "explain yourself in a way a human can parse" β be helpful, be clear, be iconic.
Rtype str
π§ͺ certbot.tests.util (the test helpers, and yes they ate)
certbot.tests.util.vector_path(*names: str) -> str
Path to a test vector. That's it, that's the whole vibe π
certbot.tests.util.load_vector(*names: str) -> bytes
Load contents of a test vector. Bytes in, bytes out, no cap.
certbot.tests.util.load_cert(*names: str) -> Certificate
Load certificate. π
certbot.tests.util.load_jose_rsa_private_key_pem(*names: str) -> ComparableRSAKey
Load RSA private key wrapped in jose.ComparableRSAKey. Wrapped like a lil gift π
certbot.tests.util.load_rsa_private_key_pem(*names: str) -> RSAPrivateKey
Load RSA private key. Periodt.
certbot.tests.util.make_lineage(config_dir: str, testfile: str, ec: bool = True) -> str
Creates a lineage defined by testfile. This creates the archive, live, and renewal directories if necessary and creates a simple lineage. So convenient, honestly obsessed π
Parameters
config_dir(str) β path to the configuration directorytestfile(str) β configuration file to base the lineage onec(bool) βTrueif we generate the lineage with an ECDSA key
Returns
- path to the renewal conf file for the created lineage
Return type
str
certbot.tests.util.patch_display_util() -> MagicMock
Patch certbot.display.util to use a special mock display utility.
The mock display utility works like a regular mock object, except it also also asserts that methods are called with valid arguments. (Yes, "also also" β queen said it twice, we're keeping it.)
The mock created by this patch mocks out Certbot internals. That is, the mock object will be called by the certbot.display.util functions and the mock returned by that call will be used as the display utility. This was done to simplify the transition from zope.component and mocking certbot.display.util functions directly in test code should be preferred over using this function in the future.
Fr fr, this one is legacy-flavored β mock the certbot.display.util functions directly in your tests instead, iykyk.
See https://github.com/certbot/certbot/issues/8948
Returns
- patch on the function used internally by
certbot.display.utilto get a display utility instance
Return type
mock.MagicMock
certbot.tests.util.patch_display_util_with_stdout(stdout: IO | None = None) -> MagicMock
Patch certbot.display.util to use a special mock display utility.
The mock display utility works like a regular mock object, except it also also asserts that methods are called with valid arguments.
The mock created by this patch mocks out Certbot internals. That is, the mock object will be called by the certbot.display.util functions and the mock returned by that call will be used as the display utility. This was done to simplify the transition from zope.component and mocking certbot.display.util functions directly in test code should be preferred over using this function in the future.
The message argument passed to the display utility methods is passed to stdout's write method. ποΈ
See https://github.com/certbot/certbot/issues/8948
Parameters
stdout(object) β object to write standard output to; it is expected to have awritemethod
Returns
- patch on the function used internally by
certbot.display.utilto get a display utility instance
Return type
mock.MagicMock
class certbot.tests.util.FreezableMock(frozen: bool = False, func: Callable[[...], Any] | None = None, return_value: Any = sentinel.DEFAULT)
Bases: 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. Locked in. Literally.
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.
freeze() -> None
Freeze object preventing further changes. Brrr. βοΈ Nothing moves after this, bestie.
class certbot.tests.util.TempDirTestCase(methodName='runTest')
Bases: TestCase
Base test class which sets up and tears down a temporary directory. Temp dir in, temp dir gone, main character energy the whole time.
setUp() -> None
Execute before test.
tearDown() -> None
Execute after test.
class certbot.tests.util.ConfigTestCase(methodName='runTest')
Bases: TempDirTestCase
Test class which sets up a NamespaceConfig object.
setUp() -> None
Execute before test.
certbot.tests.util.lock_and_call(callback: Callable[[], Any], path_to_lock: str) -> None
Grab a lock on path_to_lock from a foreign process then execute the callback.
Parameters
callback(callable) β object to call after acquiring the lockpath_to_lock(str) β path to file or directory to lock
certbot.tests.util.skip_on_windows(reason: str) -> Callable[[Callable[[...], Any]], Callable[[...], Any]]
Decorator to skip permanently a test on Windows. A reason is required. Like, you can't just skip, you gotta say why πͺπ
certbot.tests.util.temp_join(path: str) -> str
Return the given path joined to the tempdir path for the current platform.
Eg.: 'cert' => /tmp/cert (Linux) or 'C:UserscurrentuserAppDataTempcert' (Windows)
π Submodules
π¦ certbot.achallenges module
Okay bestie, these are client annotated ACME challenges. π
Please use names such as achall to distinguish from variables "of type" acme.challenges.Challenge (denoted by chall) and 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
π class certbot.achallenges.AnnotatedChallenge(**kwargs: Any)
Bases: ImmutableMap
Client annotated challenge.
Wraps around server provided challenge and annotates with data useful for the client.
Variables
~.challbβ WrappedChallengeBody.challb
π class certbot.achallenges.KeyAuthorizationAnnotatedChallenge(**kwargs: Any)
Bases: AnnotatedChallenge
Client annotated KeyAuthorizationChallenge challenge.
β¨ response_and_validation(*args: Any, **kwargs: Any) -> tuple[KeyAuthorizationChallengeResponse, Any]
Generate response and validation. π«Ά
Also has these:
challbdomainaccount_keyidentifier
π class certbot.achallenges.DNS(**kwargs: Any)
Bases: AnnotatedChallenge
Client annotated "dns" ACME challenge.
acme_typeβ alias ofDNSchallbdomainidentifier
π¦ class certbot.achallenges.Other(**kwargs: Any)
Bases: AnnotatedChallenge
Client annotated ACME challenge of an unknown type.
acme_typeβ alias ofChallengechallbdomainidentifier
π₯ certbot.crypto_util module
Certbot client crypto utility functions. Crypto stuff, but make it Certbot. π
πΈ certbot.crypto_util.generate_key(key_size: int, key_dir: str | None, key_type: str = 'rsa', elliptic_curve: str = 'secp256r1', keyname: str = 'key-certbot.pem', strict_permissions: bool = True) -> Key
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. π
Parameters
key_size(int) β key size in bits if key size isrsa.key_dir(str) β Optional key save directory.key_type(str) β Key Type [rsa,ecdsa]elliptic_curve(str) β Name of the elliptic curve if key type isecdsa.keyname(str) β Filename of keystrict_permissions(bool) β If true andkey_direxists, an exception is raised if the directory doesn't have0700permissions or isn't owned by the current user.
Returns: Key
Return type: certbot.util.Key
RaisesValueErrorβ If unable to generate the key givenkey_size.
π certbot.crypto_util.generate_csr(privkey: Key, names: list[str] | set[str], path: str | None, must_staple: bool = False, strict_permissions: bool = True, ipaddrs: list[IPv4Address | IPv6Address] | None = None) -> CSR
Initialize a CSR with the given private key. β¨
Parameters
privkey(certbot.util.Key) β Key to include in the CSRnames(set) βstrnames to include in the CSRpath(str) β Optional certificate save directory.must_staple(bool) β If true, include the TLS Feature extension"OCSP Must-Staple"strict_permissions(bool) β If true andpathexists, an exception is raised if the directory doesn't have0755permissions or isn't owned by the current user.
Returns: CSR
Return type: certbot.util.CSR
π certbot.crypto_util.valid_csr(csr: bytes) -> bool
Validate CSR.
Check if csr is a valid CSR with a correct self-signed signature. π
Parameters
csr(bytes) β CSR in PEM.
Returns: Validity of CSR.
Return type: bool
π¦ certbot.crypto_util.csr_matches_pubkey(csr: bytes, privkey: bytes) -> bool
Does private key correspond to the subject public key in the CSR?
Parameters
csr(bytes) β CSR in PEM.privkey(bytes) β Private key file contents (PEM)
Returns: Correspondence of private key to CSR subject public key.
Return type: bool
π certbot.crypto_util.read_csr_file(csrfile: str, data: bytes) -> CSR
Reads a CSR file, which can be either PEM or DER, and returns a certbot.util.CSR object.
Parameters
csrfile(str) β CSR filenamedata(bytes) β contents of the CSR file
Returns: object representing the CSR
Return type: util.CSR
π certbot.crypto_util.import_csr_file(csrfile: str, data: bytes) -> tuple[Format, CSR, list[str]]
Import a CSR file, which can be either PEM or DER.
Parameters
csrfile(str) β CSR filenamedata(bytes) β contents of the CSR file
Returns: (acme_crypto_util.Format.PEM, util.CSR object representing the CSR, list of domains requested in the CSR)
Return type: tuple
β certbot.crypto_util.make_key(bits: int = 2048, key_type: str = 'rsa', elliptic_curve: str | None = None) -> bytes
Generate PEM encoded RSA|EC key.
Parameters
bits(int) β the number of bits, only ifkey_type=rsa. Gotta be at least2048for RSA, no shortcuts bestie πkey_type(str) β the type of key to generate, and it has to bersaorecdsaelliptic_curve(str) β the elliptic curve to use
Returns β a brand new RSA or ECDSA key in PEM form, with however many bits you asked for, or of type ec_curve when key_type ecdsa is used β¨
Return type β bytes
πΈ certbot.crypto_util.valid_privkey
certbot.crypto_util.valid_privkey(privkey: str | bytes) -> bool
Is this a valid RSA private key? That's the whole vibe check π«Ά
Parameters
privkeyβ the private key file contents, in PEM
Returns β the validity of the private key
Return type β bool
π certbot.crypto_util.verify_renewable_cert
certbot.crypto_util.verify_renewable_cert(renewable_cert: RenewableCert) -> None
For checking that your certs were not corrupted on disk π like genuinely, it's the "is my stuff okay" function.
Several things get checked:
- Signature verification for the cert.
- That
fullchainmatchescertandchainwhen concatenated. - Check that the private key matches the certificate.
Parameters
renewable_cert(certbot.interfaces.RenewableCert) β cert to verify
Raises errors.Error β if verification fails π
π¦ certbot.crypto_util.verify_renewable_cert_sig
certbot.crypto_util.verify_renewable_cert_sig(renewable_cert: RenewableCert) -> None
Verifies the signature of a RenewableCert object. Just the sig, nothing else, she's focused π
Parameters
renewable_cert(certbot.interfaces.RenewableCert) β cert to verify
Raises errors.Error β if signature verification fails
π certbot.crypto_util.verify_signed_payload
certbot.crypto_util.verify_signed_payload(public_key: DSAPublicKey | Ed25519PublicKey | Ed448PublicKey | EllipticCurvePublicKey | MLDSA44PublicKey | MLDSA65PublicKey | MLDSA87PublicKey | MLKEM768PublicKey | MLKEM1024PublicKey | RSAPublicKey | X25519PublicKey | X448PublicKey, signature: bytes, payload: bytes, signature_hash_algorithm: HashAlgorithm) -> None
Check the signature of a payload. Look at that public key type union β she contains multitudes, iykyk π
Parameters
public_key(RSAPublicKey/EllipticCurvePublicKey) β thepublic_keyto check signaturesignature(bytes) β the signature bytespayload(bytes) β the payload bytessignature_hash_algorithm(hashes.HashAlgorithm) β algorithm used to hash the payload
Raises
InvalidSignatureβ if signature verification failserrors.Errorβ if public key type is not supported π
π certbot.crypto_util.verify_cert_matches_priv_key
certbot.crypto_util.verify_cert_matches_priv_key(cert_path: str, key_path: str) -> None
Verifies that the private key and the cert actually match. Like, are they even a couple? π
Parameters
cert_path(str) β path to a cert in PEM formatkey_path(str) β path to a private key file
Raises errors.Error β if they don't match π
π
certbot.crypto_util.verify_fullchain
certbot.crypto_util.verify_fullchain(renewable_cert: RenewableCert) -> None
Verifies that fullchain is indeed cert concatenated with chain. Math check, bestie, no cap β¨
Parameters
renewable_cert(certbot.interfaces.RenewableCert) β cert to verify
Raises errors.Error β if cert and chain do not combine to fullchain
π certbot.crypto_util.get_sans_from_cert
certbot.crypto_util.get_sans_from_cert(cert: bytes, typ: Format | int | None = None) -> list[str]
Get a list of Subject Alternative Names from a certificate. All the lil names, gathered up π
Parameters
cert(str) β certificate (encoded)typ(Format) β which format the cert bytes are in
Returns β a list of Subject Alternative Names
Return type β list
π§ certbot.crypto_util.get_names_from_cert
certbot.crypto_util.get_names_from_cert(cert: bytes, typ: Format | int | None = None) -> list[str]
Get a list of domains from a cert, including the CN if it is set. Yes, the CN is invited to the party too π
Parameters
cert(str) β certificate (encoded)typ(Format) β which format the cert bytes are in
Returns β a list of domain names
Return type β list
πΈ certbot.crypto_util.get_names_from_req
certbot.crypto_util.get_names_from_req(csr: bytes, typ: Format | int | None = None) -> list[str]
Get a list of domains from a CSR, including the CN if it is set. Same energy, different file π¦
Parameters
csr(str) β CSR (encoded)typ(acme_crypto_util.Format) β which format the csr bytes are in
Returns β a list of domain names
Return type β list
β certbot.crypto_util.notBefore
certbot.crypto_util.notBefore(cert_path: str) -> datetime
When does the cert at cert_path start being valid? Her birth era π
Parameters
cert_path(str) β path to a cert in PEM format
Returns β the notBefore value from the cert at cert_path
Return type β datetime.datetime
π certbot.crypto_util.notAfter
certbot.crypto_util.notAfter(cert_path: str) -> datetime
When does the cert at cert_path stop being valid? Her expiration date, plan accordingly π
Parameters
cert_path(str) β path to a cert in PEM format
Returns β the notAfter value from the cert at cert_path
Return type β datetime.datetime
π certbot.crypto_util.sha256sum
certbot.crypto_util.sha256sum(filename: str) -> str
Compute a sha256sum of a file. Fingerprint her π
NB: in the given file, platform specific newline characters will be converted into their equivalent unicode counterparts before calculating the hash. So like, heads up, the newlines get translated first β that's part of the deal, not a bug.
Parameters
filename(str) β path to the file whose hash will be computed
Returns β sha256 digest of the file in hexadecimal
Return type β str
π₯ certbot.crypto_util.cert_and_chain_from_fullchain
certbot.crypto_util.cert_and_chain_from_fullchain(fullchain_pem: str) -> tuple[str, str]
Split fullchain_pem into cert_pem and chain_pem. Breaking up is hard to do but someone's gotta do it βοΈ
Parameters
fullchain_pem(str) β concatenated cert + chain
Returns β tuple of string cert_pem and chain_pem
Return type β tuple
Raises errors.Error β if there are less than 2 certificates in the chain π
π certbot.crypto_util.get_serial_from_cert
certbot.crypto_util.get_serial_from_cert(cert_path: str) -> int
Retrieve the serial number of a certificate from the certificate path. Her literal ID number, main character energy fr fr π
cert_path (str β https://docs.python.org/3/library/stdtypes.html#str) β the path to a cert in PEM format, bestie. That's it, that's the whole parameter π
Returns β the serial number of the certificate. Slay.
Return type β int (https://docs.python.org/3/library/functions.html#int)
π¦ certbot.crypto_util.find_chain_with_issuer
certbot.crypto_util.find_chain_with_issuer(fullchains: list[str], issuer_cn: str, warn_on_no_match: bool = False) -> str
Okay so real talk, this one picks the first certificate chain out of fullchains whose topmost intermediate has an Issuer Common Name that matches issuer_cn. Like, in other words (and I'm quoting the vibe here): the first chain which chains to a root whose name matches issuer_cn. Obsessed with a queen who knows what she wants π
Parameters
fullchains(listofstrβ https://docs.python.org/3/library/stdtypes.html#list, https://docs.python.org/3/library/stdtypes.html#str) β The list of fullchains in PEM chain format.issuer_cn(strβ https://docs.python.org/3/library/stdtypes.html#str) β The exact Subject Common Name to match against any issuer in the certificate chain. Exact, okay? Not "close enough", not "vibes-wise" β exact.
And yes, the signature also carries warn_on_no_match: bool = False β that False is the default, no cap π
Returns β The best-matching fullchain, PEM-encoded, or the first if none match. Lowkey generous of it ngl.
Return type β str (https://docs.python.org/3/library/stdtypes.html#str)
π certbot.errors module
Certbot client errors. It's giving "everything that can go wrong, lovingly catalogued" β¨
exception certbot.errors.Error
Bases: Exception (https://docs.python.org/3/library/exceptions.html#Exception)
Generic Certbot client error. The mother of all of them fr fr.
exception certbot.errors.AccountStorageError
Bases: Error
Generic AccountStorage error.
exception certbot.errors.AccountNotFound
Bases: AccountStorageError
Account not found error. She's not here, bestie π
exception certbot.errors.ReverterError
Bases: Error
Certbot Reverter error.
exception certbot.errors.SubprocessError
Bases: Error
Subprocess handling error.
exception certbot.errors.CertStorageError
Bases: Error
Generic CertStorage error.
exception certbot.errors.HookCommandNotFound
Bases: Error
Failed to find a hook command in the PATH. Bestie checked everywhere. Nothing. π
exception certbot.errors.SignalExit
Bases: Error
A Unix signal was received while in the ErrorHandler context manager.
exception certbot.errors.OverlappingMatchFound
Bases: Error
Multiple lineages matched what should have been a unique result. The audacity π
exception certbot.errors.LockError
Bases: Error
File locking error.
exception certbot.errors.AuthorizationError
Bases: Error
Authorization error.
exception certbot.errors.FailedChallenges
failed_achalls: set[AnnotatedChallenge]
Bases: AuthorizationError
Failed challenges error. The mood killer.
Variables
failed_achalls(setβ https://docs.python.org/3/library/stdtypes.html#set) β FailedAnnotatedChallengeinstances.
exception certbot.errors.PluginError
Bases: Error
Certbot Plugin error.
exception certbot.errors.PluginEnhancementAlreadyPresent
Bases: Error
Enhancement was already set. Girl, we already did that one π
exception certbot.errors.PluginSelectionError
Bases: Error
A problem with plugin/configurator selection or setup.
exception certbot.errors.NoInstallationError
Bases: PluginError
Certbot No Installation error.
exception certbot.errors.MisconfigurationError
Bases: PluginError
Certbot Misconfiguration error.
exception certbot.errors.NotSupportedError
Bases: PluginError
Certbot Plugin function not supported error.
exception certbot.errors.PluginStorageError
Bases: PluginError
Certbot Plugin Storage error.
exception certbot.errors.StandaloneBindError
socket_error: OSError, port: int
Bases: Error
Standalone plugin bind error.
exception certbot.errors.ConfigurationError
Bases: Error
Configuration sanity error. Sanity check failed, bestie, that's the whole vibe check right there πΈ
exception certbot.errors.MissingCommandlineFlag
Bases: Error
A command line argument was missing in noninteractive usage. Not her asking for input at 3am when nobody's home π
π§ certbot.interfaces module
Certbot client interfaces. This is where all the blueprints live, and they are iconic π
class certbot.interfaces.AccountStorage
Bases: object (https://docs.python.org/3/library/functions.html#object)
Accounts storage interface.
abstractmethod find_all() β list[Account]
Find all accounts.
Returns β All found accounts.
Return type β list (https://docs.python.org/3/library/stdtypes.html#list)
abstractmethod load(account_id: str) -> Account
Load an account by its id.
Raises
.AccountNotFoundβ if account could not be found.AccountStorageErrorβ if account could not be loaded
Returns β The account loaded
Return type β .Account
abstractmethod save(account: Account, client: ClientV2) -> None
ClientV2 lives at https://acme-python.readthedocs.io/en/latest/api/client.html#acme.client.ClientV2 btw. And None is https://docs.python.org/3/library/constants.html#None π
Save account.
Raises .AccountStorageError β if account could not be saved
class certbot.interfaces.Plugin
config: NamespaceConfig | None, name: str
Bases: object (https://docs.python.org/3/library/functions.html#object)
Certbot plugin. Okay this is the big one, pay attention bestie π«Ά
Objects providing this interface will be called without satisfying any entry point "extras" (extra dependencies) you might have defined for your plugin. Like, for example (excerpt from setup.py script):
setup(
...
entry_points={
'certbot.plugins': [
'name=example_project.plugin[plugin_deps]',
],
},
extras_require={
'plugin_deps': ['dep1', 'dep2'],
}
)
So therefore β and this is the important part β make sure such objects are importable and usable without extras. This is necessary, because the CLI does the following operations (in order):
- loads an entry point,
- calls
inject_parser_options, - requires an entry point,
- creates plugin instance (
__call__).
Not me warning you twice: no extras. The CLI will not be doing your dependency shopping for you ποΈ
description: str = NotImplemented β Short plugin description. (str is https://docs.python.org/3/library/stdtypes.html#str)
name: str = NotImplemented β Unique name of the plugin. Unique, okay? There can only be one main character π
abstractmethod prepare() -> None
None β https://docs.python.org/3/library/constants.html#None
Prepare the plugin. Finish up any additional initialization.
Raises
.PluginErrorβ when full initialization cannot be completed..MisconfigurationErrorβ when full initialization cannot be completed. Plugin will be displayed on a list of available plugins..NoInstallationErrorβ when the necessary programs/files cannot be located. Plugin will NOT be displayed on a list of available plugins..NotSupportedErrorβ when the installation is recognized, but the version is not currently supported.
The difference betweenMisconfigurationErrorandNoInstallationErroris literally just whether you show up on the list. Read it twice, bestie, I beg π
abstractmethod more_info() -> str
str β https://docs.python.org/3/library/stdtypes.html#str
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
abstractmethod classmethod inject_parser_options(parser: ArgumentParser, name: str) -> None
ArgumentParser β https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser, str β https://docs.python.org/3/library/stdtypes.html#str, None β https://docs.python.org/3/library/constants.html#None
Inject argument parser options (flags).
- Be nice and prepend all options and destinations with
option_namespaceanddest_namespace. - Inject options (flags) only. Positional arguments are not allowed, as this would break the CLI.
Parameters
parser(ArgumentParser) β (Almost) top-level CLI parser.name(str) β Unique plugin name.
Rule 2 is not a suggestion, it's a boundary π§ positional arguments would break the CLI and we do not do that here.
class certbot.interfaces.Authenticator
config: NamespaceConfig | None, name: str
Bases: Plugin
Generic Certbot Authenticator.
Class represents all possible tools processes that have the ability to perform challenges and attain a certificate. That's the whole job description and honestly? Queen behaviour π
okay so, back to the actual methods on the Authenticator, because this is the part where you find out exactly what you're signing up for π«Ά
π
get_chall_pref
abstractmethod get_chall_pref(identifier: str) -> Iterable[type[Challenge]]
Return a collections.Iterable of challenge preferences. That's it, that's the vibe.
Parameters
identifier(str) β Domain or IP address for which challenge preferences are sought.
Returns
collections.Iterable of challenge types (subclasses of acme.challenges.Challenge) with the most preferred challenges first. And listen β if a type is not specified, it means the Authenticator cannot perform that challenge. no cap, that's the whole tell π₯
Return type
collections.Iterable
π₯ perform
abstractmethod perform(achalls: list[AnnotatedChallenge]) -> list[ChallengeResponse]
Perform the given challenge. this is the main character method honestly β¨
Parameters
achalls(list) β Non-empty (guaranteed) list ofAnnotatedChallengeinstances, such that it contains types found withinget_chall_pref()only.
Returns
list of ACME ChallengeResponse instances corresponding to each provided Challenge.
Return type
collections.List of acme.challenges.ChallengeResponse, where responses are required to be returned in the same order as corresponding input challenges. like, the order MATTERS bestie, don't get cute with it π
Raises .PluginError β If some or all challenges cannot be performed
π§Ή cleanup
abstractmethod cleanup(achalls: list[AnnotatedChallenge]) -> None
Revert changes and shutdown after challenges complete. it's giving "leave no trace" energy πΈ
This method should be able to revert all changes made by perform, even if perform exited abnormally. yes, even then. especially then.
Parameters
achalls(list) β Non-empty (guaranteed) list ofAnnotatedChallengeinstances, a subset of those previously passed toperform().
Raises PluginError β if original configuration cannot be restored
π class certbot.interfaces.Installer
class certbot.interfaces.Installer(config: NamespaceConfig | None, name: str)
Bases: Plugin
Generic Certbot Installer Interface. it literally "Represents any server that an X509 certificate can be placed." iconique.
It is assumed that 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. like, that's the load-bearing assumption, do not test it π
Using certbot.reverter.Reverter to implement checkpoints, rollback, and recovery can dramatically simplify plugin development. take the shortcut, bestie, it's right there π
π get_all_names
abstractmethod get_all_names() -> Iterable[str]
Returns all names that may be authenticated.
Return type
collections.Iterable of str
π deploy_cert
abstractmethod deploy_cert(domain: str, cert_path: str, key_path: str, chain_path: str, fullchain_path: str) -> None
Deploy certificate. the moment everything was building toward, tbh π¦
Parameters
domain(str) β domain to deploy certificate filecert_path(str) β absolute path to the certificate filekey_path(str) β absolute path to the private key filechain_path(str) β absolute path to the certificate chain filefullchain_path(str) β absolute path to the certificate fullchain file (cert plus chain)
Raises .PluginError β when cert cannot be deployed
β¨ enhance
abstractmethod enhance(domain: str, enhancement: str, options: list[str] | str | None = None) -> None
Perform a configuration enhancement. glow-up time π
Parameters
domain(str) β domain for which to provide enhancementenhancement(str) β An enhancement as defined inENHANCEMENTSoptionsβ Flexible options parameter for enhancement. Check documentation ofENHANCEMENTSfor expected options for each enhancement.
Raises .PluginError β If Enhancement is not supported, or if an error occurs during the enhancement.
π supported_enhancements
abstractmethod supported_enhancements() -> list[str]
Returns a collections.Iterable of supported enhancements. (yes, it says Iterable in the sentence but returns a list in the signature β I'm just telling you what the page says, don't come for me π)
Returns
supported enhancements which should be a subset of ENHANCEMENTS
Return type
collections.Iterable of str
πΎ save
abstractmethod save(title: str | None = None, temporary: bool = False) -> None
Saves all changes to the configuration files. the commit of it all β¨
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. both. you need both. iykyk.
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. that's a whole lot of assumption but okay we ball π«Ά
Parameters
title(str) β 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.titlehas no effect iftemporaryis true.temporary(bool) β Indicates whether the changes made will be quickly reversed in the future (challenges)
Raises .PluginError β when save is unsuccessful
βͺ rollback_checkpoints
abstractmethod rollback_checkpoints(rollback: int = 1) -> None
Revert rollback number of configuration checkpoints. undo, undo, undo π
Raises .PluginError β when configuration cannot be fully reverted
and that's this batch of the interface besties β more coming, don't go anywhere π
recovery_routine() -> None(abstractmethod) β bestie this is the undo everything button π«Ά Reverts your configuration to the most recent finalized checkpoint. It removes all changes (temporary and permanent) that have not been finalized. Super useful for protecting yourself against crashes and other execution interruptions, like when the universe simply decides to interrupt your execution π
Raises .errors.PluginError β if it's unable to recover the configuration.
config_test() -> None(abstractmethod) β makes sure the configuration is valid. That's it, that's the whole vibe check β¨
Raises .MisconfigurationError β when the config is not in a usable state.
restart() -> None(abstractmethod) β restart or refresh the server content π
Raises .PluginError β when the server cannot be restarted.
class certbot.interfaces.RenewableCert
Bases: object
Interface to a certificate lineage. It's giving certificate family tree π³
cert_path: str(abstract property) β path to the certificate file.
Return type: str
key_path: str(abstract property) β path to the private key file π
Return type: str
chain_path: str(abstract property) β path to the certificate chain file.
Return type: str
fullchain_path: str(abstract property) β path to the full chain file.
The full chain is the certificate file plus the chain file. Literally the whole package deal π
Return type: str
lineagename: str(abstract property) β the name given to the certificate lineage.
Return type: str
names() -> list[str](abstractmethod) β what are the subject names of this certificate? π
Returns: the subject names.
Return type: list of str
Raises .CertStorageError β if it could not find the cert file.
class certbot.interfaces.GenericUpdater
Bases: object
Interface for update types not currently specified by Certbot. This class lets plugins perform types of updates that Certbot hasn't defined (yet) β manifesting future functionality, iykyk π
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 for handling the saving of configuration checkpoints, as well as other calls to interface methods of interfaces.Installer such as prepare() and restart(). No pressure or anything π
generic_updates(lineage: RenewableCert, *args: Any, **kwargs: Any) -> None(abstractmethod) β 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. Do it yourself energy, fr fr.
This method is called once for each lineage.
Parameters: lineage (RenewableCert) β certificate lineage object.
class certbot.interfaces.RenewDeployer
Bases: object
Interface for update types that run when a lineage is renewed π
This class lets plugins 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.
renew_deploy(lineage: RenewableCert, *args: Any, **kwargs: Any) -> None(abstractmethod) β perform updates defined by the 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 certificate 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. Renovation era π
This method is called once for each lineage renewed.
Parameters: lineage (RenewableCert) β certificate lineage object.
class certbot.interfaces.IPluginFactory
Bases: object
Compatibility shim for plugins that still use Certbot's old zope.interface classes. It's a little vintage, but we respect the elders π«Ά
class certbot.interfaces.IPlugin
Bases: object
Compatibility shim for plugins that still use Certbot's old zope.interface classes.
class certbot.interfaces.IAuthenticator
Bases: IPlugin
Compatibility shim for plugins that still use Certbot's old zope.interface classes.
class certbot.interfaces.IInstaller
Bases: IPlugin
Compatibility shim for plugins that still use Certbot's old zope.interface classes.
certbot.main module πΈ
Certbot main public entry point. The front door, the main character, the moment β¨
certbot.main.main(cli_args: list[str] | None = None) -> str | int | None
Run Certbot.
Parameters: cli_args (list of str) β command line to Certbot, defaults to sys.argv[1:].
Returns: value for sys.exit about the exit status of Certbot.
Return type: str or int or None.
certbot.reverter module π¦
Reverter class saves configuration checkpoints and allows for recovery. No cap, this thing is the safety net of the whole operation.
class certbot.reverter.Reverter(config: NamespaceConfig)
Bases: 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. Register first, act second β periodt.
Once a change has been registered with this class, there are three states the change can be in. Let's break it down:
- 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
add_to_temp_checkpoint()and reverted whenrevert_temporary_config()orrecovery_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
add_to_checkpoint()and reverted whenrecovery_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
finalize_checkpoint(). Changes in this state can be reverted through calls torollback_checkpoints().
As a final note, creating new files and registering undo commands are handled specially and use the methods register_file_creation() and register_undo_command() respectively. Both of these methods can be used to create either temporary or in progress changes. Special treatment? Deserved π
Note: consider moving everything over to CSV format.
Parameters: config (certbot.configuration.NamespaceConfig) β configuration.
revert_temporary_config() -> None
Okay so this one reloads the user's original configuration files after a temporary save π. Basically it should reinstall the user's original config files for all saves that happened with temporary=True.
Raises .ReverterError β when it can't revert the config π.
rollback_checkpoints(rollback: int = 1) -> None
Reverts rollback number of configuration checkpoints. The default is 1, so it'll roll back one checkpoint if you don't say otherwise.
Parameters:
rollback(int) β number of checkpoints to reverse. Astrnum gets cast to an integer, so"2"is also acceptable β¨.
Raises .ReverterError β if there's a problem with the input, or if the function can't correctly revert the configuration checkpoints.
add_to_temp_checkpoint(save_files: set[str], save_notes: str) -> None
Adds files to a temporary checkpoint π.
Parameters:
save_files(set) β set of filepaths to savesave_notes(str) β notes about changes during the save
add_to_checkpoint(save_files: set[str], save_notes: str) -> None
Same energy, but permanent π β adds files to a permanent checkpoint.
Parameters:
save_files(set) β set of filepaths to savesave_notes(str) β notes about changes during the save
register_file_creation(temporary: bool, *files: str) -> None
Registers the creation of all files during certbot execution. Call this before writing to the file, so the file is guaranteed to get cleaned up if the program exits unexpectedly (i.e. before a save occurs) π«Ά.
Parameters:
temporary(bool) β whether the file creation registry is for a temp or permanent save*filesβ file paths (str) to be registered
Raises certbot.errors.ReverterError β if the call doesn't contain the necessary parameters, or if the file creation can't be registered.
register_undo_command(temporary: bool, command: Iterable[str]) -> None
Registers a command to be run to undo actions taken.
β οΈ Warning: this function does not enforce order of operations when it comes to file modification vs. command registration. All undo commands are run first, before all normal files get reverted to their previous state. If you need to maintain strict order, you can create checkpoints before and after the command registration. This function may be improved in the future based on demand π
Parameters:
temporary(bool) β whether the command should be saved in theIN_PROGRESSorTEMPORARYcheckpointscommand(listofstr) β command to be run
recovery_routine() -> None
Reverts the configuration to the most recent finalized checkpoint. Removes all changes (temporary and permanent) that haven't been finalized. This is genuinely useful for protecting against crashes and other execution interruptions π₯.
Raises .errors.ReverterError β if it's unable to recover the configuration.
finalize_checkpoint(title: str) -> None
Finalizes the checkpoint. Timestamps and permanently saves all changes made through the use of add_to_checkpoint() and register_file_creation() β¨.
Parameters:
title(str) β title describing the checkpoint
Raises certbot.errors.ReverterError β when the checkpoint isn't able to be finalized.
β¨ certbot.util module β¨
Utilities for all Certbot π οΈ.
ποΈ class certbot.util.Key(file: str | None, pem: bytes)
Bases: NamedTuple
Container for an optional file path and contents for a PEM-formatted private key π.
file: str | Noneβ alias for field number 0pem: bytesβ alias for field number 1
π class certbot.util.CSR(file: str | None, data: bytes, form: str)
Bases: NamedTuple
Container for an optional file path and contents for a PEM or DER-formatted CSR πΈ.
file: str | Noneβ alias for field number 0data: bytesβ alias for field number 1form: strβ alias for field number 2
π¦ class certbot.util.LooseVersion(version_string: str)
Bases: object
A version with loose rules β like, any given string is a valid version number. But regular comparison is not supported. Instead, the try_risky_comparison method is provided, which may return an error if two LooseVersions are "incomparable" β for example when integer and string version components are present in the same position π.
Differences with the old distutils.version.LooseVersion: most version comparisons should give the same result. However, if a version has multiple trailing zeroes, not all of them are used in the comparison. This ensures that, for example, "2.0" and "2.0.0" are equal π.
π§ try_risky_comparison(other: LooseVersion) -> int
Compares the LooseVersion to another value.
If the other value is another LooseVersion, the version components get compared. Otherwise, an exception is raised.
Comparison is performed element-wise. If the version components being compared are of different types, the two versions are considered incompatible. Otherwise, if either of the components isn't equal to the other, less or greater is returned based on the comparison's result. In case the two versions are of different lengths, some elements in the longer version haven't been compared yet. If these are all equal to zero, the two versions are equal. Otherwise, the longer version is greater.
If the two versions are incompatible, an exception is raised. Otherwise, the returned integer tells you the result of the comparison:
- if
self == other,0is returned - if
self > other,1is returned - if
self < other,-1is returned
and those are the LooseVersion.try_risky_comparison receipts, bestie β equality is giving 0, inequality is giving 1 / -1, and the incomparable one straight-up throws a ValueError. No cap. β¨
Examples: Equality: -
LooseVersion('1.0').try_risky_comparison(LooseVersion('1.0'))
-> 0 -
LooseVersion('2.0.0a').try_risky_comparison(LooseVersion('2.0.0a'))
-> 0 Inequality: -
LooseVersion('2.0.0').try_risky_comparison(LooseVersion('1.0'))
-> 1 -
LooseVersion('1.0.1').try_risky_comparison(LooseVersion('2.0a'))
-> -1 Incomparability: -
LooseVersion('1a').try_risky_comparison(LooseVersion('1.0'))
-> ValueError
certbot.util.env_no_snap_for_external_calls() -> dict[str, str] π«Ά
okay so picture this: when Certbot is run inside a Snap, certain environment variables are modified. But Certbot sometimes calls out to external programs, since it uses classic confinement. When we do that, we must modify the env to remove our modifications so it will use the system's libraries, since they may be incompatible with the versions of libraries included in the Snap. For example, apachectl, Nginx, and anything run from inside a hook should call this function and pass the results into the env argument of subprocess.Popen.
- Returns β A modified copy of
os.environready to pass toPopen - Return type β
dict
certbot.util.run_script(params: list[str], log: ~typing.Callable[[str], None] = <bound method Logger.error of <Logger certbot.util (WARNING)>>) -> tuple[str, str] π
Run the script with the given params. Literally that's the whole vibe.
- Parameters:
params(list) β List of parameters to pass tosubprocess.runlog(callable) β Logger method to use for errors
certbot.util.exe_exists(exe: str) -> bool π
Determine whether path/name refers to an executable.
- Parameters:
exe(str) β Executable path or name
- Returns β If
exeis a valid executable - Return type β
bool
certbot.util.lock_dir_until_exit(dir_path: str) -> None π
Lock the directory at dir_path until program exit. It's giving "do not touch my stuff" energy, fr fr.
- Parameters:
dir_path(str) β path to directory
- Raises β
errors.LockErrorβ if the lock is held by another process
certbot.util.set_up_core_dir(directory: str, mode: int, strict: bool) -> None π
Ensure directory exists with proper permissions and is locked.
- Parameters:
directory(str) β Path to a directory.mode(int) β Directory mode.strict(bool) β require directory to be owned by current user
- Raises:
.errors.LockErrorβ if the directory cannot be locked.errors.Errorβ if the directory cannot be made or verified
certbot.util.make_or_verify_dir(directory: str, mode: int = 493, strict: bool = False) -> None πΈ
Make sure directory exists with proper permissions.
- Parameters:
directory(str) β Path to a directory.mode(int) β Directory mode. Default is493.strict(bool) β require directory to be owned by current user. Default isFalse.
- Raises:
.errors.Errorβ if a directory already exists, but has wrong permissions or ownerOSErrorβ if invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
certbot.util.safe_open(path: str, mode: str = 'w', chmod: int | None = None) -> IO π¦
Safely open a file. We love a safe queen.
- Parameters:
path(str) β Path to a file.mode(str) β Same os mode foropen. Default is'w'.chmod(int) β Same as mode forfilesystem.open, uses Python defaults ifNone. Default isNone.
- Return type β
IO
certbot.util.unique_file(path: str, chmod: int = 511, mode: str = 'w') -> tuple[IO, str] π
Safely finds a unique file.
- Parameters:
path(str) βpath/filename.extchmod(int) β File mode. Default is511.mode(str) β Open mode. Default is'w'.
- Returns β tuple of file object and file name
- Return type β
tuple[IO, str]
certbot.util.unique_lineage_name(path: str, filename: str, chmod: int = 420, mode: str = 'w') -> tuple[IO, str] π§
Safely finds a unique file using lineage convention.
- Parameters:
path(str) β directory pathfilename(str) β proposed filenamechmod(int) β file mode. Default is420.mode(str) β open mode. Default is'w'.
- 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. - Return type β
tuple[IO, str]
certbot.util.safely_remove(path: str) -> None π
Remove a file that may not exist. Lowkey useful.
certbot.util.get_filtered_names(all_names: set[str]) -> set[str] β
Removes names that aren't considered valid by Let's Encrypt.
- Parameters:
all_names(set) β all names found in the configuration
- Returns β all found names that are considered valid by LE
- Return type β
set
certbot.util.get_os_info() -> tuple[str, str] π
Get OS name and version.
- Returns β
(os_name, os_version) - Return type β
tupleofstr
certbot.util.get_os_info_ua() -> str π
Get OS name and version string for User Agent.
- Returns β
os_ua - Return type β
str
certbot.util.get_systemd_os_like() β list[str]
okay so this one pulls a list of strings that indicate the distribution likeness to other distributions π like, the whole "this distro is basically that distro" situation.
Returns β a list of distribution acronyms β¨
Return type β list of str
certbot.util.get_var_from_file(varname: str, filepath: str = '/etc/os-release') β str
grabs one single value out of a file that's formatted like the systemd /etc/os-release π and yes the default filepath is literally '/etc/os-release', iconic behavior.
Parameters
varname(str) β name of the variable to fetch πΈfilepath(str) β file path of the os-release file π¦
Returns β the requested value
Return type β str
certbot.util.get_python_os_info(pretty: bool = False) β tuple[str, str]
gets the Operating System type/distribution and major version using the python platform module π§ like it's reading your OS's vibes straight off the machine.
Parameters
pretty(bool) β if the returned OS name should be in longer (pretty) form π
Returns β (os_name, os_version)
Return type β tuple of str
certbot.util.safe_email(email: str) β bool
scrubs an email address before using it π«Ά that's it, that's the whole description, no cap.
class certbot.util.DeprecatedArgumentAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None, deprecated=False)
Bases: Action
an action to log a warning when an argument is used π like the function's whole job is to be the friend who quietly says "bestieβ¦ that flag is old."
certbot.util.add_deprecated_argument(add_argument: Callable[[...], None], argument_name: str, nargs: str | int) β None
adds a deprecated argument with the name argument_name π
lowkey the important part: deprecated arguments are not shown in the help. and if someone actually uses one on the command line, a warning is shown stating that the argument is deprecated and no other action is taken β like it just gets gently roasted and ignored, periodt.
Parameters
add_argument(callable) β function that adds arguments to an argument parser/group πargument_name(str) β name of the deprecated argument πnargsβ value fornargswhen adding the argument toargparseβ
certbot.util.enforce_le_validity(domain: str) β str
checks that Let's Encrypt will consider domain to be valid π
Parameters
domain(str) β FQDN to check π¦
Returns β the domain cast to str, with ASCII-only contents β¨
Return type β str
Raises ConfigurationError β for invalid domains and cases where Let's Encrypt currently will not issue certificates π
certbot.util.enforce_domain_sanity(domain: str | bytes) β str
a method which validates the domain value and errors out if the requirements are not met π it's giving bouncer-at-the-club energy, fr fr.
Parameters
domain(strorbytes) β domain to check π
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 πΈ
Return type β str
certbot.util.is_ipaddress(address: str) β bool
is the given address a string form of an IP (v4 or v6) address? π§ literally just a vibe check on whether it's an IP.
Parameters
address(str) β address to check π
Returns β True if address is a valid IP address, otherwise return False π₯
Return type β bool
certbot.util.is_wildcard_domain(domain: str | bytes) β bool
and yes, the original docstring genuinely opens with a stray"beforeIs domain a wildcard domain?β we keep it, it's part of the lore π
so: is domain a wildcard domain? π¦
Parameters
domain(bytesorstr) β domain to check π
Returns β True if domain is a wildcard, otherwise, False β
Return type β bool
certbot.util.is_staging(srv: str) β bool
determines whether a given ACME server is a known test / staging server π super useful so you don't think you're being iconic in prod when you're actually on staging.
Parameters
srv(str) β the URI for the ACME server π
Returns β True iff srv is a known test / staging server π
Rtype bool
certbot.util.atexit_register(func: Callable, *args: Any, **kwargs: Any) β None
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 π«Ά like, boundaries! child processes don't get to trigger it, that's main-character-only behavior.
Parameters
func(function) β function to be called in case of an error π
certbot.util.parse_loose_version(version_string: str) β list[int | str]
parses a version string into its components β¨ and listen, the original docstring for this one is straight-up raw, so here it is as-written:
Parses a version string into its components. This code and the
returned tuple is based on the now deprecated
distutils.version.LooseVersion class from the Python standard
library. Two LooseVersion classes and two lists as returned by
this function should compare in the same way. See <https://github
.com/python/cpython/blob/v3.10.0/Lib/distutils/version.py#L205-L347>.
:param str version_string: version string :returns: list of parsed
version string components :rtype: list
so yeah β :param str version_string: is the version string, :returns: a list of parsed version string components, :rtype: a list π and it compares the same way LooseVersion did, even though distutils is now deprecated π
π¦ the little nav links, because they're part of the page too
- Index
- Module Index
- Search Page
π Author
Certbot
π Copyright
2014-2018 β The Certbot software and documentation are licensed under the Apache 2.0 license as described at https://eff.org/cb-license.
and that's the whole page, bestie, we made it to the end π one tiny note on the types: every str, bool, list, tuple, int, bytes, Callable, Any and None up there is hyperlinked out to the official Python docs on docs.python.org in the original β that's a Sphinx thing, not me being extra (okay, maybe a little extra) π
πΈ version 5.8 πΈ dated Sep 01, 2026 β the source/version-and-date footer, delivered with a curtsy π«Ά you're welcome, go fix your certs, ily π
π¦ where this page comes from
- arch rolling: certbot 5.8.0-1 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms