U
    ÓZj¹J  ã                   @   s¤  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z
ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ e e¡Zdd„ Zdd„ Z e !d¡Z"e !dej#¡Z$e
j% &ej'¡G dd„ de(ƒƒZ)G dd„ de)ƒZ*G dd„ de(ƒZ+G dd„ de(ƒZ,G dd„ de,ƒZ-dd„ Z.d d!„ Z/G d"d#„ d#e(ƒZ0e0ej1e ƒej1e< dS )$zPlugin common functions.é    N)Úutil)ÚList)Úachallenges)Ú	constants)Úcrypto_util)Úerrors)Ú
interfaces)Úreverter)Úos)Ú
filesystem)ÚPluginStoragec                 C   s   | d S )ú9ArgumentParser options namespace (prefix of all options).ú-© ©Únamer   r   úY/var/www/html/TRUCKING_PROJECT/venv/lib/python3.8/site-packages/certbot/plugins/common.pyÚoption_namespace   s    r   c                 C   s   |   dd¡d S )ú;ArgumentParser dest namespace (prefix of all destinations).r   Ú_)Úreplacer   r   r   r   Údest_namespace$   s    r   zX(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)z3^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*[a-z]+$c                   @   sb   e Zd ZdZdd„ Zejdd„ ƒZedd„ ƒZ	e
dd	„ ƒZd
d„ Ze
dd„ ƒZdd„ Zdd„ ZdS )ÚPluginzGeneric plugin.c                 C   s   || _ || _d S ©N)Úconfigr   )Úselfr   r   r   r   r   Ú__init__5   s    zPlugin.__init__c                 C   s   dS )a°  Add plugin arguments to the CLI argument parser.

        NOTE: If some of your flags interact with others, you can
        use cli.report_config_interaction to register this to ensure
        values are correctly saved/overridable during renewal.

        :param callable add: Function that proxies calls to
            `argparse.ArgumentParser.add_argument` prepending options
            with unique plugin name prefix.

        Nr   )ÚclsÚaddr   r   r   Úadd_parser_arguments9   s    zPlugin.add_parser_argumentsc                    s   ‡ ‡fdd„}|   |¡S )zYInject parser options.

        See `~.IPlugin.inject_parser_options` for docs.

        c                    s   ˆj d tˆ ƒ| ¡f|ž|ŽS )Nz--{0}{1})Úadd_argumentÚformatr   )Zarg_name_no_prefixÚargsÚkwargs©r   Úparserr   r   r   O   s    ÿþþz)Plugin.inject_parser_options.<locals>.add)r   )r   r%   r   r   r   r$   r   Úinject_parser_optionsG   s    zPlugin.inject_parser_optionsc                 C   s
   t | jƒS )r   )r   r   ©r   r   r   r   r   V   s    zPlugin.option_namespacec                 C   s
   | j | S )z'Option name (include plugin namespace).)r   )r   r   r   r   r   Úoption_name[   s    zPlugin.option_namec                 C   s
   t | jƒS )r   )r   r   r'   r   r   r   r   _   s    zPlugin.dest_namespacec                 C   s   | j | dd¡ S )z.Find a destination for given variable ``var``.r   r   )r   r   ©r   Úvarr   r   r   Údestd   s    zPlugin.destc                 C   s   t | j|  |¡ƒS )z0Find a configuration value for variable ``var``.)Úgetattrr   r+   r)   r   r   r   Úconfj   s    zPlugin.confN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú	jose_utilÚabstractclassmethodr   Úclassmethodr&   Úpropertyr   r(   r   r+   r-   r   r   r   r   r   /   s   



r   c                       st   e Zd ZdZ‡ fdd„Zddd„Zdd„ Zd	d
„ Zdd„ Zddd„Z	dd„ Z
edd„ ƒZedd„ ƒZdd„ Z‡  ZS )Ú	Installerz‹An installer base class with reverter and ssl_dhparam methods defined.

    Installer plugins do not have to inherit from this class.

    c                    s4   t t| ƒj||Ž t| j| jƒ| _t | j¡| _d S r   )	Úsuperr6   r   r   r   r   Zstorager	   ZReverter)r   r"   r#   ©Ú	__class__r   r   r   u   s    zInstaller.__init__Fc              
   C   s\   |r| j j}n| j j}z|||ƒ W n2 tjk
rV } zt t|ƒ¡‚W 5 d}~X Y nX dS )a´  Add files to a checkpoint.

        :param set save_files: set of filepaths to save
        :param str save_notes: notes about changes during the save
        :param bool temporary: True if the files should be added to a
            temporary checkpoint rather than a permanent one. This is
            usually used for changes that will soon be reverted.

        :raises .errors.PluginError: when unable to add to checkpoint

        N)r	   Zadd_to_temp_checkpointÚadd_to_checkpointr   ÚReverterErrorÚPluginErrorÚstr)r   Z
save_filesZ
save_notesÚ	temporaryZcheckpoint_funcÚerrr   r   r   r:   z   s    
zInstaller.add_to_checkpointc              
   C   sH   z| j  |¡ W n2 tjk
rB } zt t|ƒ¡‚W 5 d}~X Y nX dS )z±Timestamp and save changes made through the reverter.

        :param str title: Title describing checkpoint

        :raises .errors.PluginError: when an error occurs

        N)r	   Úfinalize_checkpointr   r;   r<   r=   )r   Útitler?   r   r   r   r@   �   s    zInstaller.finalize_checkpointc              
   C   sF   z| j  ¡  W n2 tjk
r@ } zt t|ƒ¡‚W 5 d}~X Y nX dS )zÉ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

        N)r	   Úrecovery_routiner   r;   r<   r=   ©r   r?   r   r   r   rB   �   s    zInstaller.recovery_routinec              
   C   sF   z| j  ¡  W n2 tjk
r@ } zt t|ƒ¡‚W 5 d}~X Y nX dS )zkRollback temporary checkpoint.

        :raises .errors.PluginError: when unable to revert config

        N)r	   Úrevert_temporary_configr   r;   r<   r=   rC   r   r   r   rD   ª   s    z!Installer.revert_temporary_configé   c              
   C   sH   z| j  |¡ W n2 tjk
rB } zt t|ƒ¡‚W 5 d}~X Y nX dS )zúRollback saved checkpoints.

        :param int rollback: Number of checkpoints to revert

        :raises .errors.PluginError: If there is a problem with the input or
            the function is unable to correctly revert the configuration

        N)r	   Úrollback_checkpointsr   r;   r<   r=   )r   Úrollbackr?   r   r   r   rF   µ   s    	zInstaller.rollback_checkpointsc                 C   sx   t jdtdd� t  ¡ �V t  ddt¡ z| j ¡  W n2 tjk
rh } zt 	t
|ƒ¡‚W 5 d}~X Y nX W 5 Q R X dS )z¼Show all of the configuration changes that have taken place.

        :raises .errors.PluginError: If there is a problem while processing
            the checkpoints directories.

        z�The view_config_changes method is no longer part of Certbot's plugin interface, has been deprecated, and will be removed in a future release.é   ©Ú
stacklevelÚignorez.*view_config_changesN)ÚwarningsÚwarnÚDeprecationWarningÚcatch_warningsÚfilterwarningsr	   Úview_config_changesr   r;   r<   r=   rC   r   r   r   rQ   Ã   s     ý
zInstaller.view_config_changesc                 C   s   t j | jjtj¡S )z(Full absolute path to ssl_dhparams file.)r
   ÚpathÚjoinr   Ú
config_dirr   ZSSL_DHPARAMS_DESTr'   r   r   r   Ússl_dhparams×   s    zInstaller.ssl_dhparamsc                 C   s   t j | jjtj¡S )z:Full absolute path to digest of updated ssl_dhparams file.)r
   rR   rS   r   rT   r   ZUPDATED_SSL_DHPARAMS_DIGESTr'   r   r   r   Úupdated_ssl_dhparams_digestÜ   s    z%Installer.updated_ssl_dhparams_digestc                 C   s   t | j| jtjtjƒS )zJCopy Certbot's ssl_dhparams file into the system's config dir if required.)Úinstall_version_controlled_filerU   rV   r   ZSSL_DHPARAMS_SRCZALL_SSL_DHPARAMS_HASHESr'   r   r   r   Úinstall_ssl_dhparamsá   s    üzInstaller.install_ssl_dhparams)F)rE   )r.   r/   r0   r1   r   r:   r@   rB   rD   rF   rQ   r5   rU   rV   rX   Ú__classcell__r   r   r8   r   r6   o   s   



r6   c                   @   sv   e Zd ZdZddd„Zedd„ ƒZdd„ Zd	d
„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ ZdS )ÚAddrzˆRepresents an virtual host address.

    :param str addr: addr part of vhost address
    :param str port: port number or \*, or ""

    Fc                 C   s   || _ || _d S r   )ÚtupÚipv6)r   r[   r\   r   r   r   r   ñ   s    zAddr.__init__c                 C   sŠ   |  d¡rh| d¡}|d|d … }d}t|ƒ|d krX||d  dkrX||d d… }| ||fdd	�S | d¡}| |d
 |d fƒS dS )zInitialize Addr from string.ú[ú]NrE   Ú rH   ú:T)r\   r   )Ú
startswithÚrfindÚlenÚ	partition)r   Zstr_addrZendIndexÚhostÚportr[   r   r   r   Ú
fromstringõ   s    

 
zAddr.fromstringc                 C   s   | j d rd| j  S | j d S )NrE   z%s:%sr   ©r[   r'   r   r   r   Ú__str__  s    

zAddr.__str__c                 C   s   | j r|  ¡ | jd fS | jS )z5Normalized representation of addr/port tuple
        rE   )r\   Úget_ipv6_explodedr[   r'   r   r   r   Únormalized_tuple	  s    zAddr.normalized_tuplec                 C   s    t || jƒr|  ¡ | ¡ kS dS )NF)Ú
isinstancer9   rk   )r   Úotherr   r   r   Ú__eq__  s    zAddr.__eq__c                 C   s
   t | jƒS r   )Úhashr[   r'   r   r   r   Ú__hash__  s    zAddr.__hash__c                 C   s
   | j d S )z Return addr part of Addr object.r   rh   r'   r   r   r   Úget_addr  s    zAddr.get_addrc                 C   s
   | j d S )zReturn port.rE   rh   r'   r   r   r   Úget_port  s    zAddr.get_portc                 C   s   |   | jd |f| j¡S )z6Return new address object with same addr and new port.r   )r9   r[   r\   )r   rf   r   r   r   Úget_addr_obj#  s    zAddr.get_addr_objc                 C   s   |  d¡}| d¡}|  |¡S )z7Return IPv6 address in normalized form, helper functionr]   r^   )ÚlstripÚrstripÚ_explode_ipv6)r   Úaddrr   r   r   Ú_normalize_ipv6'  s    

zAddr._normalize_ipv6c                 C   s    | j rd |  | jd ¡¡S dS )zReturn IPv6 in normalized formr`   r   r_   )r\   rS   rx   r[   r'   r   r   r   rj   -  s    zAddr.get_ipv6_explodedc                 C   s    ddddddddg}|  d¡}t|ƒt|ƒkr>|dt|ƒ… }d}t|ƒD ]P\}}|s^d}qJnt|ƒdkrt| d¡}|s†t|ƒ||< qJt|ƒ||t|ƒ < qJ|S )z#Explode IPv6 address for comparisonÚ0r`   r   FTrE   )Úsplitrc   Ú	enumeratert   r=   )r   rw   ÚresultZ	addr_listZappend_to_endÚiÚblockr   r   r   rv   3  s    

zAddr._explode_ipv6N)F)r.   r/   r0   r1   r   r4   rg   ri   rk   rn   rp   rq   rr   rs   rx   rj   rv   r   r   r   r   rZ   ê   s   

rZ   c                   @   s*   e Zd ZdZdd„ Zd	dd„Zdd„ ZdS )
ÚChallengePerformerav  Abstract base for challenge performers.

    :ivar configurator: Authenticator and installer plugin
    :ivar achalls: Annotated challenges
    :vartype achalls: `list` of `.KeyAuthorizationAnnotatedChallenge`
    :ivar indices: Holds the indices of challenges from a larger array
        so the user of the class doesn't have to.
    :vartype indices: `list` of `int`

    c                 C   s   || _ g | _g | _d S r   )ÚconfiguratorÚachallsÚindices©r   r€   r   r   r   r   X  s    zChallengePerformer.__init__Nc                 C   s$   | j  |¡ |dk	r | j |¡ dS )zÝStore challenge to be performed when perform() is called.

        :param .KeyAuthorizationAnnotatedChallenge achall: Annotated
            challenge.
        :param int idx: index to challenge in a larger array

        N)r�   Úappendr‚   )r   ÚachallÚidxr   r   r   Ú	add_chall]  s    zChallengePerformer.add_challc                 C   s
   t ƒ ‚dS )z�Perform all added challenges.

        :returns: challenge responses
        :rtype: `list` of `acme.challenges.KeyAuthorizationChallengeResponse`


        N)ÚNotImplementedErrorr'   r   r   r   Úperformi  s    zChallengePerformer.perform)N)r.   r/   r0   r1   r   r‡   r‰   r   r   r   r   r   L  s   
r   c                       sB   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Zddd„Z‡  Z	S )ÚTLSSNI01z1Abstract base for TLS-SNI-01 challenge performersc                    s(   t t| ƒ |¡ tj |jjd¡| _d S )Nz!le_tls_sni_01_cert_challenge.conf)	r7   rŠ   r   r
   rR   rS   r   rT   Zchallenge_confrƒ   r8   r   r   r   x  s
     ÿzTLSSNI01.__init__c                 C   s    t j | jjj|j d¡d ¡S )zãReturns standardized name for challenge certificate.

        :param .KeyAuthorizationAnnotatedChallenge achall: Annotated
            tls-sni-01 challenge.

        :returns: certificate file name
        :rtype: str

        Útokenz.crt©r
   rR   rS   r€   r   Úwork_dirZchallÚencode©r   r…   r   r   r   Úget_cert_path~  s    
ÿzTLSSNI01.get_cert_pathc                 C   s    t j | jjj|j d¡d ¡S )z'Get standardized path to challenge key.r‹   z.pemrŒ   r�   r   r   r   Úget_key_path‹  s    ÿzTLSSNI01.get_key_pathc                 C   s   |  |j¡j d¡S )z.Returns z_domain (SNI) name for the challenge.zutf-8)ÚresponseZaccount_keyZz_domainÚdecoder�   r   r   r   Úget_z_domain�  s    zTLSSNI01.get_z_domainNc              	   C   s¶   |   |¡}|  |¡}| jj d|¡ | jj d|¡ |j|d�\}\}}tj tjj	|¡}tj 
tjj	|¡}	t|dƒ�}
|
 |¡ W 5 Q R X tj|ddd��}| |	¡ W 5 Q R X |S )z-Generate and write out challenge certificate.T)Úcert_keyÚwbé   )Úchmod)r�   r‘   r€   r	   Zregister_file_creationZresponse_and_validationÚOpenSSLZcryptoZdump_certificateZFILETYPE_PEMZdump_privatekeyÚopenÚwriter   Z	safe_open)r   r…   r•   Z	cert_pathZkey_pathr’   ÚcertÚkeyZcert_pemZkey_pemZcert_chall_fdÚkey_filer   r   r   Ú_setup_challenge_cert”  s(    

ÿ ÿ ÿzTLSSNI01._setup_challenge_cert)N)
r.   r/   r0   r1   r   r�   r‘   r”   rŸ   rY   r   r   r8   r   rŠ   t  s   rŠ   c              	      s´   t  ˆ¡‰‡‡fdd„‰ ‡ ‡‡fdd„}tj ˆ¡s>|ƒ  dS t  ˆ¡}|ˆkrTdS ||krd|ƒ  nLtj ˆ¡rštˆdƒ�}| ¡ }W 5 Q R X |ˆkršdS ˆ ƒ  t dˆˆˆ¡ dS )aƒ  Copy a file into an active location (likely the system's config dir) if required.

       :param str dest_path: destination path for version controlled file
       :param str digest_path: path to save a digest of the file in
       :param str src_path: path to version controlled file found in distribution
       :param list all_hashes: hashes of every released version of the file
    c               	      s$   t ˆdƒ�} |  ˆ ¡ W 5 Q R X d S )NÚw)rš   r›   )Úf)Úcurrent_hashÚdigest_pathr   r   Ú_write_current_hash·  s    z<install_version_controlled_file.<locals>._write_current_hashc                      s   t  ˆˆ¡ ˆ ƒ  d S r   )ÚshutilÚcopyfiler   )r¤   Ú	dest_pathÚsrc_pathr   r   Ú_install_current_file»  s    z>install_version_controlled_file.<locals>._install_current_fileNÚrzh%s has been manually modified; updated file saved to %s. We recommend updating %s for security purposes.)	r   Z	sha256sumr
   rR   Úisfilerš   ÚreadÚloggerÚwarning)r§   r£   r¨   Z
all_hashesr©   Zactive_file_digestr¡   Zsaved_digestr   )r¤   r¢   r§   r£   r¨   r   rW   ­  s,    

  þrW   c                 C   s„   dd„ }|dƒ}|dƒ}|dƒ}t  |tj¡ t  |tj¡ t  |tj¡ t |tj d| ¡¡}t	j
|tj || ¡dd� |||fS )	z5Setup the directories necessary for the configurator.c                 S   s   t  t | ¡¡S )a�  Return the real path of a temp directory with the specified prefix

        Some plugins rely on real paths of symlinks for working correctly. For
        example, certbot-apache uses real paths of configuration files to tell
        a virtual host from another. On systems where TMP itself is a symbolic
        link, (ex: OS X) such plugins will be confused. This function prevents
        such a case.
        )r   ÚrealpathÚtempfileÚmkdtemp)Úprefixr   r   r   Úexpanded_tempdirá  s    	z#dir_setup.<locals>.expanded_tempdirÚtempr   ZworkZtestdataT)Úsymlinks)r   r˜   r   ZCONFIG_DIRS_MODEÚpkg_resourcesÚresource_filenamer
   rR   rS   r¥   Úcopytree)Ztest_dirÚpkgr³   Útemp_dirrT   r�   Ztest_configsr   r   r   Ú	dir_setupß  s"     ÿ  ÿr»   c                   @   s8   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ ZdS )Ú_TLSSNI01DeprecationModulez€
    Internal class delegating to a module, and displaying warnings when
    attributes related to TLS-SNI-01 are accessed.
    c                 C   s   || j d< d S ©NÚ_module)Ú__dict__)r   Úmoduler   r   r   r     s    z#_TLSSNI01DeprecationModule.__init__c                 C   s$   |dkrt jdtdd� t| j|ƒS )NrŠ   z0TLSSNI01 is deprecated and will be removed soon.rH   rI   )rL   rM   rN   r,   r¾   ©r   Úattrr   r   r   Ú__getattr__  s     ÿz&_TLSSNI01DeprecationModule.__getattr__c                 C   s   t | j||ƒ d S r   )Úsetattrr¾   )r   rÂ   Úvaluer   r   r   Ú__setattr__  s    z&_TLSSNI01DeprecationModule.__setattr__c                 C   s   t | j|ƒ d S r   )Údelattrr¾   rÁ   r   r   r   Ú__delattr__  s    z&_TLSSNI01DeprecationModule.__delattr__c                 C   s   dgt | jƒ S r½   )Údirr¾   r'   r   r   r   Ú__dir__  s    z"_TLSSNI01DeprecationModule.__dir__N)	r.   r/   r0   r1   r   rÃ   rÆ   rÈ   rÊ   r   r   r   r   r¼      s   r¼   )2r1   ÚloggingÚrer¥   Úsysr°   rL   r™   r¶   Zzope.interfaceZzopeZjosepyr   r2   Zacme.magic_typingr   Zcertbotr   r   r   r   r   r	   Zcertbot.compatr
   r   Zcertbot.plugins.storager   Ú	getLoggerr.   r­   r   r   ÚcompileZprivate_ips_regexÚ
IGNORECASEZhostname_regexZ	interfaceZimplementerZIPluginÚobjectr   r6   rZ   r   rŠ   rW   r»   r¼   Úmodulesr   r   r   r   Ú<module>   sR   
ÿ ÿ?{b(92!