U
    ]I                     @   s  d 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mZ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G d
d deZdd Zdd Zdd Zdd Zdd ZdZed ed dded eedZdd Zdd  Z dS )!zACME AuthHandler.    N)
challenges)messages)errors)DictListTuple)achallenges)error_handler)
interfacesc                   @   sR   e Zd ZdZdd ZdddZdd	 Zd
d Zdd Zdd Z	dd Z
dd ZdS )AuthHandlera  ACME Authorization Handler for a client.

    :ivar auth: Authenticator capable of solving
        :class:`~acme.challenges.Challenge` types
    :type auth: :class:`certbot.interfaces.IAuthenticator`

    :ivar acme.client.BackwardsCompatibleClientV2 acme_client: ACME client API.

    :ivar account: Client's Account
    :type account: :class:`certbot.account.Account`

    :ivar list pref_challs: sorted user specified preferred challenges
        type strings with the most preferred challenge listed first

    c                 C   s   || _ || _|| _|| _d S N)authacmeaccountpref_challs)selfr   Zacme_clientr   r    r   6/usr/lib/python3/dist-packages/certbot/auth_handler.py__init__&   s    zAuthHandler.__init__F   c                 C   sJ  |j dd }|std| |}|s.|S t| j| zJ| j|}t	
d tjtj}|jrtjtjj}|ddd W n< tjk
r }	 zt	d t	
d |	W 5 d}	~	X Y nX t|t|kstd	t||D ]\}
}| j|
j| q| ||| d
d |D }|s0td|W  5 Q R  S Q R X dS )aT  
        Retrieve all authorizations, perform all challenges required to validate
        these authorizations, then poll and wait for the authorization to be checked.
        :param acme.messages.OrderResource orderr: must have authorizations filled in
        :param bool best_effort: if True, not all authorizations need to be validated (eg. renew)
        :param int max_retries: maximum number of retries to poll authorizations
        :returns: list of all validated authorizations
        :rtype: List

        :raises .AuthorizationError: If unable to retrieve all authorizations
        NzNo authorization to handle.zWaiting for verification...z\Challenges loaded. Press continue to submit to CA. Pass "-v" for more info about challenges.T)pausez!Failure in setting up challenges.z0Attempting to clean up outstanding challenges...z(Some challenges have not been performed.c                 S   s   g | ]}|j jtjkr|qS r   bodystatusr   ZSTATUS_VALID.0authzrr   r   r   
<listcomp>^   s    z5AuthHandler.handle_authorizations.<locals>.<listcomp>zAll challenges have failed.)authorizationsr   AuthorizationError_choose_challengesr	   ZExitHandler_cleanup_challengesr   Zperformloggerinfozope	component
getUtilityr
   ZIConfigZdebug_challengesZIDisplayZnotificationcriticallenAssertionErrorzipr   Zanswer_challengechallb_poll_authorizations)r   orderrbest_effortmax_retriesauthzrsachallsZrespsZconfigZnotifyerrorachallrespZauthzrs_validatedr   r   r   handle_authorizations-   s8    






z!AuthHandler.handle_authorizationsc                 C   s   dd |j D }g }g }|D ]^}z| j|}|| W q tjk
rx } z|| td|j| W 5 d}~X Y qX q||fS )a~  
        Deactivate all `valid` authorizations in the order, so that they cannot be re-used
        in subsequent orders.
        :param messages.OrderResource orderr: must have authorizations filled in
        :returns: tuple of list of successfully deactivated authorizations, and
                  list of unsuccessfully deactivated authorizations.
        :rtype: tuple
        c                 S   s   g | ]}|j jtjkr|qS r   r   r   r   r   r   r   o   s    z?AuthHandler.deactivate_valid_authorizations.<locals>.<listcomp>z)Failed to deactivate authorization %s: %sN)	r   r   Zdeactivate_authorizationappendacme_errorsErrorr"   debugZuri)r   r-   Zto_deactivateZdeactivatedZfailedr   er   r   r   deactivate_valid_authorizationse   s    

$z+AuthHandler.deactivate_valid_authorizationsc                    s$  dd t |D }g }d}t|D ]}|dkr8t|  fdd| D }| D ]\}\}	}|	||< qVdd | D }
|
D ]}td|jj	j
 q||
 d	d | D }|s qt fd
d| D }|tj   }q"|rt| jj |std|r tddS )a  
        Poll the ACME CA server, to wait for confirmation that authorizations have their challenges
        all verified. The poll may occur several times, until all authorizations are checked
        (valid or invalid), or after a maximum of retries.
        c                 S   s   i | ]\}}||d fqS r   r   )r   indexr   r   r   r   
<dictcomp>   s    z4AuthHandler._poll_authorizations.<locals>.<dictcomp>   r   c                    s"   i | ]\}\}}| j |qS r   )r   Zpoll)r   r<   r   _r   r   r   r=      s    
  c                 S   s"   g | ]\}}|j jtjkr|qS r   )r   r   r   ZSTATUS_INVALID)r   r   r?   r   r   r   r      s    z4AuthHandler._poll_authorizations.<locals>.<listcomp>zChallenge failed for domain %sc                 S   s,   i | ]$\}\}}|j jtjkr|||fqS r   )r   r   r   ZSTATUS_PENDING)r   r<   r   r4   r   r   r   r=      s    
 c                 3   s    | ]\}} j |d V  qdS )   N)r   retry_after)r   r?   r4   r@   r   r   	<genexpr>   s   z3AuthHandler._poll_authorizations.<locals>.<genexpr>zSome challenges have failed.z0All authorizations were not finalized by the CA.N)	enumeraterangetimesleepitemsvaluesr"   Zwarningr   
identifiervalueextendmaxdatetimeZnowZtotal_seconds_report_failed_authzrsr   keyr   r   )r   r0   r/   r.   Zauthzrs_to_checkZauthzrs_failed_to_reportZsleep_secondsr?   r<   r   Zauthzrs_failedZauthzr_failedrB   r   r@   r   r,   ~   sD    




z AuthHandler._poll_authorizationsc                 C   s   dd |D }g }|r t d |D ]f}|jj}| jjdkrF|jj}ntdd tt	|D }t
|| |jjj|}|| || q$|S )z
        Retrieve necessary and pending challenges to satisfy server.
        NB: Necessary and already validated challenges are not retrieved,
        as they can be reused for a certificate issuance.
        c                 S   s   g | ]}|j jtjkr|qS r   r   r   r   r   r   r      s    z2AuthHandler._choose_challenges.<locals>.<listcomp>z$Performing the following challenges:r>   c                 s   s   | ]}|fV  qd S r   r   )r   ir   r   r   rC      s     z1AuthHandler._choose_challenges.<locals>.<genexpr>)r"   r#   r   r   r   Zacme_versioncombinationstuplerE   r(   gen_challenge_path_get_chall_prefrJ   rK   rL   _challenge_factory)r   r0   Zpending_authzrsr1   r   Zauthzr_challengesrR   pathr   r   r   r       s     

zAuthHandler._choose_challengesc                 C   sn   g }| j |}| jr`tdd |D }| jD ]}||kr.|tjj|  q.|rV|S t	d|
| |S )z{Return list of challenge preferences.

        :param str domain: domain for which you are requesting preferences

        c                 s   s   | ]}|j V  qd S r   )typ)r   challr   r   r   rC      s     z.AuthHandler._get_chall_pref.<locals>.<genexpr>zENone of the preferred challenges are supported by the selected plugin)r   Zget_chall_prefr   setr6   r   Z	ChallengeZTYPESr   r   rL   )r   domainZchall_prefsZplugin_prefZplugin_pref_typesrX   r   r   r   rU      s    

zAuthHandler._get_chall_prefc                 C   s   t d | j| dS )zCleanup challenges.

        :param achalls: annotated challenges to cleanup
        :type achalls: `list` of :class:`certbot.achallenges.AnnotatedChallenge`

        zCleaning up challengesN)r"   r#   r   Zcleanup)r   r1   r   r   r   r!      s    
zAuthHandler._cleanup_challengesc                 C   s:   g }|D ],}|j j| }|t|| jj|j jj q|S )ai  Construct Namedtuple Challenges

        :param messages.AuthorizationResource authzr: authorization

        :param list path: List of indices from `challenges`.

        :returns: achalls, list of challenge type
            :class:`certbot.achallenges.Indexed`
        :rtype: list

        :raises .errors.Error: if challenge type is not recognized

        )r   r   r6   challb_to_achallr   rP   rJ   rK   )r   r   rW   r1   r<   r+   r   r   r   rV      s      zAuthHandler._challenge_factoryN)Fr   )__name__
__module____qualname____doc__r   r5   r;   r,   r    rU   r!   rV   r   r   r   r   r      s   
8<
r   c                 C   sb   | j }td|j| t|tjr2tj| ||dS t|tj	rLtj	| |dS t
d|jdS )a:  Converts a ChallengeBody object to an AnnotatedChallenge.

    :param .ChallengeBody challb: ChallengeBody
    :param .JWK account_key: Authorized Account Key
    :param str domain: Domain of the challb

    :returns: Appropriate AnnotatedChallenge
    :rtype: :class:`certbot.achallenges.AnnotatedChallenge`

    z%s challenge for %s)r+   r[   account_key)r+   r[   z+Received unsupported challenge of type: {0}N)rY   r"   r#   rX   
isinstancer   ZKeyAuthorizationChallenger   Z"KeyAuthorizationAnnotatedChallengeZDNSr   r8   format)r+   ra   r[   rY   r   r   r   r\     s      
r\   c                 C   s   |rt | ||S t| |S )a  Generate a plan to get authority over the identity.

    .. todo:: This can be possibly be rewritten to use resolved_combinations.

    :param tuple challbs: A tuple of challenges
        (:class:`acme.messages.Challenge`) from
        :class:`acme.messages.AuthorizationResource` to be
        fulfilled by the client in order to prove possession of the
        identifier.

    :param list preferences: List of challenge preferences for domain
        (:class:`acme.challenges.Challenge` subclasses)

    :param tuple combinations: A collection of sets of challenges from
        :class:`acme.messages.Challenge`, each of which would
        be sufficient to prove possession of the identifier.

    :returns: tuple of indices from ``challenges``.
    :rtype: tuple

    :raises certbot.errors.AuthorizationError: If a
        path cannot be created that satisfies the CA given the preferences and
        combinations.

    )_find_smart_path_find_dumb_path)challbspreferencesrR   r   r   r   rT   %  s    rT   c                 C   s   i }d}t |D ]\}}|||< ||7 }qd}|}d}	|D ]:}
|
D ]}|	|| | jj|7 }	qB|	|k rp|
}|	}d}	q:|st|  |S )zFind challenge path with server hints.

    Can be called if combinations is included. Function uses a simple
    ranking system to choose the combo with the lowest cost.

    r>   Nr   )rD   getrY   	__class___report_no_chall_path)rf   rg   rR   Z
chall_costZmax_costrQ   Z	chall_clsZ
best_comboZbest_combo_costZcombo_totalZcomboZchallenge_indexr   r   r   rd   D  s,    
rd   c                    sJ   g }t | D ]8\} t fdd|D d}|r<|| qt|  q|S )zFind challenge path without server hints.

    Should be called if the combinations hint is not included by the
    server. This function either returns a path containing all
    challenges provided by the CA or raises an exception.

    c                 3   s   | ]}t  j|rd V  qdS )TN)rb   rY   )r   Zpref_cr+   r   r   rC   t  s    z"_find_dumb_path.<locals>.<genexpr>F)rD   nextr6   rj   )rf   rg   rW   rQ   Z	supportedr   rk   r   re   i  s    
re   c                 C   sB   d}t | dkr*t| d jtjr*|d7 }t| t|dS )zLogs and raises an error that no satisfiable chall path exists.

    :param challbs: challenges from the authorization that can't be satisfied

    zyClient with the currently selected authenticator does not support any combination of challenges that will satisfy the CA.r>   r   zM You may need to use an authenticator plugin that can do challenges over DNS.N)	r(   rb   rY   r   ZDNS01r"   r'   r   r   )rf   msgr   r   r   rj   ~  s    
rj   zTo fix these errors, please make sure that your domain name was entered correctly and the DNS A/AAAA record(s) for that domain contain(s) the right IP address.a   Additionally, please check that your computer has a publicly routable IP address and that no firewalls are preventing the server from communicating with the client. If you're using the webroot plugin, you should also verify that you are serving files from the webroot path you provided.ze Additionally, if you have DNSSEC enabled for your domain, please ensure that the signature is valid.zTo fix these errors, please make sure that you did not provide any invalid information to the client, and try running Certbot again.zoUnfortunately, an error on the ACME server prevented you from completing authorization. Please try again later.z Additionally, please check that you have an up-to-date TLS configuration that allows the server to communicate with the Certbot client.)Z
connectionZdnssecZ	malformedZserverInternalZtlsZunauthorizedZunknownHostc                    sh   i } fdd| D }|D ]}| |jjg | qtjtj}|	 D ]}|
t||j qLdS )z.Notifies the user about failed authorizations.c                    s2   g | ]*}|j jD ]}|jrt| |j jjqqS r   )r   r   r2   r\   rJ   rK   )r   r   r+   ra   r   r   r     s
    
 z*_report_failed_authzrs.<locals>.<listcomp>N)
setdefaultr2   rX   r6   r$   r%   r&   r
   Z	IReporterrI   Zadd_message_generate_failed_chall_msgZMEDIUM_PRIORITY)Zfailed_authzrsra   Zproblemsfailed_achallsr3   Zreporterr1   r   rn   r   rO     s    
rO   c                 C   st   | d j }|j}t|r |j}dg}| D ]}|d|j||j jf  q*|tkrj|d |t|  d	|S )a  Creates a user friendly error message about failed challenges.

    :param list failed_achalls: A list of failed
        :class:`certbot.achallenges.AnnotatedChallenge` with the same error
        type.

    :returns: A formatted error message for the client.
    :rtype: str

    r   z1The following errors were reported by the server:z"

Domain: %s
Type:   %s
Detail: %sz

 )
r2   rX   r   Zis_acme_errorcoder6   r[   Zdetail_ERROR_HELPjoin)rq   r2   rX   rm   r3   r   r   r   rp     s    

  

rp   )!r`   ZloggingrF   rN   Zzope.componentr$   r   r   r   r   r7   Zacme.magic_typingr   r   r   Zcertbotr   r	   r
   Z	getLoggerr]   r"   objectr   r\   rT   rd   re   rj   Z_ERROR_HELP_COMMONrt   rO   rp   r   r   r   r   <module>   s@   
 x%