
    (XcU                         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mZ d dlmZ d d	lmZ d d
lmZ d dlmZ  G d dej6                  ej8                        Zy)    N)chan_bindings)sec_contexts)message)named_tuples)names)oids)RequirementFlagIntEnumFlagSet)_utils)Name)Credentialsc                       e Zd ZdZ	 	 	 	 	 	 	 	 	 d/dej
                  ej                     dej
                  e   dej
                  e	j                     dej
                  e   dej
                  e   dej
                  e   d	ej
                  ej                     d
ej
                  ej                      dej
                  e   dd f fdZ	 	 	 	 	 	 	 	 	 d/dej
                  ej                     dej
                  e   dej
                  e	j                     dej
                  e   dej
                  e   dej
                  e   d	ej
                  ej                     d
ej
                  ej                      dej
                  e   ddfdZdedefdZdededefdZdededej0                  fdZdedej4                  fdZdedefdZdedefdZ	 d0dededefdZdeddfdZdefdZ dZ!e"jF                  dedejH                  fd       Z%e&defd        Z'e&dej
                  e   fd!       Z( e"jR                  d"d#      Z* e"jR                  d$d%      Z+ e"jR                  d	d&      Z, e"jR                  dd'      Z- e"jR                  d(d)      Z.e&e"jF                  defd*              Z/e"j`                  	 d1dej
                  e   dej
                  e   fd+       Z1dedej
                  e   fd,Z2	 d1dej
                  e   dej
                  e   fd-Z3dejh                  ejj                  d    ejh                  def   f   fd.Z6 xZ7S )2SecurityContexta  A GSSAPI Security Context

    This class represents a GSSAPI security context that may be used
    with and/or returned by other GSSAPI methods.

    It inherits from the low-level GSSAPI
    :class:`~gssapi.raw.sec_contexts.SecurityContext` class,
    and thus may used with both low-level and high-level API methods.

    This class may be pickled and unpickled (the attached delegated
    credentials object will not be preserved, however).
    Nbasetokennamecredslifetimeflagsmechchannel_bindingsusagereturnc
                     |t        j                  |      }t        j                  dt        t
        |   | |            S )Nr   )rsec_contextsimport_sec_contexttcastsuperr   __new__)clsr   r   r   r   r   r   r   r   r   	__class__s             5/usr/lib/python3/dist-packages/gssapi/sec_contexts.pyr    zSecurityContext.__new__    sB      33E:Dvv'OS9#tDF 	F    c
                 d   d| _         |||	%|	dvrd}
t        j                  |
d      |	| _        n4|!|j                  dk7  r|j                  | _        n|d| _        nd| _        | j                  dk(  r8|t	        d	      || _        || _        t        t        |      | _	        || _
        n||||t	        d
      || _        || _        d| _        d| _        y	 | j                  rd| _        nd| _        d| _        y# t        j                  $ r d}
t        j                  |
d      w xY w)a  
        The constructor creates a new security context, but does not begin
        the initiate or accept process.

        If the `base` argument is used, an existing
        :class:`~gssapi.raw.sec_contexts.SecurityContext` object from
        the low-level API is converted into a high-level object.

        If the `token` argument is passed, the security context is imported
        using the token.

        Otherwise, a new security context is created.

        If the `usage` argument is not passed, the constructor will attempt
        to detect what the appropriate usage is based on either the existing
        security context (if `base` or `token` are used) or the argument set.

        For a security context of the `initiate` usage, the `name` argument
        must be used, and the `creds`, `mech`, `flags`,
        `lifetime`, and `channel_bindings` arguments may be
        used as well.

        For a security context of the `accept` usage, the `creds` and
        `channel_bindings` arguments may optionally be used.
        N)initiateacceptz+Usage must be either 'initiate' or 'accept'zsecurity context)objbothr&   r'   zNYou must pass the 'name' argument when creating an initiating security contextzVYou must pass at most the 'creds' argument when creating an accepting security contextz7Cannot extract usage from a partially completed context)	_last_errexcsUnknownUsageErrorr   	TypeError_target_name_mechr
   r	   _desired_flags_desired_lifetime_channel_bindings_creds_delegated_credslocally_initiatedMissingContextError	_complete)selfr   r   r   r   r   r   r   r   r   msgs              r#   __init__zSecurityContext.__init__3   sn   N  <EM  66GC00:LMM"
"u{{f'<"[[
!'
 &
 zzZ' <# %N O O$(!!
&4_e&L#)1& $(9(H,@# %7 8 8 &6D"DK$(D!$ ,0J))!+DJ!)DJ ,0 ++ J!,,S6HIIJs   D -D/r   c                 .    t        j                  | |      S )a{  Calculate the signature for a message.

        This method calculates the signature (called a MIC) for
        the given message, which may be then used with
        :meth:`verify_signature` to confirm the validity of the
        signature.  This is useful if you wish to transmit the
        message signature and message in your own format.

        Args:
            message (bytes): the input message

        Returns:
            bytes: the message signature

        Raises:
            ~gssapi.exceptions.ExpiredContextError
            ~gssapi.exceptions.MissingContextError
            ~gssapi.exceptions.BadQoPError
        )rmessageget_micr8   r   s     r#   get_signaturezSecurityContext.get_signature   s    2 g..r$   micc                 0    t        j                  | ||      S )a_  Verify the signature for a message.

        This method verifies that a signature (generated by
        :meth:`get_signature` is valid for the given message.

        If the signature is valid, the method will return.
        Otherwise, it will raise an error.

        Args:
            message (bytes): the message
            mic (bytes): the signature to verify

        Returns:
            int: the QoP used.

        Raises:
            ~gssapi.exceptions.BadMICError: the signature was not valid
            ~gssapi.exceptions.InvalidTokenError
            ~gssapi.exceptions.DuplicateTokenError
            ~gssapi.exceptions.ExpiredTokenError
            ~gssapi.exceptions.TokenTooLateError
            ~gssapi.exceptions.TokenTooEarlyError
            ~gssapi.exceptions.ExpiredContextError
            ~gssapi.exceptions.MissingContextError
        )r<   
verify_mic)r8   r   r@   s      r#   verify_signaturez SecurityContext.verify_signature   s    > ""4#66r$   encryptc                 0    t        j                  | ||      S )a5  Wrap a message, optionally with encryption

        This wraps a message, signing it and optionally
        encrypting it.

        Args:
            message (bytes): the message to wrap
            encrypt (bool): whether or not to encrypt the message

        Returns:
            WrapResult: the wrapped message and details about it
            (e.g. whether encryption was used succesfully)

        Raises:
            ~gssapi.exceptions.ExpiredContextError
            ~gssapi.exceptions.MissingContextError
            ~gssapi.exceptions.BadQoPError
        )r<   wrap)r8   r   rD   s      r#   rF   zSecurityContext.wrap   s    0 }}T7G44r$   c                 .    t        j                  | |      S )a  Unwrap a wrapped message.

        This method unwraps/unencrypts a wrapped message,
        verifying the signature along the way.

        Args:
            message (bytes): the message to unwrap/decrypt

        Returns:
            UnwrapResult: the unwrapped message and details about it
            (e.g. wheter encryption was used)

        Raises:
            ~gssapi.exceptions.InvalidTokenError
            ~gssapi.exceptions.BadMICError
            ~gssapi.exceptions.DuplicateTokenError
            ~gssapi.exceptions.ExpiredTokenError
            ~gssapi.exceptions.TokenTooLateError
            ~gssapi.exceptions.TokenTooEarlyError
            ~gssapi.exceptions.ExpiredContextError
            ~gssapi.exceptions.MissingContextError
        )r<   unwrapr>   s     r#   rH   zSecurityContext.unwrap   s    6 tW--r$   c                     | j                  |d      }|j                  st        j                  d      |j                  S )a  Encrypt a message.

        This method wraps and encrypts a message, similarly to
        :meth:`wrap`.  The difference is that encryption is always
        used, and the method will raise an exception if this is
        not possible.  Additionally, this method simply returns
        the encrypted message directly.

        Args:
            message (bytes): the message to encrypt

        Returns:
            bytes: the encrypted message

        Raises:
            ~gssapi.exceptions.EncryptionNotUsed: the encryption could not be
                used
            ~gssapi.exceptions.ExpiredContextError
            ~gssapi.exceptions.MissingContextError
            ~gssapi.exceptions.BadQoPError
        T)rD   z!Wrapped message was not encrypted)rF   	encryptedr+   EncryptionNotUsedr   r8   r   ress      r#   rD   zSecurityContext.encrypt  s9    4 iii.}}(()LMM{{r$   c                     | j                  |      }|j                  s>| j                  t        j                  z  r!t        j                  d|j                        |j                  S )a  Decrypt a message.

        This method decrypts and unwraps a message, verifying the signature
        along the way, similarly to :meth:`unwrap`.  The difference is that
        this method will raise an exception if encryption was established
        by the context and not used, and simply returns the decrypted
        message directly.

        Args:
            message (bytes): the encrypted message

        Returns:
            bytes: the decrypted message

        Raises:
            ~gssapi.exceptions.EncryptionNotUsed: encryption was expected, but
                not used
            ~gssapi.exceptions.InvalidTokenError
            ~gssapi.exceptions.BadMICError
            ~gssapi.exceptions.DuplicateTokenError
            ~gssapi.exceptions.ExpiredTokenError
            ~gssapi.exceptions.TokenTooLateError
            ~gssapi.exceptions.TokenTooEarlyError
            ~gssapi.exceptions.ExpiredContextError
            ~gssapi.exceptions.MissingContextError
        zTThe context was established with encryption, but unwrapped message was not encrypted)unwrapped_message)rH   rJ   actual_flagsr	   confidentialityr+   rK   r   rL   s      r#   decryptzSecurityContext.decrypt1  s\    > kk'"!!O$C$CC(( *= <?;;H H
 {{r$   desired_output_sizerJ   c                 0    t        j                  | ||      S )ag  Calculate the maximum message size for a given wrapped message size.

        This method calculates the maximum input message size for a given
        maximum wrapped/encrypted message size.

        Args:
            desired_output_size (int): the maximum output message size
            encrypted (bool): whether or not encryption should be taken
                into account

        Returns:
            int: the maximum input message size

        Raises:
            ~gssapi.exceptions.MissingContextError
            ~gssapi.exceptions.ExpiredContextError
            ~gssapi.exceptions.BadQoPError
        )r<   wrap_size_limit)r8   rS   rJ   s      r#   get_wrap_size_limitz#SecurityContext.get_wrap_size_limit[  s    0 ''.A(13 	3r$   c                 0    t        j                  | |       y)a  Process an output token asynchronously.

        This method processes an output token even when the security context
        was not expecting it.

        Warning:
            This method is deprecated.

        Args:
            token (bytes): the token to process

        Raises:
            ~gssapi.exceptions.InvalidTokenError
            ~gssapi.exceptions.MissingContextError
        N)r   process_context_tokenr8   r   s     r#   process_tokenzSecurityContext.process_tokenv  s    ( 	++D%8r$   c                 ,    t        j                  |       S )a{  Export a security context.

        This method exports a security context, allowing it to be passed
        between processes.

        Returns:
            bytes: the exported security context

        Raises:
            ~gssapi.exceptions.ExpiredContextError
            ~gssapi.exceptions.MissingContextError
            ~gssapi.exceptions.OperationUnavailableError
        )r   export_sec_contextr8   s    r#   exportzSecurityContext.export  s     //55r$   )initiator_nametarget_namer   r   r   locally_initcompletekwargsc           	         |sd}nd}| j                   D ]  }|j                  ||      ||<    t        j                  | fi |}|j                  dd      r"|j                  t        |j                        }nd}|j                  dd      r"|j                  t        |j                        }nd}t        j                  |||j                  |j                  |j                  |j                  |j                        S )a4  Inspect the security context for information

        This method inspects the security context for information.

        If no keyword arguments are passed, all available information
        is returned.  Otherwise, only the keyword arguments that
        are passed and set to `True` are returned.

        Args:
            initiator_name (bool): get the initiator name for this context
            target_name (bool): get the target name for this context
            lifetime (bool): get the remaining lifetime, in seconds, for this
                context
            mech (bool): get the :class:`MechType` used by this context
            flags (bool): get the flags set on this context
            locally_init (bool): get whether this context was locally initiated
            complete (bool): get whether negotiation on this context has
                been completed

        Returns:
            InquireContextResult: the results of the inquiry, with unused
            fields set to None

        Raises:
            ~gssapi.exceptions.MissingContextError
        TFr_   Nr`   )_INQUIRE_ARGSgetr   inquire_contextr_   r   r`   tuplesInquireContextResultr   r   r   ra   rb   )r8   rc   default_valargrM   	init_namer`   s          r#   _inquirezSecurityContext._inquire  s    > KK%% 	7C **S+6F3K	7 ++D;F;JJ'/"".S//0IIJJ}e,+s/KK**9k+.<<+.99c6F6F+.<<9 	9r$   c                 ,    t        j                  |       S )z7The amount of time for which this context remains valid)r   context_timer]   s    r#   r   zSecurityContext.lifetime  s     ))$//r$   c                     | j                   S )zThe credentials delegated from the initiator to the acceptor

        .. warning::

            This value will not be preserved across picklings.  These should
            be separately exported and transfered.

        )r4   r]   s    r#   delegated_credszSecurityContext.delegated_creds  s     $$$r$   r_   z2The :class:`Name` of the initiator of this contextr`   z/The :class:`Name` of the target of this contextz8The mechanism (:class:`MechType`) in use by this contextzThe flags set on this contextra   z)Whether this context was locally intiatedc                     | j                   r6| j                  }|&	 | j                  d      j                  }|| _        |S |S y# t        j
                  $ r Y yw xY w)z7Whether negotiation for this context has been completedT)rb   F)_startedr7   rm   rb   r+   r6   )r8   rb   s     r#   rb   zSecurityContext.complete  sd     ==~~H.#}}d};DDH &.DNO8O // ! !s   A AAc                 p    | j                   dk(  r| j                  |xs d      S | j                  |      S )a*  Perform a negotation step.

        This method performs a negotiation step based on the usage type
        of this context.  If `__DEFER_STEP_ERRORS__` is set to True on
        the class, this method will return a token, even when exceptions
        would be thrown.  The generated exception will be thrown on the next
        method call or property lookup on the context.
        **This is the default behavior.**

        This method should be used in a while loop, as such:

        .. code-block:: python

           input_token = None
           try:
               while not ctx.complete:
                   output_token = ctx.step(input_token)
                   if not output_token:
                       break
                   input_token = send_and_receive(output_token)
           except GSSError as e:
                handle_the_issue()

        .. tip::

            Disabling `__DEFER_STEP_ERRORS__` is rarely necessary.
            When this method is used in a loop (as above),
            `__DEFER_STEP_ERRORS__` will ensure that you always
            send an error token when it's available,
            keeping the other end of the security context updated
            with the status of the negotiation.

        Args:
            token (bytes): the input token from the other participant's step

        Returns:
            bytes: the output token to send to the other participant

        Raises:
            ~gssapi.exceptions.InvalidTokenError
            ~gssapi.exceptions.InvalidCredentialsError
            ~gssapi.exceptions.MissingCredentialsError
            ~gssapi.exceptions.ExpiredCredentialsError
            ~gssapi.exceptions.BadChannelBindingsError
            ~gssapi.exceptions.BadMICError
            ~gssapi.exceptions.ExpiredTokenError: (initiate only)
            ~gssapi.exceptions.DuplicateTokenError
            ~gssapi.exceptions.MissingContextError
            ~gssapi.exceptions.BadNameTypeError: (initiate only)
            ~gssapi.exceptions.BadNameError: (initiate only)
            ~gssapi.exceptions.BadMechanismError
        r'   r$   )r   )r   _acceptor_step_initiator_steprY   s     r#   stepzSecurityContext.step  s=    t ::!&&U\c&::''e'44r$   c                     t        j                  || j                  | | j                        }|j                  t        |j                        | _        nd | _        |j                   | _        |j                  S N)
r   accept_sec_contextr3   r2   rq   r   r4   
more_stepsr7   r   r8   r   rM   s      r#   ru   zSecurityContext._acceptor_stepJ  si     ..udkk/3T5K5KM *$/0C0C$DD!$(D! ^^+yyr$   c           
          t        j                  | j                  | j                  | | j                  | j
                  | j                  | j                  |      }|j                   | _	        |j                  S ry   )r   init_sec_contextr.   r3   r/   r0   r1   r2   r{   r7   r   r|   s      r#   rv   zSecurityContext._initiator_stepZ  sc     ,,T->->-14::-1-@-@-1-C-C-1-C-C-24 !^^+yyr$   c                 <    t        |       d | j                         ffS ry   )typer^   r]   s    r#   
__reduce__zSecurityContext.__reduce__j  s     T
T4;;=122r$   )	NNNNNNNNN)Try   )8__name__
__module____qualname____doc__r   Optionalr   r   bytesrnamesr   r   introidsOIDrchan_bindingsChannelBindingsstrr    r:   r?   rC   boolrh   
WrapResultrF   UnwrapResultrH   rD   rR   rV   rZ   r^   re   r   check_last_errri   rm   propertyr   rq   inquire_propertyr_   r`   r   rP   r5   rb   catch_and_return_tokenrw   ru   rv   TupleTyper   __classcell__)r"   s   @r#   r   r      s    ;?#'(,)-$(!%&*GK!%Fjj667F zz% F jj%	F
 zz+&F **S/F zz#F jj#F **^%C%CDF zz#F 
F* ;?#'(,)-$(!%&*GK!%c0jj667c0 zz% c0 jj%	c0
 zz+&c0 **S/c0 zz#c0 jj#c0 **^%C%CDc0 zz#c0 
c0T// 
/677 7 
	7B55 5 
			54.. 
		.: 
B(( 
(Z 3 3 3 
	3699 
9,6 6"BM 7979 
	$	$79 79r 0# 0 0 	%K!8 	% 	% -V,,NPN)&))HJK"6""JLD*6**02L///CE $   & "" $(<5zz% <5 
E	<5 #<5| 
E	$ $(zz%  
E	 3	
)*AGGD%K,@@	A3r$   r   )	metaclass)typingr   
gssapi.rawr   r   r   r   r   r<   r   rh   r   r   r   r   gssapi.raw.typesr	   r
   gssapi.exceptions
exceptionsr+   gssapir   gssapi.namesr   gssapi.credsr   r   CheckLastError r$   r#   <module>r      sF     6 4 * - & $ <     $]	3m33 & 5 5]	3r$   