????

Your IP : 18.222.144.72


Current Path : /usr/lib/python3.6/site-packages/certbot/_internal/__pycache__/
Upload File :
Current File : //usr/lib/python3.6/site-packages/certbot/_internal/__pycache__/storage.cpython-36.pyc

3

گa���@sTdZddlZddlZddlZddlZddlZddlZddlmZddlm	Z	ddlm
Z
ddlmZddlmZddlm
Z
dd	lmZddlZdd
lmZddlmZddlmZddlZddlZddlZddlZdd
lmZddlmZddlmZddlmZddlmZddlmZddl m!Z!ddl m"Z"ddl m#Z#ddl$m%Z&ddl'm(Z(ddl'm)Z)ddl*m+Z,ej-e.�Z/dWZ0dZ1ej2ej3�Z4dZ5ej6ee7d �d!d"�Z8ej6e7e7d#�d$d%�Z9ej6e7e7d&�d'd(�Z:dXe
ej6ej;d �d)d*�Z<ej=�feje7ej=ejd+�d,d-�Z>e7e7e7ee7e7fee7efej;d.�d/d0�Z?e7e7ej6dd1�d2d3�Z@e7e7ee7e7fej6ej;d4�d5d6�ZAe7e7d7�d8d9�ZBdYe7eCdd;�d<d=�ZDe
e7e7eCd>�d?d@�ZEee7efe	e7efdA�dBdC�ZFe7e7dD�dEdF�ZGej6e7e7dG�dHdI�ZHe7e7e7dJ�dKdL�ZIej;ej6e7e7dM�dNdO�ZJej6e7e7dP�dQdR�ZKej6e7dd#�dSdT�ZLGdUdV�dVejM�ZMdS)ZzRenewable certificates storage.�N)�Any)�Dict)�Iterable)�List)�Mapping)�Optional)�Tuple)�default_backend)�
RSAPrivateKey)�load_pem_private_key)�
configuration)�crypto_util)�errors)�
interfaces)�ocsp)�util)�cli)�	constants)�
error_handler)�disco)�
filesystem)�os)�common�cert�privkey�chain�	fullchain�READMEi�)�config�returncCs"tjtjj|jd��}|j�|S)z�Build a list of all renewal configuration files.

    :param configuration.NamespaceConfig config: Configuration object

    :returns: list of renewal configuration files
    :rtype: `list` of `str`

    z*.conf)�globr�path�join�renewal_configs_dir�sort)r�result�r&�/usr/lib/python3.6/storage.py�renewal_conf_files/s	r()r�certnamercCs8tjj|jdj|��}tjj|�s4tjdj||���|S)z;Return /path/to/certname.conf in the renewal conf directoryz{0}.confz2No certificate found with name {0} (expected {1}).)rr!r"r#�format�existsr�CertStorageError)rr)r!r&r&r'�renewal_file_for_certname=s

r-)r�	cert_namercCst||�}tj|ddd�dS)z� 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.

    zutf-8)�encoding�default_encodingr)r-�	configobj�	ConfigObj)rr.Zcert_name_implied_confr&r&r'�cert_path_for_cert_nameFs
r3cCs6tjtjddd�}|j|dk	r"|ntjddd��|S)z?Merge supplied config, if provided, on top of builtin defaults.zutf-8)r/r0N)r1r2r�RENEWER_DEFAULTS�merge)rZ
defaults_copyr&r&r'�config_with_defaultsRs
r6)�	base_time�interval�
textparserrcCs4|j�j�r|d7}|jptj}|j|||d�dS)a�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`z days)�tzinfor)�strip�isdigitr:�pytz�UTCZparseDT)r7r8r9r:r&r&r'�add_time_interval\sr?)�
o_filename�
n_filename�archive_dir�target�
relevant_datarcCstj|ddd�}tj|d<||d<xtD]}||||<q(Wd|krZi|d<ddg|jd<|dj|�x"|dD]}||krr|d|=qrWd|kr�tjd}d	|g|_	t
jd
|�t|d��WdQRXt
jj|�r�tjt
j|�j�}	tj||	�t|d
��}
|j|
d�WdQRX|S)aWrites 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

    zutf-8)r/r0�versionrB�
renewalparams�z#Options used in the renewal process�renew_before_expiryzrenew_before_expiry = zWriting new config %s.�aN�wb)Zoutfile)r1r2�certbot�__version__�ALL_FOURZcomments�updaterr4Zinitial_comment�logger�debug�openrr!r+�stat�S_IMODE�lstat�st_moder�chmod�write)r@rArBrCrDr�kind�k�default_intervalZcurrent_permissions�fr&r&r'�write_renewal_configvs2



r\)�	prev_name�new_name�
cli_configrcCs^t||�}t||�}tjj|�r*tjd��ytj||�Wntk
rXtjd��YnXdS)z�Renames cli_config.certname's config to cli_config.new_certname.

    :param .NamespaceConfig cli_config: parsed command line
        arguments
    z+The new certificate name is already in use.z=Please specify a valid filename for the new certificate name.N)	� renewal_filename_for_lineagenamerr!r+rZConfigurationErrorr�replace�OSError)r]r^r_Z
prev_filenameZnew_filenamer&r&r'�rename_renewal_config�s


rc)�lineagenamerBrCr_rcCsbt||�}|d}tjj|�r(tj|�tt|j��}t|||||�t	j
||�tj|ddd�S)a�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

    z.newzutf-8)r/r0)
r`rr!r+�unlink�relevant_values�vars�	namespacer\rrar1r2)rdrBrCr_�config_filenameZ
temp_filename�valuesr&r&r'�update_configuration�s

rk)�linkrcCsbytj|�}Wn$tk
r2tjdj|���YnXtjj|�sVtjj	tjj
|�|�}tjj|�S)z�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.

    zExpected {0} to be a symlink)r�readlinkrbrr,r*rr!�isabsr"�dirname�abspath)rlrCr&r&r'�get_link_target�srqF)�readme_path�is_base_dirrcCsDd}|rd}t|d��$}tjd|�|jdj|d��WdQRXdS)NrGz[cert name]/�wzWriting README to %s.a�This directory contains your keys and certificates.

`{prefix}privkey.pem`  : the private key for your certificate.
`{prefix}fullchain.pem`: the certificate file used in most server software.
`{prefix}chain.pem`    : used for OCSP stapling in Nginx >=1.3.7.
`{prefix}cert.pem`     : will break many server configurations, and should not be used
                 without reading further documentation (see link below).

WARNING: DO NOT MOVE OR RENAME THESE FILES!
         Certbot expects these files to remain in this location in order
         to function properly!

We recommend not moving these files. For more information, see the Certbot
User Guide at https://certbot.eff.org/docs/using.html#where-are-my-certificates.
)�prefix)rQrOrPrWr*)rrrsrur[r&r&r'�_write_live_readme_to�srv)�
namespaces�optionrcs,ddlm}�|jkp*t�fdd�|D��S)z�
    Is this option one that could be restored for future renewal purposes?

    :param namespaces: plugin namespaces for configuration options
    :type namespaces: `list` of `str`
    :param str option: the name of the option

    :rtype: bool
    r)�renewalc3s|]}�j|�VqdS)N)�
startswith)�.0rh)rxr&r'�	<genexpr>sz_relevant.<locals>.<genexpr>)�certbot._internalryZCONFIG_ITEMS�any)rwrxryr&)rxr'�	_relevants

r)�
all_valuesrcsBtjj�}dd�|D��t�fdd�|j�D��}|d|d<|S)z�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:

    cSsg|]}tj|��qSr&)�plugins_commonZdest_namespace)r{Zpluginr&r&r'�
<listcomp>"sz#relevant_values.<locals>.<listcomp>c3s0|](\}}t�|�rtj||�r||fVqdS)N)rrZoption_was_set)r{rx�value)rwr&r'r|%sz"relevant_values.<locals>.<genexpr>�server)�
plugins_discoZPluginsRegistryZfind_all�dict�items)r�Zplugins�rvr&)rwr'rfs	

rf)rircCs.|jd�stjd��tjj|dtd���S)z:Returns the lineagename for a configuration filename.
    z.confz*renewal config file name must end in .confN)�endswithrr,rr!�basename�len)rir&r&r'�lineagename_for_filename/s
r�)rrdrcCstjj|j|�dS)z:Returns the lineagename for a configuration filename.
    z.conf)rr!r"r#)rrdr&r&r'r`8sr`)rB�	from_filercCstjj|tjj|��S)zPath to a directory from a file)rr!�relpathro)rBr�r&r&r'�_relpath_from_file?sr�)�
config_objr_rdrcCs$|rd|kr|dStjj|j|�S)aMReturns 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
    rB)rr!r"�default_archive_dir)r�r_rdr&r&r'�full_archive_pathDs
r�)r_rdrcCstjj|j|�S)z4Returns the full default live path for a lineagename)rr!r"�live_dir)r_rdr&r&r'�_full_live_pathSsr�c)Cs�t||�}td||�}t||�}zPytj|ddd�}Wn6tjk
rltjd|||�tj	dj
|���YnXWdtj|�tj
d|�Xt�}xhtD]`}|j|�}ytj|�tjd|�Wn tk
r�tjd|�YnXtjj|�}	|j|	�q�Wt|�dk�r�|j�}	tjj|	t�}
ytj|
�tjd|
�Wn"tk
�rZtjd|
�YnXytj|	�tjd|	�Wn"tk
�r�tjd	|	�YnXy&t|||�}tj|�tjd|�Wn"tk
�r�tjd
|�YnXdS)zmDelete all files related to the certificate.

    If some files are not found, ignore them and continue.
    Nzutf-8)r/r0zNCould not parse %s. You may wish to manually delete the contents of %s and %s.zerror parsing {0}z
Removed %szUnable to delete %s�z&Unable to remove %s; may not be empty.zUnable to remove %s)r-r�r�r1r2�ConfigObjErrorrO�errorrr,r*r�remove�info�setrM�getrPrbr!ro�addr��popr"r�rmdir�shutilZrmtree)rr)Zrenewal_filenameZfull_default_archive_dirZfull_default_live_dirZrenewal_configZdirectory_namesrXrlZ	directoryrrZarchive_pathr&r&r'�delete_filesXsV








r�c@s�eZdZdZdReejedd�dd�Ze	ed�dd	��Z
e	ed�d
d��Ze	ed�dd
��Ze	ed�dd��Z
e	ed�dd��Ze	ejd�dd��Ze	ed�dd��Zeed�dd�Ze	eed�dd��Ze	ed�dd��Zdd�dd�Zdd�dd �Zed�d!d"�Zdd�d#d$�Zeeeefd�d%d&�Zdd�d'd(�Zeeed)�d*d+�Zeeed)�d,d-�Z eeed.�d/d0�Z!eeed)�d1d2�Z"eed)�d3d4�Z#ed�d5d6�Z$ed�d7d8�Z%ed�d9d:�Z&ed�d;d<�Z'eedd.�d=d>�Z(edd?�d@dA�Z)eed�dBdC�Z*eed?�dDdE�Z+ed�dFdG�Z,ed�dHdI�Z-e.ee/e/e/ejddJ�dKdL��Z0e	ed�dMdN��Z1ee/e/e/ejedO�dPdQ�Z2dS)S�
RenewableCertaRenewable 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.

    FN)rir_�update_symlinksrc
s|�_t|��_ytj|ddd��_Wn&tjk
rLtjdj	|���YnXt
�j��_t�fdd�t
D��s�tjdj	�j����jjd�}|dk	r�tj|�tkr�tjd	||tj��jd
�_�jd�_�jd�_�jd
�_tjj�j��_�j�|�r�j��j �dS)aInstantiate 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.

        zutf-8)r/r0zerror parsing {0}c3s|]}|�jkVqdS)N)r)r{�x)�selfr&r'r|�sz)RenewableCert.__init__.<locals>.<genexpr>z<renewal config file {0} is missing a required file referencerENzzAttempting to parse the version %s renewal configuration file found at %s with version %s of Certbot. This might not work.rrrr)!r_r��_lineagenamer1r2�
configfiler�rr,r*r6r�allrMr��
pkg_resources�
parse_version�CURRENT_VERSIONrOr�rKrLrrrrrr!ror��
_fix_symlinks�_update_symlinks�_check_symlinks)r�rir_r�Zconf_versionr&)r�r'�__init__�s8

zRenewableCert.__init__)rcCs|jS)zDuck type for self.privkey)r)r�r&r&r'�key_path�szRenewableCert.key_pathcCs|jS)zDuck type for self.cert)r)r�r&r&r'�	cert_path�szRenewableCert.cert_pathcCs|jS)zDuck type for self.chain)r)r�r&r&r'�
chain_path�szRenewableCert.chain_pathcCs|jS)zDuck type for self.fullchain)r)r�r&r&r'�fullchain_pathszRenewableCert.fullchain_pathcCs|jS)zEName given to the certificate lineage.

        :rtype: str

        )r�)r�r&r&r'rdszRenewableCert.lineagenamecCs"|jd�}|stjd��tj|�S)z�The current target certificate's expiration datetime

        :returns: Expiration datetime of the current target certificate
        :rtype: :class:`datetime.datetime`
        rz"Target certificate does not exist.)�current_targetr�Errorr
�notAfter)r�r�r&r&r'�
target_expirys

zRenewableCert.target_expirycCst|j|j|j�S)z2Returns the default or specified archive directory)r�rr_rd)r�r&r&r'rBszRenewableCert.archive_dir)r�rcCst|j|�S)zyReturns the default or specified archive directory as a relative path

        Used for creating symbolic links.
        )r�rB)r�r�r&r&r'�relative_archive_dir#sz"RenewableCert.relative_archive_dircCs|jdjdd�S)z8Returns the ACME server associated with this certificaterFr�N)rr�)r�r&r&r'r�*szRenewableCert.servercCs|jrtj|j�SdS)z:Returns true if this is a test cert from a staging server.F)r�rZ
is_staging)r�r&r&r'�is_test_cert/szRenewableCert.is_test_certcCs^xXtD]P}t||�}tjj|�s0tjdj|���t|�}tjj	|�stjdj||���qWdS)z.Raises an exception if a symlink doesn't existzexpected {0} to be a symlinkz(target {0} of symlink {1} does not existN)
rM�getattrrr!�islinkrr,r*rqr+)r�rXrlrCr&r&r'r�6s

zRenewableCert._check_symlinkscCsVxPtD]H}t||�}t|�}tjj|j|�tjj|��}tj|�tj	||�qWdS)z#Updates symlinks to use archive_dirN)
rMr�rqrr!r"r�r�re�symlink)r�rXrl�
previous_linkZnew_linkr&r&r'r�Bs


zRenewableCert._update_symlinkscCsx8|j|j|j|jfD] }tjj|�stjd|�dSqWx8|j|j|j|jfD] }tjj	|�sPtjd|�dSqPWx�t
D]�}t||�}t|�}tjj
tjj|�|j�s�tjd|tjj|�|j�dStjj|�s�tjd||�dStjdj|��}|jtjj|��sztjd|�dSqzWdS)	z�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

        z3Element %s is not referenced with an absolute path.Fz"Element %s is not a symbolic link.a-Element's link does not point within the cert lineage's directory within the official archive directory. Link: %s, target directory: %s, archive directory: %s. If you've specified the archive directory in the renewal configuration file, you may need to update links by running certbot update_symlinks.z.Link %s points to file %s that does not exist.z^{0}([0-9]+)\.pem$z1%s does not follow the archive naming convention.T)rrrrrr!rnrOrPr�rMr�rq�samefilerorBr+�re�compiler*�matchr�)r�r�rXrlrC�patternr&r&r'�_consistentMs4


zRenewableCert._consistentcCsdS)zpAttempt to fix defects or inconsistencies in this lineage.

        .. todo:: Currently unimplemented.

        Nr&)r�r&r&r'�_fix�szRenewableCert._fixcCsJg}x@tD]8}tjjt||��}dj|�}|j|tjj||�f�q
W|S)z�Returns the kind and path of all symlinks used in recovery.

        :returns: list of (kind, symlink) tuples
        :rtype: list

        zprevious_{0}.pem)rMrr!ror�r*�appendr")r��previous_symlinksrXZlink_dirZ	link_baser&r&r'�_previous_symlinks�s

z RenewableCert._previous_symlinkscCs�|j�}tdd�|D��r^xB|D]:\}}t||�}tjj|�rHtj|�tjtj	|�|�q Wx&|D]\}}tjj
|�rdtj|�qdWdS)z�Fixes symlinks in the event of an incomplete version update.

        If there is no problem with the current symlinks, this function
        has no effect.

        css|]}tjj|d�VqdS)r�N)rr!r+)r{rlr&r&r'r|�sz.RenewableCert._fix_symlinks.<locals>.<genexpr>N)r�r�r�rr!�lexistsrer�rrmr+)r�r�rXr�Zcurrent_link�_rlr&r&r'r��s

zRenewableCert._fix_symlinks)rXrcCsB|tkrtjd��t||�}tjj|�s:tjd||�dSt	|�S)a(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

        zunknown kind of itemz*Expected symlink %s for %s does not exist.N)
rMrr,r�rr!r+rOrPrq)r�rXrlr&r&r'r��s

zRenewableCert.current_targetcCs�|tkrtjd��tjdj|��}|j|�}|dksBtjj	|�rTt
jd||�d}|jtjj
|��}|rzt|j�d�St
jd|�dS)a�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

        zunknown kind of itemz^{0}([0-9]+)\.pem$Nz3Current-version target for %s does not exist at %s.rGrzNo matches for target %s.)rMrr,r�r�r*r�rr!r+rOrPr�r��int�groups)r�rXr�rC�matchesr&r&r'�current_version�s


zRenewableCert.current_version)rXrErcCsT|tkrtjd��|j|�}|s2tjd|�d���tjj|�}tjj|dj	||��S)a�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

        zunknown kind of itemzTarget z does not exist!z
{0}{1}.pem)
rMrr,r�r�rr!ror"r*)r�rXrErl�wherer&r&r'rE�s

zRenewableCert.versioncs||tkrtjd��|j|�}|s2tjd|�d���tjj|�}tj|�}t	j
dj|����fdd�|D�}tdd�|D��S)a�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`

        zunknown kind of itemzTarget z does not exist!z^{0}([0-9]+)\.pem$csg|]}�j|��qSr&)r�)r{r[)r�r&r'r� sz4RenewableCert.available_versions.<locals>.<listcomp>cSs g|]}|rt|j�d��qS)r)r�r�)r{�mr&r&r'r�!s)
rMrr,r�r�rr!ro�listdirr�r�r*�sorted)r�rXrlr��filesr�r&)r�r'�available_versionss



z RenewableCert.available_versionscCst|j|��S)aNewest 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

        )�maxr�)r�rXr&r&r'�newest_available_version#s
z&RenewableCert.newest_available_versioncs,�fdd�tD��t�fdd��dD��S)z�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

        csg|]}�j|��qSr&)r�)r{r�)r�r&r'r�;sz7RenewableCert.latest_common_version.<locals>.<listcomp>c3s0|](�t�fdd��dd�D��r�VqdS)c3s|]}�|kVqdS)Nr&)r{�v)�nr&r'r|<sz@RenewableCert.latest_common_version.<locals>.<genexpr>.<genexpr>r�N)r�)r{)�versions)r�r'r|<sz6RenewableCert.latest_common_version.<locals>.<genexpr>r)rMr�)r�r&)r�r�r'�latest_common_version/sz#RenewableCert.latest_common_versioncst�fdd�tD��dS)z�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

        c3s|]}�j|�VqdS)N)r�)r{r�)r�r&r'r|Jsz2RenewableCert.next_free_version.<locals>.<genexpr>r�)r�rM)r�r&)r�r'�next_free_version>szRenewableCert.next_free_versioncCs(|j�r$tjd�|j|j��dSdS)z�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.zMFound a new certificate /archive/ that was not linked to in /live/; fixing...FT)�has_pending_deploymentrO�warning�update_all_links_tor�)r�r&r&r'�ensure_deployedLs

zRenewableCert.ensure_deployedcCsRg}x8tD]0}|j|�}|dkr0tj|�d���|j|�q
Wt|�}||j�kS)aIs 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

        Nz. is required but missing for this certificate.)rMr�rr�r��minr�)r�Zall_versions�itemrEZsmallest_currentr&r&r'r�[s	

z$RenewableCert.has_pending_deploymentcCs^|tkrtjd��t||�}dj||�}tjjtj	|��}tj
|�tjtjj||�|�dS)a7Make 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

        zunknown kind of itemz
{0}{1}.pemN)
rMrr,r�r*rr!rorrmrer�r")r�rXrErl�filenameZtarget_directoryr&r&r'�_update_link_toos


zRenewableCert._update_link_to)rErcCs�tj|j���|j�}x<|D]4\}}|j|�}|sDtjd|�d���tj||�qWxt	D]}|j
||�qZWx|D]\}}tj|�qtWWdQRXdS)zwChange all member objects to point to the specified version.

        :param int version: the desired version

        zTarget z does not exist!N)rZErrorHandlerr�r�r�rr�rr�rMr�re)r�rEZprevious_linksrXrlrCr�r&r&r'r��s

z!RenewableCert.update_all_links_toc	Cs@|jd�}|dkrtjd��t|d��}tj|j��SQRXdS)z�What are the subject names of this certificate?

        :returns: the subject names
        :rtype: `list` of `str`
        :raises .CertStorageError: if could not find cert file.

        rNz#could not find the certificate file�rb)r�rr,rQr
Zget_names_from_cert�read)r�rCr[r&r&r'�names�s


zRenewableCert.namescCsh|jd|�}|jd|�}ytj�j||�Stk
rb}ztjd|�tjt|��dSd}~XnXdS)a{Is the specified cert version revoked according to OCSP?

        Also returns True if the cert version is declared as revoked
        according to OCSP. If OCSP status could not be determined, False
        is returned.

        :param int version: the desired version number

        :returns: True if the certificate is revoked, otherwise, False
        :rtype: bool

        rrz4An error occurred determining the OCSP status of %s.FN)	rErZRevocationCheckerZocsp_revoked_by_paths�	ExceptionrOr�rP�str)r�rEr�r��er&r&r'�ocsp_revoked�s

zRenewableCert.ocsp_revokedcCsd|jdkp|jdjd�S)z�Is automatic renewal enabled for this cert?

        If autorenew is not specified, defaults to True.

        :returns: True if automatic renewal is enabled
        :rtype: bool

        Z	autorenewrF)rZas_bool)r�r&r&r'�autorenewal_is_enabled�s	z$RenewableCert.autorenewal_is_enabledcCs�|j�r�|j|j��r$tjd�dStjd}|jjd|�}t	j
|jd|j���}tj
jtjj��}|t||�kr�tjd||jd��dSdS)aTShould 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

        z%Should renew, certificate is revoked.TrHrz8Should renew, less than %s before certificate expiry %s.z%Y-%m-%d %H:%M:%S %ZF)r�r�r�rOrPrr4rr�r
r�rEr=r>Zfromutc�datetimeZutcnowr?Zstrftime)r�rZr8ZexpiryZnowr&r&r'�should_autorenew�s

zRenewableCert.should_autorenew)rdrrrr_rc"s�x<|j|j|jfD](}tjj|�stj|d�tj	d|�qWt
j|j|�\}}tjj|jt
�}	tjj|	�sxt|	dd�t|�}td||��t||��tjj��r�tjj��s�tj��r�|j�tjd|��tjj��o�tjj��s�tj���r|j�tjd|��x6��fD]*}tjj|��stj|�tj	d|��qW�fdd	�tD�}
�fd
d	�tD�}x,tD]$}tjt|||
|�|
|��qnWt|
dd�� }
tj	d
|
d�|
j|�WdQRXt
j|ddtd�� }tj	d|
d�|j|�WdQRXt|
dd�� }
tj	d|
d�|
j|�WdQRXt|
dd��$}
tj	d|
d�|
j||�WdQRXtjj�t
�}t|�|j�tt|j ��}t!||�|
|�}||j"|�S)a�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`

        i�zCreating directory %s.T)rsNzarchive directory exists for zlive directory exists for cs i|]}tjj�|d�|�qS)z.pem)rr!r")r{rX)r�r&r'�
<dictcomp>6sz-RenewableCert.new_lineage.<locals>.<dictcomp>cs i|]}tjj�|d�|�qS)z1.pem)rr!r")r{rX)�archiver&r'r�7srrJzWriting certificate to %s.r)rVzWriting private key to %s.rzWriting chain to %s.rzWriting full chain to %s.)#r#r�r�rr!r+r�makedirsrOrPrZunique_lineage_namer"rrvr�r�r��isdirr��closerr,rMr�r�rQrW�	safe_open�BASE_PRIVKEY_MODErfrgrhr\r�)�clsrdrrrr_�iZconfig_fileriZbase_readme_pathrCZarchive_targetrXZf_bZf_arrrjZ
new_configr&)r�r�r'�new_lineage�s`

$
&


$zRenewableCert.new_lineagecCsFt|jdd��}t|j�dt�d�}WdQRXt|t�r>dSdSdS)zc
        :returns: The type of algorithm for the private, RSA or ECDSA
        :rtype: str
        rr�N)�dataZpasswordZbackendZRSAZECDSA)rQrrr�r	�
isinstancer
)r�Z
priv_key_file�keyr&r&r'�private_key_typeXs
zRenewableCert.private_key_type)�
prior_version�new_cert�new_privkey�	new_chainr_rc!s�|�_�j����fdd�tD�}tjj�jdj|��}|dkr�tjj|�rXt	j
|�}n
dj|�}tjd|�tj
||d�n^tj|ddtd�� }tjd	|d�|j|�WdQRXt	j|t�}	t	j||d|	d
dd�t|d
d�� }tjd|d
�|j|�WdQRXt|dd�� }tjd|d�|j|�WdQRXt|dd��$}tjd|d�|j||�WdQRX�fdd�tD�}
t�j�j|
|��_t�j��_�S)a�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

        cs&i|]}tjj�jdj|���|�qS)z
{0}{1}.pem)rr!r"rBr*)r{rX)r��target_versionr&r'r��sz0RenewableCert.save_successor.<locals>.<dictcomp>zprivkey{0}.pemNz'Writing symlink to old private key, %s.rrJ)rVzWriting new private key to %s.FT)Z	copy_userZ
copy_grouprzWriting certificate to %s.rzWriting chain to %s.rzWriting full chain to %s.csi|]}�j||�qSr&)r)r{rX)r�r&r'r��s)r_r�rMrr!r"rBr*r�rrmrOrPr�rr�r�rWZcompute_private_key_modeZcopy_ownership_and_apply_moderQrkrdr�r6r)r�r�r�r�r�r_rCZold_privkeyr[�modeZsymlinksr&)r�r�r'�save_successoris@
zRenewableCert.save_successor)F)3�__name__�
__module__�__qualname__�__doc__r�r�NamespaceConfig�boolr��propertyr�r�r�r�rdr�r�rBr�rr�r�r�r�r�r�rrr�r�r�r�r�rEr�r�r�r�r�r�r�r�r�r�r�r��classmethod�bytesr�r�rr&r&r&r'r��sb"5D%^r�)rrrr)N)F)Nrr�r Zloggingr�r�rRZtypingrrrrrrrr1Zcryptography.hazmat.backendsr	Z-cryptography.hazmat.primitives.asymmetric.rsar
Z,cryptography.hazmat.primitives.serializationrZ
parsedatetimer�r=rKrr
rrrrr}rrrZcertbot._internal.pluginsrr�Zcertbot.compatrrZcertbot.pluginsrr�Z	getLoggerrrOrMrr�rLr�r�rr�r(r-r3r2r6ZCalendarr?r\rcrkrqrrvrrfr�r`r�r�r�r�r�r&r&r&r'�<module>s�
	


5 	C