
    M/ePR                     d   d 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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 ddl m!Z"  ejF                  e$      Z% G d d      Z&dejN                  dejP                  de)dejT                  fdZ+deejN                     deeejX                        de
e-df   fd Z.deejN                     dej^                  fd!Z0d"eejT                     de)fd#Z1y)$zACME AuthHandler.    N)Dict)Iterable)List)Optional)Sequence)Tuple)Type)Response)
challenges)client)errors)messages)achallenges)configuration)
interfaces)error_handler)Account)util)commonc                      e Zd ZdZdej
                  deej                     dee	   de
e   ddf
dZ	 	 	 dd	ej                  d
ej                   dededede
ej(                     fdZd	ej                  dee
e
f   fdZde
ej(                     dedededdf
dZdeej(                     de
ej6                     fdZdede
eej>                        fdZ de
ej6                     ddfdZ!dej(                  de"e   de
ej6                     fdZ#de
ej(                     ddfdZ$de
ej6                     d
ej                   defdZ%y)AuthHandlera  ACME 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

    authacme_clientaccountpref_challsreturnNc                 <    || _         || _        || _        || _        y N)r   acmer   r   )selfr   r   r   r   s        @/usr/lib/python3/dist-packages/certbot/_internal/auth_handler.py__init__zAuthHandler.__init__0   s    		&    orderrconfigbest_effortmax_retriesmax_time_minsc                 ,   |j                   dd }|st        j                  d      | j                  st        j                  d      | j                  |      }|s|S t        j                  | j                  |      5  	 | j                  j                  |      }|j                  r*t        j                  d| j                  ||      z   d       t%        |      t%        |      k(  sJ d	       t'        ||      D ]+  \  }
}| j                  j)                  |
j*                  |       - t        j#                  d
       | j-                  ||||       |D cg c]+  }|j.                  j0                  t2        j4                  k(  r|- }}|st        j                  d      |cddd       S # t        j                  $ r1}	t        j!                  d       t        j#                  d       |	d}	~	ww xY wc c}w # 1 sw Y   nxY wt        j                  d      )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
        NzNo 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...z(Some challenges have not been performed.zWaiting for verification...zAll challenges have failed.z?An unexpected error occurred while handling the authorizations.)authorizationsr   AuthorizationErrorr   Error_choose_challengesr   ExitHandler_cleanup_challengesr   performdebug_challengesdisplay_utilnotification_debug_challenges_msgloggercriticalinfolenzipanswer_challengechallb_poll_authorizationsbodystatusr   STATUS_VALID)r    r$   r%   r&   r'   r(   authzrsachallsrespserrorachallrespauthzrauthzrs_validateds                 r!   handle_authorizationsz!AuthHandler.handle_authorizations8   s   " ''*++,IJJyy,,Z[[ ))'2N &&t'?'?I 	%		))'2 ** --N227FCDKOQ u:W-Y/YY- !$GU 3 @		**6==$?@ KK56%%g{M;W 7> !QF$*KK$6$6(:O:O$O "( !Q !Q$//0MNN$?	% 	% ,,  CDNO !Q5	% 	%B ll\]]s>   =G5?AF)BG50G0G5)G-<,G((G--G55G>c                    | j                   st        j                  d      |j                  D cg c]+  }|j                  j
                  t        j                  k(  r|- }}g }g }|D ]/  }	 | j                   j                  |      }|j                  |       1 ||fS c c}w # t        j                  $ r<}|j                  |       t        j                  d|j                  |       Y d}~d}~ww xY w)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.z)Failed to deactivate authorization %s: %sN)r   r   r-   r+   r>   r?   r   r@   deactivate_authorizationappendacme_errorsr6   debuguri)r    r$   rG   to_deactivatedeactivatedfailedes          r!   deactivate_valid_authorizationsz+AuthHandler.deactivate_valid_authorizationsx   s     yy,,`aa.4.C.C IF"KK..(2G2GG   I I# 	YFY;;FC""6*	Y V$$I $$ Yf%H&**VWXXYs   0B,,B##C262C--C2rA   deadline_minutesc           
           j                   st        j                  d      t        |      D ci c]
  \  }}||df c}}}g }t        j                  j                         t	        j                  |      z   }	d}
t        |      D ]  }|
dkD  rt        j                  |
       |j                         D ci c]$  \  }\  }}| j                   j                  |      & }}}}|j                         D ]  \  }\  }}|||<    |j                         D cg c].  \  }}|j                  j                  t        j                   k(  r|0 }}}|D ]6  }t"        j%                  d|j                  j&                  j(                         8 |j+                  |       |j                         D ci c]4  \  }\  }}|j                  j                  t        j,                  k(  r|||f6 }}}}|r!t        j                  j                         |	kD  r n`t/         fd|j                         D              }t1        ||	      }|t        j                  j                         z
  j3                         }
 |r( j5                  |       |st        j6                  d      |rt        j6                  d	      yc c}}w c c}}}w c c}}w c c}}}w )
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.N)minutes   r   zChallenge failed for domain %sc              3   `   K   | ]%  \  }}|j                   j                  |d       ' y w)N   )r   retry_after).0_rF   r    s      r!   	<genexpr>z3AuthHandler._poll_authorizations.<locals>.<genexpr>   s4      3")!T!%!1 #ii33D!< 3s   +.zSome challenges have failed.z0All authorizations were not finalized by the CA.)r   r   r-   	enumeratedatetimenow	timedeltarangetimesleepitemspollvaluesr>   r?   r   STATUS_INVALIDr6   r8   
identifiervalueextendSTATUS_PENDINGmaxmintotal_seconds_report_failed_authzrsr,   )r    rA   r'   rU   r&   indexrG   authzrs_to_checkauthzrs_failed_to_reportdeadlinesleep_secondsr]   authzrs_failedauthzr_failedrF   r[   s   `               r!   r=   z AuthHandler._poll_authorizations   s    yy,,TUU 2;71CBE -v CH&RVBW BE 	 $& $$((*X-?-?HX-YY {# )	TAq 

=) $4#9#9#; =  =BT%&RStyy~~f'= =  =  = '7&<&<&> ("{!'( 7G6M6M6O P!'!3!3x7N7N!N % PN P!/ D<,11<<BBDD
 %++N;
 $4#9#9#; R  R:O%&$#);;#5#59P9P#P !&~ 5  R  R $x'8'8'<'<'>'I  3-=-D-D-F3 3K
 k84K(8+<+<+@+@+BBQQSMS)	TX $''(@A//0NOO++,^__ qBE =P Rs   J4:)J:
3K09K
c                    | j                   st        j                  d      |D cg c]+  }|j                  j                  t
        j                  k7  r|- }}g }|rt        j                  d       |D ]r  }|j                  j                  }t        || j                  |j                  j                  j                              }|j                  | j                  ||             t |S c c}w )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.z$Performing the following challenges:)r   r   r-   r>   r?   r   r@   r6   r8   r   gen_challenge_path_get_chall_prefrj   rk   rl   _challenge_factory)r    rA   rG   pending_authzrsrB   authzr_challengespaths          r!   r.   zAuthHandler._choose_challenges   s     yy,,VWW07 Kf$kk00H4I4II " K K8:KK>?% 	BF & 6 6%!$$V[[%;%;%A%ABDD NN42264@A	B Ks   0C*domainc                 l   g }| j                   j                  |      }| j                  rt|D ch c]  }|j                   }}| j                  D ]3  }||v s|j	                  t
        j                  j                  |          5 |r|S t        j                  d      |j                  |       |S c c}w )z{Return list of challenge preferences.

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

        zENone of the preferred challenges are supported by the selected plugin)r   get_chall_prefr   typrL   r   	ChallengeTYPESr   r,   rl   )r    r   chall_prefsplugin_prefchallplugin_pref_typesr   s          r!   r{   zAuthHandler._get_chall_pref   s     ii..v68C Du D D'' H++&&z';';'A'A#'FGH ""++78 8 	;' !Es   B1rB   c                 d    t         j                  d       | j                  j                  |       y)zCleanup challenges.

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

        zCleaning up challengesN)r6   r8   r   cleanup)r    rB   s     r!   r0   zAuthHandler._cleanup_challenges
  s#     	,-		'"r#   rG   r   c                 (   | j                   st        j                  d      g }|D ]i  }|j                  j                  |   }|j                  t        || j                   j                  |j                  j                  j                               k |S )at  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.AnnotatedChallenge`
        :rtype: list

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

        Account is not set.)
r   r   r-   r>   r   rL   challb_to_achallkeyrj   rk   )r    rG   r   rB   rr   r<   s         r!   r|   zAuthHandler._challenge_factory  s     ||,,455 	IE[[++E2FNN+((&++*@*@*F*FH I	I
 r#   failed_authzrsc           
      Z   | j                   st        j                  d      i }|D cg c]h  }|j                  j                  D ]M  }|j
                  r?t        || j                   j                  |j                  j                  j                        O j }}}|D ]7  }|j                  |j
                  j                  g       j                  |       9 d| j                  j                   dg}t        |j!                         d       D ]  \  }}	|j                  t#        |	             ! |rRt%        | j                  t&        j(                        r.|j                  d| j                  j+                  |       d       t-        j.                  dj1                  |             y	c c}}w )
z.Notifies the user about failed authorizations.r   z=
Certbot failed to authenticate some domains (authenticator: z5). The Certificate Authority reported these problems:c                     | d   S )Nr    )items    r!   <lambda>z4AuthHandler._report_failed_authzrs.<locals>.<lambda>>  s
    DG r#   )r   z
Hint: 
 N)r   r   r-   r>   r   rD   r   r   rj   rk   
setdefaultr   rL   r   namesortedrf   _generate_failed_chall_msg
isinstanceplugin_commonPlugin	auth_hintr3   notifyjoin)
r    r   problemsrG   r<   failed_achallsrE   msgr]   rB   s
             r!   rq   z"AuthHandler._report_failed_authzrs.  sn   ||,,455DF&4)"6;;CYCY)9?!<< +64<<3C3CV[[E[E[EaEab )b ) ) % 	EF 0 0"5<<VD	E""&))..!1 2EE F !!17KL 	<JAwJJ1':;	<
 jM4H4HIJJ$))"5"5n"E!FbIJBGGCL)')s   A-F'c                    |j                   dkD  rlg }i }i }|D ]  }t        |j                  t        j                        rD|j                  |j                        dz   ||j                  j                  |j                        <   t        |j                  t        j                        s|j                  |j                        dz   ||j                  |j                        <    |r@|j                  d       |j                         D ]  \  }}|j                  d| d|         |r@|j                  d       |j                         D ]  \  }	}
|j                  d|	 d|
         ddj                  |      z   S y)	aE  Construct 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

        r   r   zZThe following URLs should be accessible from the internet and return the value mentioned:
zURL: z
Expected value: zRThe following FQDNs should return a TXT resource record with the value mentioned:
zFQDN: z)Pass "-v" for more info about challenges.)verbose_countr   r   r   HTTP01
validationaccount_keyrO   r   DNS01validation_domain_namerL   rf   r   )r    rB   r%   r   http01_achallsdns01_achallsrE   rO   	key_authzfqdnkey_authz_hashs              r!   r5   z!AuthHandler._debug_challenges_msgH  sx    !#CNM! fllJ,=,=>))&*<*<=D #6<<#3#3FMM#BC fllJ,<,<=))&*<*<=D "&"?"?"NO 

 H I&4&:&:&< KNCJJse+=i[IJK

 @ A,9,?,?,A R(D.JJv-??OPQR$))C.((>r#   )F   r   )&__name__
__module____qualname____doc__r   Authenticatorr   r   ClientV2r   r   strr"   r   OrderResourcer   NamespaceConfigboolintfloatAuthorizationResourcerI   r   rT   r=   r   r   AnnotatedChallenger.   r	   r   r   r{   r0   r   r|   rq   r5   r   r#   r!   r   r       s   'Z55 'HV__D] '"7+':>s)'HL' Z_1357>^H,B,B >^&3&C&C>^RV>^+.>^ .3>^ =AA_A_<`>^@%h6L6L %QVW[]aWaQb %6E`D1O1O,P E`_b E`/4E`CGE`LPE`N(83Q3Q*R  $[%C%C D4c d4
8L8L3M.N ,#40N0N+O #TX #)G)G !)#378V8V3W4*T(:X:X5Y *^b *4$?T+2P2P-Q $?&3&C&C$?HK$?r#   r   r<   r   r   r   c                 P   | j                   }t        j                  d|j                  |       t	        |t
        j                        rt        j                  | ||      S t	        |t
        j                        rt        j                  | |      S t        j                  | |      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   r   )r<   r   )r   r6   r8   r   r   r   KeyAuthorizationChallenger   "KeyAuthorizationAnnotatedChallengeDNSOther)r<   r   r   r   s       r!   r   r   o  s     LLE
KK%uyy&9%==>==&kC 	C	E:>>	*fV<<  v>>r#   challbspreferences.c                 @   i }d}t        |      D ]  \  }}|||<   ||z  } d}|}t        d t        t        |             D              }d}	|D ]@  }
|
D ].  }|	|j	                  | |   j
                  j                  |      z  }	0 |	|k  r|
}|	}d}	B |st        |       |S )a  Generate 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.

    rX   Nc              3   "   K   | ]  }|f 	 y wr   r   )r\   is     r!   r^   z%gen_challenge_path.<locals>.<genexpr>  s     ;!!;s   r   )r_   tuplerc   r9   getr   	__class___report_no_chall_path)r   r   
chall_costmax_costr   	chall_cls
best_combobest_combo_costcombinationscombo_totalcombochallenge_indexs               r!   rz   rz     s    * JH!+. 9 !
9A -1JO;uS\':;;LK 	$ 	<O:>>'+!!&yy(< <K	< (J)O	 #G,,r#   c                     d}t        |       dk(  r,t        | d   j                  t        j                        r|dz  }t
        j                  |       t        j                  |      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.rX   r   zM You may need to use an authenticator plugin that can do challenges over DNS.)	r9   r   r   r   r   r6   r7   r   r,   )r   r   s     r!   r   r     s]    EC
7|qZ
(8(8*:J:JK6	7 OOC$$S))r#   r   c           
          | d   j                   }|j                  }t        j                  |      r|j                  }g }| D ];  }|j                  d|j                  d|d|j                   j                  d       = dj                  |      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   z
  Domain: z
  Type:   z
  Detail: r   r   )	rD   r   r   is_acme_errorcoderL   r   detailr   )r   rD   r   r   rE   s        r!   r   r     s~     1##E
))Ce$jj
C  6

MM3 3 35 	66 773<r#   )2r   r`   loggingrd   typingr   r   r   r   r   r   r	   josepyrequests.modelsr
   r   r   r   r   rM   r   certbotr   r   r   certbot._internalr   certbot._internal.accountr   certbot.displayr   r3   certbot.pluginsr   r   	getLoggerr   r6   r   ChallengeBodyJWKr   r   r   r   r   rz   r,   r   r   r   r#   r!   <module>r      s&               $   &   !   + - 0 3			8	$L? L?^
?X33 ?&** ? ?%0%C%C?02X%;%; < 2$(j.B.B)C$D2INsTWx2j*4(>(>#? *FD]D] *&tK4R4R/S X[ r#   