a }|gPR@sdZddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z ddl Z dd l mZdd lmZdd lmZdd lmZddlmZddlmZddlmZdd lmZddlmZddlmZddlmZddlmZddl m!Z"e#e$Z%GdddZ&ej'e j(e)ej*dddZ+eej'ee ej,e e-dfdddZ.eej'ej/dd d!Z0eej*e)d"d#d$Z1dS)%zACME AuthHandler.N)Dict)Iterable)List)Optional)Sequence)Tuple)Type)Response) challenges)client)errors)messages) achallenges) configuration) interfaces) error_handler)Account)util)commonc@s*eZdZdZejeejee e e ddddZ d#e jejeeee e jdd d Ze jee e fd d d Ze e jeeeddddZee je ejdddZe e eejdddZ e ejddddZ!e je"ee ejdddZ#e e jddddZ$e ejeje d d!d"Z%dS)$ AuthHandleraACME Authorization Handler for a client. :ivar auth: Authenticator capable of solving :class:`~acme.challenges.Challenge` types :type auth: certbot.interfaces.Authenticator :ivar acme.client.ClientV2 acme_client: ACME client API. :ivar account: Client's Account :type account: :class:`certbot._internal.account.Account` :ivar list pref_challs: sorted user specified preferred challenges type strings with the most preferred challenge listed first N)auth acme_clientaccount pref_challsreturncCs||_||_||_||_dSN)racmerr)selfrrrrrB/usr/lib/python3.9/site-packages/certbot/_internal/auth_handler.py__init__0szAuthHandler.__init__F)orderrconfig best_effort max_retries max_time_minsrc CsL|jdd}|std|js,td||}|s>|St|j|z0|j |}|j r|t j d|||ddWn>tjy} z$tdtd| WYd} ~ n d} ~ 00t||D]\} } |j| j| qtd |||||d d |D} | std | WdS1s40Ytd dS)a 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 certbot.configuration.NamespaceConfig config: current Certbot configuration :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 :param float max_time_mins: maximum time (in minutes) to poll authorizations :returns: list of all validated authorizations :rtype: List :raises .AuthorizationError: If unable to retrieve all authorizations NzNo authorization to handle.z9No ACME client defined, authorizations cannot be handled.z3Challenges loaded. Press continue to submit to CA. T)pausez!Failure in setting up challenges.z0Attempting to clean up outstanding challenges...zWaiting for verification...cSsg|]}|jjtjkr|qSrbodystatusr Z STATUS_VALID.0authzrrrr osz5AuthHandler.handle_authorizations..zAll challenges have failed.z?An unexpected error occurred while handling the authorizations.)authorizationsr AuthorizationErrorrError_choose_challengesrZ ExitHandler_cleanup_challengesrZperformZdebug_challenges display_utilZ notification_debug_challenges_msgloggercriticalinfozipZanswer_challengechallb_poll_authorizations) rr"r#r$r%r&authzrsachallsZrespserrorachallrespZauthzrs_validatedrrrhandle_authorizations8s>          $z!AuthHandler.handle_authorizations)r"rc Cs|jstddd|jD}g}g}|D]`}z|j|}||Wq,tjy}z&||td|j |WYd}~q,d}~00q,||fS)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 z?No ACME client defined, cannot deactivate valid authorizations.cSsg|]}|jjtjkr|qSrr(r+rrrr.sz?AuthHandler.deactivate_valid_authorizations..z)Failed to deactivate authorization %s: %sN) rr r1r/Zdeactivate_authorizationappend acme_errorsr6debuguri)rr"Z to_deactivateZ deactivatedZfailedr-errrdeactivate_valid_authorizationsxs    (z+AuthHandler.deactivate_valid_authorizations)r<r%deadline_minutesr$rcs`jstdddt|D}g}tjtj|d}d}t|D]} |dkr^t |fdd| D}| D]\} \} } | || <q|dd | D} | D]} t d | jjjq|| d d| D}|rtj|krq,tfd d | D}t||}|tj}qH|rL||sLtd|r\tddS)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 a maximum of retries, or the polling deadline is reached. z3No ACME client defined, cannot poll authorizations.cSsi|]\}}||dfqSrr)r,indexr-rrr sz4AuthHandler._poll_authorizations..)Zminutesrcs"i|]\}\}}|j|qSr)rZpoll)r,rIr-_rrrrJcSs"g|]\}}|jjtjkr|qSr)r)r*r ZSTATUS_INVALID)r,r-rLrrrr.s z4AuthHandler._poll_authorizations..zChallenge failed for domain %scSs,i|]$\}\}}|jjtjkr|||fqSr)r)r*r ZSTATUS_PENDING)r,rIr-r@rrrrJsc3s(|] \}}|durj|dVqdS)N)r retry_after)r,rLr@rMrr sz3AuthHandler._poll_authorizations..zSome challenges have failed.z0All authorizations were not finalized by the CA.N)rr r1 enumeratedatetimeZnowZ timedeltarangetimesleepitemsvaluesr6r8r) identifiervalueextendmaxminZ total_seconds_report_failed_authzrsr0)rr<r%rHr$Zauthzrs_to_checkZauthzrs_failed_to_reportZdeadlineZ sleep_secondsrLrIr-Zauthzrs_failedZ authzr_failedrPrrMrr;sN          z AuthHandler._poll_authorizations)r<rcCsn|jstddd|D}g}|r0td|D]4}|jj}t|||jj j }| | ||q4|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. z5No ACME client defined, cannot choose the challenges.cSsg|]}|jjtjkr|qSrr(r+rrrr.sz2AuthHandler._choose_challenges..z$Performing the following challenges:) rr r1r6r8r)r gen_challenge_path_get_chall_prefrYrZr[_challenge_factory)rr<Zpending_authzrsr=r-Zauthzr_challengespathrrrr2s  zAuthHandler._choose_challenges)domainrcCsjg}|j|}|jr\dd|D}|jD]}||vr*|tjj|q*|rR|Std| ||S)z{Return list of challenge preferences. :param str domain: domain for which you are requesting preferences cSsh|] }|jqSr)typ)r,challrrr rNz.AuthHandler._get_chall_pref..zENone of the preferred challenges are supported by the selected plugin) rZget_chall_prefrrBr ChallengeZTYPESr r0r[)rrcZ chall_prefsZ plugin_prefZplugin_pref_typesrdrrrr`s   zAuthHandler._get_chall_pref)r=rcCstd|j|dS)zCleanup challenges. :param achalls: annotated challenges to cleanup :type achalls: `list` of :class:`certbot.achallenges.AnnotatedChallenge` zCleaning up challengesN)r6r8rZcleanup)rr=rrrr3 s zAuthHandler._cleanup_challenges)r-rbrcCsJ|jstdg}|D],}|jj|}|t||jj|jjj q|S)atConstruct Namedtuple Challenges :param messages.AuthorizationResource authzr: authorization :param list path: List of indices from `challenges`. :returns: achalls, list of challenge type :class:`certbot.achallenges.AnnotatedChallenge` :rtype: list :raises .errors.Error: if challenge type is not recognized Account is not set.) rr r1r)r rBchallb_to_achallkeyrYrZ)rr-rbr=rIr:rrrras  zAuthHandler._challenge_factory)failed_authzrsrcsjstdi}fdd|D}|D]}||jjg|q*djjdg}t | dddD]\}}|t |ql|rt jt jr|d j|d td |d S) z.Notifies the user about failed authorizations.rhcs6g|].}|jjD] }|jrt|jj|jjjqqSr)r)r r>rirrjrYrZ)r,r-r:rMrrr.3sz6AuthHandler._report_failed_authzrs..z= Certbot failed to authenticate some domains (authenticator: z5). The Certificate Authority reported these problems:cSs|dS)Nrr)itemrrr>rNz4AuthHandler._report_failed_authzrs..)rjz Hint:  N)rr r1 setdefaultr>rdrBrnamesortedrW_generate_failed_chall_msg isinstance plugin_commonZPluginZ auth_hintr4notifyjoin)rrkZproblemsfailed_achallsr?msgrLr=rrMrr^.s    z"AuthHandler._report_failed_authzrs)r=r#rc Cs|jdkrg}i}i}|D]Z}t|jtjrJ||jd||j|j<t|jtj r||jd|| |j<q|r| d| D]\}}| d|d|q|r| d| D]\} } | d| d| qdd |SdSd S) aEConstruct message for debug challenges prompt :param list achalls: A list of :class:`certbot.achallenges.AnnotatedChallenge`. :param certbot.configuration.NamespaceConfig config: current Certbot configuration :returns: Message containing challenge debug info :rtype: str rrnzZThe following URLs should be accessible from the internet and return the value mentioned: zURL: z Expected value: zRThe following FQDNs should return a TXT resource record with the value mentioned: zFQDN: z)Pass "-v" for more info about challenges.N)Z verbose_countrtrer ZHTTP01Z validation account_keyrErcDNS01Zvalidation_domain_namerBrWrw) rr=r#ryZhttp01_achallsZ dns01_achallsr?rEZ key_authzZfqdnZkey_authz_hashrrrr5Hs*   z!AuthHandler._debug_challenges_msg)Fr!r!)&__name__ __module__ __qualname____doc__rZ Authenticatorrr ZClientV2rrstrr r Z OrderResourcerZNamespaceConfigboolintfloatZAuthorizationResourcerArrGr;rrAnnotatedChallenger2rr rgr`r3rrar^r5rrrrr s8   @  G   r)r:rzrcrcCs^|j}td|j|t|tjr2tj|||dSt|tj rLtj ||dStj ||dSdS)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:rcrz)r:rcN) rer6r8rdrtr ZKeyAuthorizationChallengerZ"KeyAuthorizationAnnotatedChallengeZDNSZOther)r:rzrcrerrrrios   ri.)challbs preferencesrc Csi}d}t|D]\}}|||<||7}qd}|}tddtt|D}d} |D]:} | D]} | ||| jj|7} q\| |kr| }| }d} qT|st||S)aGenerate a plan to get authority over the identity. :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) :returns: list of indices from ``challenges``. :rtype: list :raises certbot.errors.AuthorizationError: If a path cannot be created that satisfies the CA given the preferences and combinations. rKNcss|] }|fVqdSrr)r,irrrrQrNz%gen_challenge_path..r)rRtuplerTlengetre __class___report_no_chall_path) rrZ chall_costZmax_costrZ chall_clsZ best_comboZbest_combo_cost combinationsZ combo_totalZcomboZchallenge_indexrrrr_s. r_)rrcCs>d}t|dkr*t|djtjr*|d7}t|t|S)zLogs and return a raisable error reporting that no satisfiable chall path exists. :param challbs: challenges from the authorization that can't be satisfied :returns: An authorization error :rtype: certbot.errors.AuthorizationError zyClient with the currently selected authenticator does not support any combination of challenges that will satisfy the CA.rKrzM You may need to use an authenticator plugin that can do challenges over DNS.) rrtrer r{r6r7r r0)rryrrrrs  r)rxrcCsR|dj}|j}t|r |j}g}|D]}|d|j||jjfq(d|S)aCreates 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 rz( Domain: %s Type: %s Detail: %s ro) r>rdr Z is_acme_errorcoderBrcZdetailrw)rxr>rdryr?rrrrss   rs)2rrSZloggingrUtypingrrrrrrrZjosepyZrequests.modelsr rr r r rCr ZcertbotrrrZcertbot._internalrZcertbot._internal.accountrZcertbot.displayrr4Zcertbot.pluginsrruZ getLoggerr|r6rZ ChallengeBodyZJWKrrrirgrr_r0rrsrrrrsH                     Q  5