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.

here's the whole link drop, no gatekeeping:


πŸ” 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 πŸ’…

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:

  1. If you added a cron job or systemd timer to automatically run certbot-auto to renew your certificates, you should delete it. If you did this by following our instructions, you can delete the entry added to /etc/crontab by running a command like sudo sed -i '/certbot-auto/d' /etc/crontab.
  2. Delete the certbot-auto script. If you placed it in /usr/local/bin like we recommended, you can delete it by running sudo rm /usr/local/bin/certbot-auto.
  3. Delete the Certbot installation created by certbot-auto by running sudo 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: the certbot script on your web server might actually be named letsencrypt if your system is running an older package. So literally anywhere in these docs that you see certbot, just swap in the correct name as needed. iykyk.

πŸ”₯ Getting certificates (and choosing plugins) πŸ”₯

Certbot helps you achieve two tasks. Two! Iconic behavior:

  1. 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.
  2. 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.

⭐ little recap just so it's loud and clear: apache and nginx do both jobs, webroot, standalone and 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) and dns-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-known gets treated specially by your webserver configuration, you might need to modify that configuration to make sure files inside /.well-known/acme-challenge are 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:

πŸ™ˆ 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 β€” Auth and Inst. Y means yes, N means no. And yes, the notes column is where the personality lives.

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 --expand option, you use the -d option 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 the delete subcommand. I'm serious β€” do NOT go in there with rm, 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:

  1. Find all references to the certificate (substitute example.com in 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
  1. 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.pem and 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
  1. 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
  1. 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 renew exit status will only be 1 if a renewal attempt failed. That means certbot renew exit status will be 0 if no certificate needs to be updated. If you write a custom script and expect to run a command only after a certificate was actually renewed, you'll need to use --deploy-hook, because the exit status is 0 both on successful renewal and when renewal isn't necessary. Sneaky little 0, 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:

  1. 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. πŸ¦‹

  1. 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
  1. 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. πŸ“

  1. 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-name can be anything you want; by default it's the first domain listed on the cert.
  2. 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.
  3. Restart your webserver, if applicable. πŸ”„
  4. 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

  1. 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. πŸ§ͺ
  2. 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:

  1. 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
  1. 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:

  1. 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.
  2. 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 renew command in either your system's crontab (typically /etc/crontab or /etc/cron.*/*) or systemd timers (systemctl list-timers).
  3. 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 $domain used in the path /etc/letsencrypt/live/$domain follows this convention: - it is the name given to --cert-name, - if --cert-name is 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 be example.com, - if a name collision would occur with a certificate already named example.com, the new certificate name will be constructed using a numerical sequence as example.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 version 0.29.0, private keys for new certificate default to 0600. 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.pem and chain.pem (less common) β€” cert.pem contains the server certificate by itself, and chain.pem contains the additional intermediate certificate or certificates that web browsers will need in order to validate the server certificate. If you provide one of these files to your web server, you must provide both of them, or some browsers will show "This Connection is Untrusted" errors for your site, some of the time https://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 using openssl. You can automate that with --deploy-hook if 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 authenticated
  • CERTBOT_VALIDATION: The validation string
  • CERTBOT_TOKEN: Resource name part of the HTTP-01 challenge (HTTP-01 only)
  • CERTBOT_REMAINING_CHALLENGES: Number of challenges remaining after the current challenge
  • CERTBOT_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-run uses the Let's Encrypt staging server β€” unless --server is specified on the CLI or in the cli.ini configuration file. So take caution when using --dry-run with 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.ini if $XDG_CONFIG_HOME is 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 traditional logrotate script. 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, --config CONFIG_FILE β€” path to config file. Default is /etc/letsencrypt/cli.ini and ~/.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-backups MAX_LOG_BACKUPS β€” Specifies the maximum number of backup logs that should be kept by Certbot's built in log rotation. Setting this flag to 0 disables log rotation entirely, causing Certbot to always append to the same log file. Default: 1000. (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 the renew subcommand. Default: False.
  • -d, --domains, --domain DOMAIN β€” Domain names to include. For multiple domains you can use multiple -d flags 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 -0001 will be appended to the certificate name. Default: Ask. (First domain = main character energy, lowkey πŸ‘‘)
  • --ip-address IP_ADDRESSES β€” IP addresses to include. For multiple IP addresses you can use multiple --ip-address flags. All IP addresses will be included as Subject Alternative Names on the certificate. Default: [].
  • --eab-kid EAB_KID β€” Key Identifier for External Account Binding. Default: None.
  • --eab-hmac-key EAB_HMAC_KEY β€” HMAC key for External Account Binding. Default: None.
  • --eab-hmac-alg EAB_HMAC_ALG β€” HMAC algorithm for External Account Binding. Default: HS256.
  • --cert-name CERTNAME β€” Certificate name to apply. This name is used by Certbot for housekeeping and in file paths; it doesn't affect the content of the certificate itself. Certificate name cannot contain filepath separators (i.e. '/' or '\', depending on the platform). To see certificate names, run certbot certificates. When creating a new certificate, specifies the new certificate's name. Default: the first provided domain or the name of an existing certificate on your system for the same domains.
  • --dry-run β€” Perform a test run against the Let's Encrypt staging server, obtaining test (invalid) certificates but not saving them to disk. This can only be used with the certonly and renew subcommands. It may trigger webserver reloads to temporarily modify & roll back configuration files. --pre-hook and --post-hook commands run by default. --deploy-hook commands 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 -v option, the challenge URLs or FQDNs and their expected return values are shown. Default: False.
  • --required-profile REQUIRED_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, setting preferred_profile instead may be preferable because it allows fallback to a default. Use this setting when renewal failure is preferable to fallback. Default: None.
  • --preferred-profile PREFERRED_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-chain PREFERRED_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-challenges PREF_CHALLS β€” A sorted, comma delimited list of the preferred challenge to use during authorization with the most preferred challenge listed first (Eg, "dns" or "http,dns"). Not all plugins support all challenges. See https://certbot.eff.org/docs/using.html#plugins for details. ACME Challenges are versioned, but if you pick "http" rather than "http-01", Certbot will select the latest version automatically. Default: [].
  • --issuance-timeout ISSUANCE_TIMEOUT β€” This option specifies how long (in seconds) Certbot will wait for the server to issue a certificate. Default: 90.
  • --user-agent USER_AGENT β€” Set a custom user agent string for the client. User agent strings allow the CA to collect high level statistics about success rates by OS, plugin and use case, and to know when to deprecate support for past Python versions and flags. If you wish to hide this information from the Let's Encrypt server, set this to "". Default: CertbotACMEClient/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-comment USER_AGENT_COMMENT β€” Add a comment to the default user agent string. May be used when repackaging Certbot or calling it from another tool to allow additional statistical data to be collected. Ignored if --user-agent is set. (Example: Foo-Wrapper/1.0) Default: None.

πŸ€– automation πŸ€–

Flags for automating execution & other tweaks β€” 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 the run subcommand 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-expiring is 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-key on an existing certificate. (default: False)
  • --new-key β€” when renewing or replacing a certificate, generate a fresh new private key, even if --reuse-key is set on the existing certificate. heads up though: combining --new-key and --reuse-key means 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 the Strict-Transport-Security header 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 use https:// for every http:// 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-run or reconfigure, 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 using reconfigure. (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 the REQUESTS_CA_BUNDLE environment 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 (with certonly --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 Certbot
  • delete β€” clean up all files related to a certificate
  • renew β€” renew all certificates (or one specified with --cert-name)
  • revoke β€” revoke a certificate specified with --cert-path or --cert-name
  • reconfigure β€” 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 the PATH environment variable. While this command runs, the shell variable $RENEWED_LINEAGE points 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_DOMAINS holds 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 --csr only works with the certonly subcommand, 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-validation is used, the command's first word must be the absolute pathname of an executable or one found via the PATH environment 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-validation is used, the command's first word must be the absolute pathname of an executable or one found via the PATH environment 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-hook get 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 the renew subcommand 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 --authenticator or --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 Apache a2enmod binary lives (default: None)
  • --apache-dismod APACHE_DISMOD β€” where the Apache a2dismod binary 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 the apache2/httpd binary (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-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/nginx or /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 -d or --ip-address for 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 / -d entries. At present, if you put webroot-map in a config file, it needs to be on a single line, like: webroot-map = {"example.com":"/var/www"}. (default: {})

πŸ’¬ 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 --version output
  • 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.os instead of os
  • 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 execute run_acme_server --help to see the inline help of the run_acme_server tool.
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 code
  • certbot β€” main client code
  • certbot-apache and certbot-nginx β€” client code to configure specific web servers
  • certbot-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:

  1. Be consistent with the rest of the code.
  2. Read PEP 8 - Style Guide for Python Code <https://www.python.org/dev/peps/pep-0008>.
  3. 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
  1. Remember to use pylint.
  2. 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 🫢
  3. Please avoid unittest.assertTrue or unittest.assertFalse when possible, and use assertEqual or 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:

  1. 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.
  2. 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 mypy on a machine that has Python 3 installed.
  3. 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.
  4. Run tox run -e lint to check for pylint errors. Fix any errors.
  5. Run tox --skip-missing-interpreters to run all the tests we recommend developers run locally. The --skip-missing-interpreters argument ignores missing versions of Python needed for running the tests. Fix any errors.
  6. If any documentation should be added or updated as part of the changes you have made, please include the documentation changes in your PR.
  7. 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.
  8. 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:

  1. Install Homebrew at https://brew.sh/. It is the most popular package manager on macOS by a wide margin and works well enough.
  2. 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.
  3. 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) 🫢

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 πŸ”:

  • BF6BCFC89E90747B9A680FD7B6029E8500F7DB16
  • 86379B4F0AF371B50CD9E5FF3402831161D1D280
  • 20F201346BF8F3F455A73F9A780CC99432A28621
  • F2871B4152AE13C49519111F447BF683AA3B26C3

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

  1. Please use our tagged releases, not main! fr fr, do not package the live branch πŸ™ˆ
  2. Do not package certbot-compatibility-test as it's only used internally.
  3. To run tests on our packages, you should use pytest by running the command python -m pytest. Running pytest directly may not work because PYTHONPATH is not handled the same way and local modules may not be found by the test runner. (ask us how we know 😭)
  4. If you'd like to include automated renewal in your package:
    • certbot renew -q should be added to crontab or systemd timer.
    • 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-renewal should be included on the CLI or in cli.ini for all invocations of Certbot, so that it can adjust its interactive output regarding automated renewal (Certbot >= 1.9.0).
  5. jws is an internal script for acme module and it doesn't have to be packaged β€” it's mostly for debugging: you can use it as echo foo | jws sign | jws verify.
  6. 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 $domain is 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 file
  • mode (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 file
  • dst (str) β€” Path of the destination file
  • mode (int) β€” Permission mode to apply on the destination file
  • copy_user (bool) β€” Copy user if True
  • copy_group (bool) β€” Copy group if True on 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 file
  • dst (str) β€” Path of the destination file
  • copy_user (bool) β€” copies the user over if True
  • copy_group (bool) β€” copies the group over if True on 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 file
  • mode (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 check
  • mode (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 open
  • flags (int) β€” flags to apply on the file while it's opened
  • mode (int) β€” POSIX mode to apply on the file when opened; Python defaults will be applied if None

Returns: the file descriptor to the opened file

Return type: int

Raise OSError(errno.EEXIST) if the file already exists and os.O_CREAT & os.O_EXCL are set, and OSError(errno.EACCES) on Windows if the file already exists and is a directory, and os.O_CREAT is 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 open
  • mode (int) β€” POSIX mode to apply on the leaf directory when it's created; Python defaults apply if None

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 open
  • mode (int) β€” POSIX mode to apply on the directory when created; Python defaults apply if None

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(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 key
  • base_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 file
  • path2 (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 check
  • min_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, work or logs)

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 run
  • shell_cmd (str) β€” shell command to execute
  • env (dict) β€” environ to pass into subprocess.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) β€” Method os.access() is forbidden
  • certbot.compat.os.chmod(*unused_args, **unused_kwargs) β€” Method os.chmod() is forbidden
  • certbot.compat.os.chown(*unused_args, **unused_kwargs) β€” Method os.chown() is forbidden
  • certbot.compat.os.fstat(*unused_args, **unused_kwargs) β€” Method os.stat() is forbidden
  • certbot.compat.os.mkdir(*unused_args, **unused_kwargs) β€” Method os.mkdir() is forbidden
  • certbot.compat.os.open(*unused_args, **unused_kwargs) β€” Method os.open() is forbidden
  • certbot.compat.os.rename(*unused_args, **unused_kwargs) β€” Method os.rename() is forbidden
  • certbot.compat.os.replace(*unused_args, **unused_kwargs) β€” Method os.replace() is forbidden
  • certbot.compat.os.stat(*unused_args, **unused_kwargs) β€” Method os.stat() is forbidden
  • certbot.compat.os.umask(*unused_args, **unused_kwargs) β€” Method os.chmod() is forbidden
  • certbot.compat.os.makedirs(*unused_args, **unused_kwargs) β€” Method os.makedirs() is forbidden
ik the fstat one says os.stat() and the umask one says os.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) β€” True if 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 one Account

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 from
  • question (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 object
  • question (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, and logging β†’ https://docs.python.org/3/library/logging.html#module-logging. Also input_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 is unused_domains in the signature but the parameter doc calls it domains β€” 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 says list here while the signature annotates it str. 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 command
  • returncode (int) β€” The exit code of the executed command
  • stdout (str) β€” The stdout output of the executed command
  • stderr (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 an errors.Error, its text will be displayed and the user will be re-prompted.
  • *args (list) β€” Arguments to be passed to input_text.
  • **kwargs (dict) β€” Arguments to be passed to input_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 an errors.Error, its text will be displayed and the user will be re-prompted.
  • *args (list) β€” Arguments to be passed to directory_select.
  • **kwargs (dict) β€” Arguments to be passed to directory_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 display
  • pause (bool) β€” Whether or not the program should pause for the user's confirmation
  • wrap (bool) β€” Whether or not the application should wrap text
  • force_interactive (bool) β€” True if it's safe to prompt the user because it won't cause any workflow regressions
  • decorate (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 menu
  • choices (list of tuples (tag, item) or list of descriptions (tags will be enumerated)) β€” Menu lines, len must be > 0
  • default β€” default value to return, if interaction is not possible
  • cli_flag (str) β€” option used to set this value with the CLI
  • force_interactive (bool) β€” True if it's safe to prompt the user because it won't cause any workflow regressions

Returns β€” tuple of (code, index) where code β€” str display exit code, index β€” int index of the user's selection

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 text
  • default β€” default value to return, if interaction is not possible 🫢
  • cli_flag (str) β€” option used to set this value with the CLI
  • force_interactive (bool) β€” True if 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 user
  • yes_label (str) β€” Label of the "Yes" parameter
  • no_label (str) β€” Label of the "No" parameter
  • default β€” default value to return, if interaction is not possible
  • cli_flag (str) β€” option used to set this value with the CLI
  • force_interactive (bool) β€” True if 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 user
  • tags (list) β€” str tags to select, and note the condition: len(tags) > 0 (so like, at least one, obviously πŸ’…)
  • default β€” default value to return, if interaction is not possible
  • cli_flag (str) β€” option used to set this value with the CLI
  • force_interactive (bool) β€” True if it's safe to prompt the user because it won't cause any workflow regressions

Returns β€” tuple of (code, tags) where code β€” str display exit code, 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 user
  • default β€” default value to return, if interaction is not possible
  • cli_flag (str) β€” option used to set this value with the CLI
  • force_interactive (bool) β€” True if it's safe to prompt the user because it won't cause any workflow regressions

Returns β€” tuple of the form (code, string) where code β€” display exit code, 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 user
  • default β€” default answer to prompt
  • cli_flag (str) β€” command line option for setting an answer to this question
  • force_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 to argparse.ArgumentParser.add_argument prepending 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, periodt
  • dest(var: str) -> str β€” find a destination for the given variable var πŸ¦‹
  • conf(var: str) -> Any β€” find a configuration value for variable var
  • auth_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_hint belongs in Authenticator but can't be added until the next major version of Certbot. For now, it lives in .Plugin and auth_handler will only call it on authenticators that subclass .Plugin. For now, inherit from Plugin to implement and/or override the method. πŸ’€

Parameters

  • failed_achalls (list) β€” list of one or more failed challenges (achallenges.AnnotatedChallenge subclasses).

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 save
  • save_notes (str) β€” notes about changes during the save
  • temporary (bool) β€” True if the files should be added to a temporary checkpoint rather than a permanent one. This is usually used for changes that will soon be reverted.

Raises .errors.PluginError β€” when unable to add to checkpoint 😬

  • 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 the ssl_dhparams file ⭐
  • updated_ssl_dhparams_digest (property, str) β€” full absolute path to the digest of the updated ssl_dhparams file
  • install_ssl_dhparams() -> None β€” copy Certbot's ssl_dhparams file 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 address
  • port (str) β€” port number or *, or ""
  • classmethod fromstring(str_addr: str) -> GenericAddr β€” initialize Addr from string πŸŽ€
  • normalized_tuple() -> tuple[str, str] β€” normalized representation of the addr/port tuple
  • get_addr() -> str β€” return the addr part of the Addr object
  • get_port() -> str β€” return the port
  • get_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 plugin
  • achalls (list of KeyAuthorizationAnnotatedChallenge) β€” annotated challenges
  • indices (list of int) β€” 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 when perform() is called.

Parameters

  • achall (.KeyAuthorizationAnnotatedChallenge) β€” annotated challenge
  • idx (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

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 of AnnotatedChallenge (#certbot.achallenges.AnnotatedChallenge) instances, such that it contains types found within get_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 of AnnotatedChallenge (#certbot.achallenges.AnnotatedChallenge) instances, a subset of those previously passed to perform().

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() -> None
  • test_get_chall_pref() -> None
  • test_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 of RequestException.
  • 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() -> None
  • test_add_txt_record_try_twice_to_find_domain() -> None
  • test_add_txt_record_fail_to_find_domain() -> None
  • test_add_txt_record_fail_to_authenticate() -> None
  • test_add_txt_record_fail_to_authenticate_with_unknown_error() -> None
  • test_add_txt_record_error_finding_domain() -> None
  • test_add_txt_record_error_adding_record() -> None
  • test_del_txt_record() -> None
  • test_del_txt_record_fail_to_find_domain() -> None
  • test_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() β†’ returns None
  • test_del_txt_record_error_finding_domain() β†’ returns None
  • test_del_txt_record_error_deleting_record() β†’ returns None

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 of RequestException
    • LOGIN_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: None
  • ensure-http-header: name of header (i.e. Strict-Transport-Security)
  • ocsp-stapling: certificate chain file path
  • certbot.plugins.enhancements.enabled_enhancements(config: NamespaceConfig) -> Generator[dict[str, Any], None, None] β€” a generator πŸ’« that yields the enabled new style enhancements. Take a config (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
  • certbot.plugins.enhancements.enable(lineage: RenewableCert | None, domains: Iterable[str], installer: Installer | None, config: NamespaceConfig) -> None β€” run the enable method for each requested enhancement that is supported. This is the "go actually do the thing" function 🫢
    • Parameters:
      • lineage (certbot.interfaces.RenewableCert) β€” Certificate lineage object
      • domains (str) β€” List of domains in certificate to enhance
      • installer (interfaces.Installer) β€” Installer object
      • config (certbot.configuration.NamespaceConfig) β€” Configuration.
  • certbot.plugins.enhancements.populate_cli(add: Callable[[...], None]) -> None β€” populates the command line flags for certbot._internal.cli.HelpfulParser. Parameter: add (func) β€” the add function of certbot._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_autohsts is called when the header is initially installed using a low max-age value.
  • update_autohsts is called every time when Certbot is run using the 'renew' verb. The max-age value should be increased over time using this method.
  • deploy_autohsts is called for every lineage that has had its certificate renewed. A long HSTS max-age value should be set here, as we should be confident that the user is able to automatically renew their certificates.

  • 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: the prepare() method inherited from interfaces.Plugin might 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 object
    • domains (list of str) β€” 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/c returns ['/a/b/c', '/a/b', '/a', '/']
  • (Windows) C:abc returns ['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 the PATH

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) β€” a Status object
  • challs (list) β€” Challenge objects
  • statuses (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 for
  • cert_path (str) β€” absolute path to the certificate file
  • key_path (str) β€” absolute path to the private key file
  • chain_path (str) β€” absolute path to the certificate chain file
  • fullchain_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 enhancement
  • enhancement (str) β€” an enhancement as defined in ENHANCEMENTS
  • options β€” flexible options parameter for the enhancement. Check the documentation of ENHANCEMENTS for 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. title has no effect if temporary is 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 to argparse.ArgumentParser.add_argument prepending 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 directory
  • testfile (str) β€” configuration file to base the lineage on
  • ec (bool) β€” True if 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.util to 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 a write method

Returns

  • patch on the function used internally by certbot.display.util to 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 lock
  • path_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 β€” Wrapped ChallengeBody.
  • 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:

  • challb
  • domain
  • account_key
  • identifier

πŸŽ€ class certbot.achallenges.DNS(**kwargs: Any)

Bases: AnnotatedChallenge

Client annotated "dns" ACME challenge.

  • acme_type β€” alias of DNS
  • challb
  • domain
  • identifier

πŸ¦‹ class certbot.achallenges.Other(**kwargs: Any)

Bases: AnnotatedChallenge

Client annotated ACME challenge of an unknown type.

  • acme_type β€” alias of Challenge
  • challb
  • domain
  • identifier

πŸ”₯ 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 is rsa.
  • 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 is ecdsa.
  • keyname (str) β€” Filename of key
  • strict_permissions (bool) β€” If true and key_dir exists, an exception is raised if the directory doesn't have 0700 permissions or isn't owned by the current user.

Returns: Key

Return type: certbot.util.Key

Raises ValueError β€” If unable to generate the key given key_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 CSR
  • names (set) β€” str names to include in the CSR
  • path (str) β€” Optional certificate save directory.
  • must_staple (bool) β€” If true, include the TLS Feature extension "OCSP Must-Staple"
  • strict_permissions (bool) β€” If true and path exists, an exception is raised if the directory doesn't have 0755 permissions 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 filename
  • data (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 filename
  • data (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 if key_type=rsa. Gotta be at least 2048 for RSA, no shortcuts bestie πŸ’…
  • key_type (str) β€” the type of key to generate, and it has to be rsa or ecdsa
  • elliptic_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:

  1. Signature verification for the cert.
  2. That fullchain matches cert and chain when concatenated.
  3. 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) β€” the public_key to check signature
  • signature (bytes) β€” the signature bytes
  • payload (bytes) β€” the payload bytes
  • signature_hash_algorithm (hashes.HashAlgorithm) β€” algorithm used to hash the payload

Raises

  • InvalidSignature β€” if signature verification fails
  • errors.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 format
  • key_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

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

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 between MisconfigurationError and NoInstallationError is 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).

  1. Be nice and prepend all options and destinations with option_namespace and dest_namespace.
  2. 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 of AnnotatedChallenge instances, such that it contains types found within get_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 of AnnotatedChallenge instances, a subset of those previously passed to perform().

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 file
  • cert_path (str) β€” absolute path to the certificate file
  • key_path (str) β€” absolute path to the private key file
  • chain_path (str) β€” absolute path to the certificate chain file
  • fullchain_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 enhancement
  • enhancement (str) β€” An enhancement as defined in ENHANCEMENTS
  • options β€” Flexible options parameter for enhancement. Check documentation of ENHANCEMENTS for 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. title has no effect if temporary is 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:

  1. 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 when revert_temporary_config() or recovery_routine() is called.
  2. 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 when recovery_routine() is called.
  3. 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 to rollback_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. A str num 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 save
  • save_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 save
  • save_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 the IN_PROGRESS or TEMPORARY checkpoints
  • command (list of str) β€” 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 0
  • pem: 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 0
  • data: bytes β€” alias for field number 1
  • form: 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, 0 is returned
  • if self > other, 1 is returned
  • if self < other, -1 is 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.environ ready to pass to Popen
  • 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 to subprocess.run
    • log (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 exe is 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 is 493.
    • strict (bool) β€” require directory to be owned by current user. Default is False.
  • Raises:
    • .errors.Error β€” if a directory already exists, but has wrong permissions or owner
    • OSError β€” if invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.

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 for open. Default is 'w'.
    • chmod (int) β€” Same as mode for filesystem.open, uses Python defaults if None. Default is None.
  • 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.ext
    • chmod (int) β€” File mode. Default is 511.
    • 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 path
    • filename (str) β€” proposed filename
    • chmod (int) β€” file mode. Default is 420.
    • 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 β€” tuple of str

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 for nargs when adding the argument to argparse ⭐

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 (str or bytes) β€” 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 " before Is domain a wildcard domain? β€” we keep it, it's part of the lore πŸ’€

so: is domain a wildcard domain? πŸ¦‹

Parameters

  • domain (bytes or str) β€” 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 πŸ’€


  • Index
  • Module Index
  • Search Page

πŸ‘‘ Author

Certbot

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