Coverage for certbot/storage.py : 99%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
"""Renewable certificates storage."""
"""Build a list of all renewal configuration files.
:param certbot.interfaces.IConfig config: Configuration object
:returns: list of renewal configuration files :rtype: `list` of `str`
"""
"""Return /path/to/certname.conf in the renewal conf directory""" "{1}).".format(certname, path))
""" If `--cert-name` was specified, but you need a value for `--cert-path`.
:param `configuration.NamespaceConfig` config: parsed command line arguments :param str cert_name: cert name.
"""
"""Merge supplied config, if provided, on top of builtin defaults."""
"""Parse the time specified time interval, and add it to the base_time
The interval can be in the English-language format understood by parsedatetime, e.g., '10 days', '3 weeks', '6 months', '9 hours', or a sequence of such intervals like '6 months 1 week' or '3 days 12 hours'. If an integer is found with no associated unit, it is interpreted by default as a number of days.
:param datetime.datetime base_time: The time to be added with the interval. :param str interval: The time interval to parse.
:returns: The base_time plus the interpretation of the time interval. :rtype: :class:`datetime.datetime`"""
# try to use the same timezone, but fallback to UTC
"""Writes a renewal config file with the specified name and values.
:param str o_filename: Absolute path to the previous version of config file :param str n_filename: Absolute path to the new destination of config file :param str archive_dir: Absolute path to the archive directory :param dict target: Maps ALL_FOUR to their symlink paths :param dict relevant_data: Renewal configuration options to save
:returns: Configuration object for the new config file :rtype: configobj.ConfigObj
"""
"Options used in " "the renewal process"]
# TODO: add human-readable comments explaining other available # parameters
# Ensure that the file exists
# Copy permissions from the old version of the file, if it exists.
"""Renames cli_config.certname's config to cli_config.new_certname.
:param .NamespaceConfig cli_config: parsed command line arguments """ "is already in use.") "for the new certificate name.")
"""Modifies lineagename's config to contain the specified values.
:param str lineagename: Name of the lineage being modified :param str archive_dir: Absolute path to the archive directory :param dict target: Maps ALL_FOUR to their symlink paths :param .NamespaceConfig cli_config: parsed command line arguments
:returns: Configuration object for the updated config file :rtype: configobj.ConfigObj
"""
# If an existing tempfile exists, delete it
# Save only the config items that are relevant to renewal
"""Get an absolute path to the target of link.
:param str link: Path to a symbolic link
:returns: Absolute path to the target of link :rtype: str
:raises .CertStorageError: If link does not exists.
""" except OSError: raise errors.CertStorageError( "Expected {0} to be a symlink".format(link))
"`{prefix}privkey.pem` : the private key for your certificate.\n" "`{prefix}fullchain.pem`: the certificate file used in most server software.\n" "`{prefix}chain.pem` : used for OCSP stapling in Nginx >=1.3.7.\n" "`{prefix}cert.pem` : will break many server configurations, and " "should not be used\n" " without reading further documentation (see link below).\n\n" "WARNING: DO NOT MOVE OR RENAME THESE FILES!\n" " Certbot expects these files to remain in this location in order\n" " to function properly!\n\n" "We recommend not moving these files. For more information, see the Certbot\n" "User Guide at https://certbot.eff.org/docs/using.html#where-are-my-" "certificates.\n".format(prefix=prefix))
""" Is this option one that could be restored for future renewal purposes? :param str option: the name of the option
:rtype: bool """
any(option.startswith(namespace) for namespace in namespaces))
"""Return a new dict containing only items relevant for renewal.
:param dict all_values: The original values.
:returns: A new dictionary containing items that can be used in renewal. :rtype dict:
""" (option, value) for option, value in six.iteritems(all_values) if _relevant(option) and cli.option_was_set(option, value)) # We always save the server value to help with forward compatibility # and behavioral consistency when versions of Certbot with different # server defaults are used.
"""Returns the lineagename for a configuration filename. """ "renewal config file name must end in .conf")
"""Returns the lineagename for a configuration filename. """
"""Path to a directory from a file"""
"""Returns the full archive path for a lineagename
Uses cli_config to determine archive path if not available from config_obj.
:param configobj.ConfigObj config_obj: Renewal conf file contents (can be None) :param configuration.NamespaceConfig cli_config: Main config file :param str lineagename: Certificate name """ else:
"""Returns the full default live path for a lineagename"""
"""Delete all files related to the certificate.
If some files are not found, ignore them and continue. """ # file exists # config is corrupted "delete the contents of %s and %s.", renewal_filename, full_default_live_dir, full_default_archive_dir) "error parsing {0}".format(renewal_filename)) finally: # we couldn't read it, but let's at least delete it # if this was going to fail, it already would have.
# cert files and (hopefully) live directory # it's not guaranteed that the files are in our default storage # structure. so, first delete the cert files.
# if all four were in the same directory, and the only thing left # is the README file (or nothing), delete that directory. # this will be wrong in very few but some cases. # delete the README file # if it's now empty, delete the directory
# archive directory
# pylint: disable=too-many-instance-attributes,too-many-public-methods """Renewable certificate.
Represents a lineage of certificates that is under the management of Certbot, indicated by the existence of an associated renewal configuration file.
Note that the notion of "current version" for a lineage is maintained on disk in the structure of symbolic links, and is not explicitly stored in any instance variable in this object. The RenewableCert object is able to determine information about the current (or other) version by accessing data on disk, but does not inherently know any of this information except by examining the symbolic links as needed. The instance variables mentioned below point to symlinks that reflect the notion of "current version" of each managed object, and it is these paths that should be used when configuring servers to use the certificate managed in a lineage. These paths are normally within the "live" directory, and their symlink targets -- the actual cert files -- are normally found within the "archive" directory.
:ivar str cert: The path to the symlink representing the current version of the certificate managed by this lineage. :ivar str privkey: The path to the symlink representing the current version of the private key managed by this lineage. :ivar str chain: The path to the symlink representing the current version of the chain managed by this lineage. :ivar str fullchain: The path to the symlink representing the current version of the fullchain (combined chain and cert) managed by this lineage. :ivar configobj.ConfigObj configuration: The renewal configuration options associated with this lineage, obtained from parsing the renewal configuration file and/or systemwide defaults.
""" """Instantiate a RenewableCert object from an existing lineage.
:param str config_filename: the path to the renewal config file that defines this lineage. :param .NamespaceConfig: parsed command line arguments
:raises .CertStorageError: if the configuration file's name didn't end in ".conf", or the file is missing or broken.
"""
# self.configuration should be used to read parameters that # may have been chosen based on default values from the # systemwide renewal configuration; self.configfile should be # used to make and save changes. "error parsing {0}".format(config_filename)) # TODO: Do we actually use anything from defaults and do we want to # read further defaults from the systemwide renewal configuration # file at this stage?
"renewal config file {0} is missing a required " "file reference".format(self.configfile))
util.get_strict_version(conf_version) > CURRENT_VERSION): "Attempting to parse the version %s renewal configuration " "file found at %s with version %s of Certbot. This might not " "work.", conf_version, config_filename, certbot.__version__)
def key_path(self): """Duck type for self.privkey"""
def cert_path(self): """Duck type for self.cert"""
def chain_path(self): """Duck type for self.chain""" return self.chain
def fullchain_path(self): """Duck type for self.fullchain"""
def target_expiry(self): """The current target certificate's expiration datetime
:returns: Expiration datetime of the current target certificate :rtype: :class:`datetime.datetime` """ return crypto_util.notAfter(self.current_target("cert"))
def archive_dir(self): """Returns the default or specified archive directory""" self.cli_config, self.lineagename)
"""Returns the default or specified archive directory as a relative path
Used for creating symbolic links. """
def is_test_cert(self): """Returns true if this is a test cert from a staging server.""" else:
"""Raises an exception if a symlink doesn't exist""" "expected {0} to be a symlink".format(link)) "not exist".format(target, link))
"""Updates symlinks to use archive_dir""" os.path.basename(previous_link))
"""Are the files associated with this lineage self-consistent?
:returns: Whether the files stored in connection with this lineage appear to be correct and consistent with one another. :rtype: bool
""" # Each element must be referenced with an absolute path "absolute path.", x)
# Each element must exist and be a symbolic link
# Each element's link must point within the cert lineage's # directory within the official archive directory "cert lineage's directory within the " "official archive directory. Link: %s, " "target directory: %s, " "archive directory: %s. If you've specified " "the archive directory in the renewal configuration " "file, you may need to update links by running " "certbot update_symlinks.", link, os.path.dirname(target), self.archive_dir)
# The link must point to a file that exists link, target)
# The link must point to a file that follows the archive # naming convention "convention.", target)
# It is NOT required that the link's target be a regular # file (it may itself be a symlink). But we should probably # do a recursive check that ultimately the target does # exist? # XXX: Additional possible consistency checks (e.g. # cryptographic validation of the chain being a chain, # the chain matching the cert, and the cert matching # the subject key) # XXX: All four of the targets are in the same directory # (This check is redundant with the check that they # are all in the desired directory!) # len(set(os.path.basename(self.current_target(x) # for x in ALL_FOUR))) == 1
"""Attempt to fix defects or inconsistencies in this lineage.
.. todo:: Currently unimplemented.
""" # TODO: Figure out what kinds of fixes are possible. For # example, checking if there is a valid version that # we can update the symlinks to. (Maybe involve # parsing keys and certs to see if they exist and # if a key corresponds to the subject key of a cert?)
# TODO: In general, the symlink-reading functions below are not # cautious enough about the possibility that links or their # targets may not exist. (This shouldn't happen, but might # happen as a result of random tampering by a sysadmin, or # filesystem errors, or crashes.)
"""Returns the kind and path of all symlinks used in recovery.
:returns: list of (kind, symlink) tuples :rtype: list
"""
"""Fixes symlinks in the event of an incomplete version update.
If there is no problem with the current symlinks, this function has no effect.
"""
"""Returns full path to which the specified item currently points.
:param str kind: the lineage member item ("cert", "privkey", "chain", or "fullchain")
:returns: The path to the current version of the specified member. :rtype: str or None
""" link, kind)
"""Returns numerical version of the specified item.
For example, if kind is "chain" and the current chain link points to a file named "chain7.pem", returns the integer 7.
:param str kind: the lineage member item ("cert", "privkey", "chain", or "fullchain")
:returns: the current version of the specified member. :rtype: int
""" "does not exist at %s.", kind, target) else:
"""The filename that corresponds to the specified version and kind.
.. warning:: The specified version may not exist in this lineage. There is no guarantee that the file path returned by this method actually exists.
:param str kind: the lineage member item ("cert", "privkey", "chain", or "fullchain") :param int version: the desired version
:returns: The path to the specified version of the specified member. :rtype: str
"""
"""Which alternative versions of the specified kind of item exist?
The archive directory where the current version is stored is consulted to obtain the list of alternatives.
:param str kind: the lineage member item ( ``cert``, ``privkey``, ``chain``, or ``fullchain``)
:returns: all of the version numbers that currently exist :rtype: `list` of `int`
"""
"""Newest available version of the specified kind of item?
:param str kind: the lineage member item (``cert``, ``privkey``, ``chain``, or ``fullchain``)
:returns: the newest available version of this member :rtype: int
"""
"""Newest version for which all items are available?
:returns: the newest available version for which all members (``cert, ``privkey``, ``chain``, and ``fullchain``) exist :rtype: int
""" # TODO: this can raise CertStorageError if there is no version overlap # (it should probably return None instead) # TODO: this can raise a spurious AttributeError if the current # link for any kind is missing (it should probably return None)
"""Smallest version newer than all full or partial versions?
:returns: the smallest version number that is larger than any version of any item currently stored in this lineage :rtype: int
""" # TODO: consider locking/mutual exclusion between updating processes # This isn't self.latest_common_version() + 1 because we don't want # collide with a version that might exist for one file type but not # for the others.
"""Make sure we've deployed the latest version.
:returns: False if a change was needed, True otherwise :rtype: bool
May need to recover from rare interrupted / crashed states."""
"fixing...")
"""Is there a later version of all of the managed items?
:returns: ``True`` if there is a complete version of this lineage with a larger version number than the current version, and ``False`` otherwise :rtype: bool
""" # TODO: consider whether to assume consistency or treat # inconsistent/consistent versions differently
"""Make the specified item point at the specified version.
(Note that this method doesn't verify that the specified version exists.)
:param str kind: the lineage member item ("cert", "privkey", "chain", or "fullchain") :param int version: the desired version
""" # Relative rather than absolute target directory # TODO: it could be safer to make the link first under a temporary # filename, then unlink the old link, then rename the new link # to the old link; this ensures that this process is able to # create symlinks. # TODO: we might also want to check consistency of related links # for the other corresponding items
"""Change all member objects to point to the specified version.
:param int version: the desired version
"""
"""What are the subject names of this certificate?
(If no version is specified, use the current version.)
:param int version: the desired version number :returns: the subject names :rtype: `list` of `str` :raises .CertStorageError: if could not find cert file.
""" else:
# pylint: disable=no-self-use,unused-argument """Is the specified cert version revoked according to OCSP?
Also returns True if the cert version is declared as intended to be revoked according to Let's Encrypt OCSP extensions. (If no version is specified, uses the current version.)
This method is not yet implemented and currently always returns False.
:param int version: the desired version number
:returns: whether the certificate is or will be revoked :rtype: bool
""" # XXX: This query and its associated network service aren't # implemented yet, so we currently return False (indicating that the # certificate is not revoked).
"""Is automatic renewal enabled for this cert?
If autorenew is not specified, defaults to True.
:returns: True if automatic renewal is enabled :rtype: bool
""" self.configuration["renewalparams"].as_bool("autorenew"))
"""Should we now try to autorenew the most recent cert version?
This is a policy question and does not only depend on whether the cert is expired. (This considers whether autorenewal is enabled, whether the cert is revoked, and whether the time interval for autorenewal has been reached.)
Note that this examines the numerically most recent cert version, not the currently deployed version.
:returns: whether an attempt should now be made to autorenew the most current cert version in this lineage :rtype: bool
""" # Consider whether to attempt to autorenew this cert now
# Renewals on the basis of revocation
# Renews some period before expiry time "cert", self.latest_common_version())) "expiry %s.", interval, expiry.strftime("%Y-%m-%d %H:%M:%S %Z"))
def new_lineage(cls, lineagename, cert, privkey, chain, cli_config): # pylint: disable=too-many-locals """Create a new certificate lineage.
Attempts to create a certificate lineage -- enrolled for potential future renewal -- with the (suggested) lineage name lineagename, and the associated cert, privkey, and chain (the associated fullchain will be created automatically). Optional configurator and renewalparams record the configuration that was originally used to obtain this cert, so that it can be reused later during automated renewal.
Returns a new RenewableCert object referring to the created lineage. (The actual lineage name, as well as all the relevant file paths, will be available within this object.)
:param str lineagename: the suggested name for this lineage (normally the current cert's first subject DNS name) :param str cert: the initial certificate version in PEM format :param str privkey: the private key in PEM format :param str chain: the certificate chain in PEM format :param .NamespaceConfig cli_config: parsed command line arguments
:returns: the newly-created RenewalCert object :rtype: :class:`storage.renewableCert`
"""
# Examine the configuration and find the new lineage's name cli_config.live_dir): cli_config.renewal_configs_dir, lineagename)
# Determine where on disk everything will go # lineagename will now potentially be modified based on which # renewal configuration file could actually be created "archive directory exists for " + lineagename) "live directory exists for " + lineagename) "directory %s created.", archive, live_dir)
# Put the data into the appropriate files on disk for kind in ALL_FOUR]) for kind in ALL_FOUR]) # XXX: Let's make sure to get the file permissions right here # assumes that OpenSSL.crypto.dump_certificate includes # ending newline character
# Write a README file to the live directory
# Document what we've done in a new renewal config file
# Save only the config items that are relevant to renewal
target, values)
new_privkey, new_chain, cli_config): """Save new cert and chain as a successor of a prior version.
Returns the new version number that was created.
.. note:: this function does NOT update links to deploy this version
:param int prior_version: the old version to which this version is regarded as a successor (used to choose a privkey, if the key has not changed, but otherwise this information is not permanently recorded anywhere) :param bytes new_cert: the new certificate, in PEM format :param bytes new_privkey: the new private key, in PEM format, or ``None``, if the private key has not changed :param bytes new_chain: the new chain, in PEM format :param .NamespaceConfig cli_config: parsed command line arguments
:returns: the new version number that was created :rtype: int
""" # XXX: assumes official archive location rather than examining links # XXX: consider using os.open for availability of os.O_EXCL # XXX: ensure file permissions are correct; also create directories # if needed (ensuring their permissions are correct) # Figure out what the new version is and hence where to save things
[(kind, os.path.join(self.archive_dir, "{0}{1}.pem".format(kind, target_version))) for kind in ALL_FOUR])
self.archive_dir, "privkey{0}.pem".format(prior_version))
# Distinguish the cases where the privkey has changed and where it # has not changed (in the latter case, making an appropriate symlink # to an earlier privkey version) # The behavior below keeps the prior key by creating a new # symlink to the old key or the target of the old key symlink. else: else: # Preserve gid and (mode & 074) from previous privkey in this lineage. (stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | \ stat.S_IROTH)
# Save everything else
# Update renewal config file self.lineagename, self.archive_dir, symlinks, cli_config)
|