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}~XnXt|t|kstd x&t||D]\} } |jj| j| qWtjd |j|||d d |D} | s&tjd | SQRXtjddS)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...z(Some challenges have not been performed.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 notificationloggercriticalinfolenAssertionErrorzipZanswer_challengechallb_poll_authorizations) rr r!r"r#authzrsachallsZrespserrorachallrespZauthzrs_validatedrrrhandle_authorizations7s:          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)r9r#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(rDr)_)rrrrEscSs"g|]\}}|jjtjkr|qSr)r%r&r ZSTATUS_INVALID)r(r)rGrrrr*sz4AuthHandler._poll_authorizations..zChallenge failed for domain %scSs,i|]$\}\}}|jjtjkr||f|qSr)r%r&r ZSTATUS_PENDING)r(rDr)r=rrrrEs c3s(|] \}}|dk rjj|dVqdS)N)r retry_after)r(rGr=)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,) rr9r#r"Zauthzrs_to_checkZauthzrs_failed_to_reportZ sleep_secondsrGrDr)Zauthzrs_failedZ authzr_failedrIr)rrr8s>            z AuthHandler._poll_authorizations)r9rcCs|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:rFcss|] }|fVqdS)Nr)r(irrrrJsz1AuthHandler._choose_challenges..)rr r-r1r3r%r Z acme_version combinationstuplerLr4gen_challenge_path_get_chall_prefrPrQrR_challenge_factory)rr9Zpending_authzrsr:r)Zauthzr_challengesrWpathrrrr.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(challrrrrJsz.AuthHandler._get_chall_pref..zENone of the preferred challenges are supported by the selected plugin) rZget_chall_prefrsetr?r ChallengeZTYPESr r,rR)rr]Z chall_prefsZ plugin_prefZplugin_pref_typesr^rrrrZs   zAuthHandler._get_chall_pref)r:rcCstjd|jj|dS)zCleanup challenges. :param achalls: annotated challenges to cleanup :type achalls: `list` of :class:`certbot.achallenges.AnnotatedChallenge` zCleaning up challengesN)r1r3rZcleanup)rr:rrrr/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_achallkeyrPrQ)rr)r\r:rDr7rrrr[s   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 r;rbrrcrPrQ)r(r)r7)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..)rcz Hint:  N)rr r- setdefaultr;r^r?rnamesortedrN_generate_failed_chall_msg isinstance plugin_commonZPluginZ auth_hintr0Znotifyjoin)rrdZproblemsfailed_achallsr<msgrGr:r)rrrU,s   z"AuthHandler._report_failed_authzrs)Fr)#__name__ __module__ __qualname____doc__rZ Authenticatorrr ZClientV2rrstrrr Z OrderResourcerZNamespaceConfigboolintZAuthorizationResourcer>rrCr8rr AnnotatedChallenger.rr rarZr/r[rUrrrrrs "< B r)r7 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)r7r]rz)r7r]z+Received unsupported challenge of type: {0}N) r_r1r3r^rmr ZKeyAuthorizationChallenger Z"KeyAuthorizationAnnotatedChallengeZDNSr r-format)r7rzr]r_rrrrbGs    rb.)challbs preferencesrWrcCs|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}rWrrrrY_s rYc 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. rFNr)rKgetr_ __class___report_no_chall_path) r|r}rWZ chall_costZmax_costrVZ 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)rmr_)r(Zpref_c)r7rrrJsz"_find_dumb_path..F)rKnextr?r)r|r}r\rVZ supportedr)r7rrs   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.rFrzM You may need to use an authenticator plugin that can do challenges over DNS.) r4rmr_r ZDNS01r1r2r r,)r|rqrrrrs  r)rprcCsV|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 rh) r;r^r Z is_acme_errorcoder?r]Zdetailro)rpr;r^rqr<rrrrls   rl)3rurTZloggingrMZtypingrrrrrrZjosepyZrequests.modelsrrr r r r@r Zcertbotr rrZcertbot._internalrZcertbot._internal.accountrZcertbot.displayrr0Zcertbot.pluginsrrnZ getLoggerrrr1rZ ChallengeBodyZJWKrvryrbrarxrYr~rr,rrlrrrrsP                    *   %