3 گaO@sdZddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z ddlm Z ddl Z dd l m Z dd lmZdd lmZdd lmZdd lmZddlmZddlmZdd lmZddlmZddlmZddlmZddlmZddlm Z!ej"e#Z$GdddZ%ej&e j'e(ej)dddZ*eej&ee ej+e ee,dfee,dddZ-eej&ee ej+e ee,dfee,dddZ.eej&ee ej+ee,d d!d"Z/eej&ej0d#d$d%Z1eej)e(d&d'd(Z2dS))zACME AuthHandler.N)Dict)Iterable)List)Optional)Tuple)Type)Response) challenges)client)errors)messages) achallenges) configuration) interfaces) error_handler)Account)util)commonc@s eZdZdZejeejee e e ddddZ d e jejeee e jdd d Ze jee e fd d d Ze e jeeddddZee je ejdddZe e eejdddZe ejddddZ e je ee ejdddZ!e e jddddZ"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.BackwardsCompatibleClientV2 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||_||_||_||_dS)N)racmerr)selfrrrrr"/usr/lib/python3.6/auth_handler.py__init__/szAuthHandler.__init__F)orderrconfig best_effort max_retriesrc Cs&|jdd}|stjd|js,tjd|j|}|s>|Stj|j|y$|j j |}|j rpt j dddWn<tjk r}ztjdtjd|WYdd}~XnXx&t||D]\} } |jj| j| qWtjd |j|||d d |D} | stjd | SQRXtjd 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 :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.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...zWaiting for verification...cSsg|]}|jjtjkr|qSr)bodystatusr STATUS_VALID).0authzrrrr lsz5AuthHandler.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 notificationloggercriticalinfozipZanswer_challengechallb_poll_authorizations) rr r!r"r#authzrsachallsZrespserrorachallrespZauthzrs_validatedrrrhandle_authorizations7s8          z!AuthHandler.handle_authorizations)r rcCs|jstjddd|jD}g}g}xf|D]^}y|jj|}|j|Wq.tjk r}z |j|tjd|j |WYdd}~Xq.Xq.W||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|qSr)r%r&r r')r(r)rrrr*sz?AuthHandler.deactivate_valid_authorizations..z)Failed to deactivate authorization %s: %sN) rr r-r+Zdeactivate_authorizationappend acme_errorsr1debugZuri)rr Z to_deactivateZ deactivatedZfailedr)errrdeactivate_valid_authorizationsus     &z+AuthHandler.deactivate_valid_authorizations)r7r#r"rc s:jstjdddt|D}g}d}xt|D]}|dkrJtj|fdd|jD}x |jD]\}\} }| ||<qjWdd|jD} x| D]} t j d | j j j qW|j| d d|jD}|sPtfd d |jD} | tjjj}q4W|r&j||s&tjd |r6tjddS)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. z3No ACME client defined, cannot poll authorizations.cSsi|]\}}|df|qS)Nr)r(indexr)rrr sz4AuthHandler._poll_authorizations..rcs"i|]\}\}}jj||qSr)rZpoll)r(rBr)_)rrrrCscSs"g|]\}}|jjtjkr|qSr)r%r&r ZSTATUS_INVALID)r(r)rErrrr*sz4AuthHandler._poll_authorizations..zChallenge failed for domain %scSs,i|]$\}\}}|jjtjkr||f|qSr)r%r&r ZSTATUS_PENDING)r(rBr)r;rrrrCs c3s(|] \}}|dk rjj|dVqdS)N)r retry_after)r(rEr;)rrr sz3AuthHandler._poll_authorizations..zSome challenges have failed.z0All authorizations were not finalized by the CA.N)rr r- enumeraterangetimeZsleepitemsvaluesr1r3r% identifiervalueextendmaxdatetimeZnowZ total_seconds_report_failed_authzrsr,) rr7r#r"Zauthzrs_to_checkZauthzrs_failed_to_reportZ sleep_secondsrErBr)Zauthzrs_failedZ authzr_failedrGr)rrr6s>            z AuthHandler._poll_authorizations)r7rcCs|jstjddd|D}g}|r0tjdxn|D]f}|jj}|jjdkrX|jj}nt ddt t |D}t ||j |jjj|}|j|j||q6W|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|qSr)r%r&r r')r(r)rrrr*sz2AuthHandler._choose_challenges..z$Performing the following challenges:rDcss|] }|fVqdS)Nr)r(irrrrHsz1AuthHandler._choose_challenges..)rr r-r1r3r%r Z acme_version combinationstuplerJlengen_challenge_path_get_chall_prefrNrOrP_challenge_factory)rr7Zpending_authzrsr8r)Zauthzr_challengesrUpathrrrr.s"     zAuthHandler._choose_challenges)domainrcCsrg}|jj|}|jrdtdd|D}x(|jD]}||kr0|jtjj|q0W|rZ|Stj d|j ||S)z{Return list of challenge preferences. :param str domain: domain for which you are requesting preferences css|] }|jVqdS)N)typ)r(challrrrrHsz.AuthHandler._get_chall_pref..zENone of the preferred challenges are supported by the selected plugin) rZget_chall_prefrsetr=r ChallengeZTYPESr r,rP)rr\Z chall_prefsZ plugin_prefZplugin_pref_typesr]rrrrYs   zAuthHandler._get_chall_pref)r8rcCstjd|jj|dS)zCleanup challenges. :param achalls: annotated challenges to cleanup :type achalls: `list` of :class:`certbot.achallenges.AnnotatedChallenge` zCleaning up challengesN)r1r3rZcleanup)rr8rrrr/s zAuthHandler._cleanup_challenges)r)r[rcCsN|jstjdg}x4|D],}|jj|}|jt||jj|jjj qW|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 zAccount is not set.) rr r-r%r r=challb_to_achallkeyrNrO)rr)r[r8rBr5rrrrZs   zAuthHandler._challenge_factory)failed_authzrsrcsjstjdi}fdd|D}x"|D]}|j|jjgj|q,Wdjjdg}x.t |j dddD]\}}|jt |qrW|rt jt jr|jd jj|d tjd j|d S) z.Notifies the user about failed authorizations.zAccount is not set.cs6g|].}|jjD] }|jrt|jj|jjjqqSr)r%r r9rarrbrNrO)r(r)r5)rrrr*1sz6AuthHandler._report_failed_authzrs..z= Certbot failed to authenticate some domains (authenticator: z5). The Certificate Authority reported these problems:cSs|dS)Nrr)itemrrr<sz4AuthHandler._report_failed_authzrs..)rbz Hint:  N)rr r- setdefaultr9r]r=rnamesortedrL_generate_failed_chall_msg isinstance plugin_commonZPluginZ auth_hintr0Znotifyjoin)rrcZproblemsfailed_achallsr:msgrEr8r)rrrS,s   z"AuthHandler._report_failed_authzrs)Fr)#__name__ __module__ __qualname____doc__rZ Authenticatorrr ZClientV2rrstrrr Z OrderResourcerZNamespaceConfigboolintZAuthorizationResourcer<rrAr6rr AnnotatedChallenger.rr r`rYr/rZrSrrrrrs "< B r)r5 account_keyr\rcCsb|j}tjd|j|t|tjr2tj|||dSt|tj rLtj ||dSt j dj |jdS)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)r5r\ry)r5r\z+Received unsupported challenge of type: {0}N) r^r1r3r]rlr ZKeyAuthorizationChallenger Z"KeyAuthorizationAnnotatedChallengeZDNSr r-format)r5ryr\r^rrrraGs    ra.)challbs preferencesrUrcCs|rt|||St||S)aGenerate 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: 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. )_find_smart_path_find_dumb_path)r{r|rUrrrrX_s rXc Csi}d}x$t|D]\}}|||<||7}qWd}|}d} xF|D]>} x$| D]} | |j|| jj|7} qJW| |krz| }| }d} q@W|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. rDNr)rIgetr^ __class___report_no_chall_path) r{r|rUZ chall_costZmax_costrTZ chall_clsZ best_comboZbest_combo_costZ combo_totalZcomboZchallenge_indexrrrr}s&    r})r{r|rcsNg}xDt|D]8\}tfdd|Dd}|r>|j|qt|qW|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. c3s|]}tj|rdVqdS)TN)rlr^)r(Zpref_c)r5rrrHsz"_find_dumb_path..F)rInextr=r)r{r|r[rTZ supportedr)r5rr~s   r~)r{rcCs>d}t|dkr*t|djtjr*|d7}tj|tj|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.rDrzM You may need to use an authenticator plugin that can do challenges over DNS.) rWrlr^r ZDNS01r1r2r r,)r{rprrrrs  r)rorcCsV|dj}|j}tj|r |j}g}x&|D]}|jd|j||jjfq*Wdj|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 rg) r9r]r Z is_acme_errorcoder=r\Zdetailrn)ror9r]rpr:rrrrks   rk)3rtrRZloggingrKZtypingrrrrrrZjosepyZrequests.modelsrrr r r r>r Zcertbotr rrZcertbot._internalrZcertbot._internal.accountrZcertbot.displayrr0Zcertbot.pluginsrrmZ getLoggerrqr1rZ ChallengeBodyZJWKrurxrar`rwrXr}r~r,rrkrrrrsP                    *   %