
    Wwg1b                     F   d dl Z d dlZd dlZd dlmZmZ d dlmZmZ d dlm	Z	m
Z
mZmZmZmZ d dlmZmZmZ d dlmZ ddlmZmZ dd	lmZmZ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&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8  ed       G d d             Z9 G d d      Z: ed       G d d             Z; e       dddddfdeeedf   de
e3   de
e4   de
ejx                     dee   d e
e)   d!e;fd"Z= ed       G d# d$             Z>y)%    N)	dataclassfield)datetime	timedelta)DictIterableListOptionalSetUnion)crlocspx509)timezone   )AuthorityWithCertCertTrustAnchor)FetcherBackendFetchersdefault_fetcher_backend)RequestsFetcherBackend)
POEManager)ValidationTimingInfoValidationTimingParams)ValidationPath)AlgorithmUsagePolicyCertRevTrustPolicyDisallowWeakAlgorithmsPolicyNonRevokedStatusAssertionPKIXValidationParamsRevocationCheckingPolicy)CertificateRegistryPathBuilderSimpleTrustManagerTrustManagerTrustRootList)CRLContainerOCSPContainerprocess_legacy_crl_inputprocess_legacy_ocsp_input)RevinfoManagerT)frozenc                       e Zd ZU dZ ee      Zeej                     e
d<   	  ee      Zeej                     e
d<   y)ACTargetDescriptiona_  
    Value type to guide attribute certificate targeting checks, for
    attribute certificates that use the target information extension.

    As stipulated in RFC 5755, an AC targeting check passes if the
    information in the relevant :class:`.AATargetDescription` matches
    at least one ``Target`` in the AC's target information extension.
    )default_factoryvalidator_namesgroup_membershipsN)__name__
__module____qualname____doc__r   listr0   r	   r   GeneralName__annotations__r1        T/var/www/horilla/myenv/lib/python3.12/site-packages/pyhanko_certvalidator/context.pyr.   r.   )   sJ     /4D.IOT$**+I 16d0KtD,,-Kr:   r.   c            .          e Zd Zdddddddddddd ed      dddddddddfdee   dee   deeej                        d	eee	e
ef         d
ee   dee   dedeee	e
ej                  f         deee	e
ej"                  f         dedee   deee      dededee   dee   dee   dee   dee   dee   dee   dee   f,dZedefd       Zedefd       Zedefd        Zedefd!       Z edefd"       Z!edefd#       Z"edefd$       Z#ede$ej                     fd%       Z%ede$ej"                     fd&       Z&ed'        Z'd( Z(d)e)fd*Z*d+ Z+d, Z,d- Z-d. Z.d/ Z/d0 Z0d1 Z1edee   fd2       Z2y)3ValidationContextNFz	soft-failr   secondstrust_rootsextra_trust_rootsother_certswhitelisted_certsmomentbest_signature_timeallow_fetchingcrlsocspsrevocation_moderevinfo_policyweak_hash_algostime_toleranceretroactive_revinfofetcher_backendacceptable_ac_targetspoe_managerrevinfo_managercertificate_registrytrust_manageralgorithm_usage_policyfetchersc                    |!t        t        j                  |
      |      }n|j                  t	        d      || _        |j                  j                  }|s|s||	|rt        d      |&t        j                  t        j                        }d}n|j                         t        d      d}||}n|j                         t        d      t               | _        ||D ]  }t!        |t"              r|j%                  d	      }|j'                  d
d      j'                  dd      }| j                  j)                  t+        j,                  |j/                  d	                    |!|t1        t3        |            }n
t1               }|| _        d}|r+||
t7               }|j9                         }|j:                  }nd}|t=        j>                  |xs d|      }|| _         |tC        j>                  ||      }t!        |tB              r&|jE                         D ]  }|jG                  |        tI        ||      | _%        |rtM        |      nd}|	rtO        |	      nd}	|tQ        ||xs
 tS               ||	|      }|| _*        i | _+        g | _,        |rt[        |      n
t]        d      }t_        ta        |||      |      | _1        || _2        y)a  
        :param trust_roots:
            If the operating system's trust list should not be used, instead
            pass a list of byte strings containing DER or PEM-encoded X.509
            certificates, or asn1crypto.x509.Certificate objects. These
            certificates will be used as the trust roots for the path being
            built.

        :param extra_trust_roots:
            If the operating system's trust list should be used, but augmented
            with one or more extra certificates. This should be a list of byte
            strings containing DER or PEM-encoded X.509 certificates, or
            asn1crypto.x509.Certificate objects.

        :param other_certs:
            A list of byte strings containing DER or PEM-encoded X.509
            certificates, or a list of asn1crypto.x509.Certificate objects.
            These other certs are usually provided by the service/item being
            validated. In TLS, these would be intermediate chain certs.

        :param whitelisted_certs:
            None or a list of byte strings or unicode strings of the SHA-1
            fingerprint of one or more certificates. The fingerprint is a hex
            encoding of the SHA-1 byte string, optionally separated into pairs
            by spaces or colons. These whilelisted certificates will not be
            checked for validity dates. If one of the certificates is an
            end-entity certificate in a certificate path, any TLS hostname
            mismatches, key usage errors or extended key usage errors will also
            be ignored.

        :param moment:
            If certificate validation should be performed based on a date and
            time other than right now. A datetime.datetime object with a tzinfo
            value. If this parameter is specified, then the only way to check
            OCSP and CRL responses is to pass them via the crls and ocsps
            parameters. Can not be combined with allow_fetching=True.

        :param best_signature_time:
            The presumptive time at which the certificate was used.
            Assumed equal to :class:`moment` if unspecified.

            .. note::
                The difference is significant in some point-in-time validation
                models, where the signature is validated after a
                "cooldown period" of sorts.

        :param crls:
            None or a list/tuple of asn1crypto.crl.CertificateList objects of
            pre-fetched/cached CRLs to be utilized during validation of paths

        :param ocsps:
            None or a list/tuple of asn1crypto.ocsp.OCSPResponse objects of
            pre-fetched/cached OCSP responses to be utilized during validation
            of paths

        :param allow_fetching:
            A bool - if HTTP requests should be made to fetch CRLs and OCSP
            responses. If this is True and certificates contain the location of
            a CRL or OCSP responder, an HTTP request will be made to obtain
            information for revocation checking.

        :param revocation_mode:
            A unicode string of the revocation mode to use: "soft-fail" (the
            default), "hard-fail" or "require". In "soft-fail" mode, any sort of
            error in fetching or locating revocation information is ignored. In
            "hard-fail" mode, if a certificate has a known CRL or OCSP and it
            can not be checked, it is considered a revocation failure. In
            "require" mode, every certificate in the certificate path must have
            a CRL or OCSP.

        :param weak_hash_algos:
            A set of unicode strings of hash algorithms that should be
            considered weak.

        :param time_tolerance:
            Time delta tolerance allowed in validity checks.
            Defaults to one second.

        :param retroactive_revinfo:
            Treat revocation info as retroactively valid, i.e. ignore the
            ``this_update`` field in CRLs and OCSP responses.
            Defaults to ``False``.

            .. warning::
                Be careful with this option, since it will cause incorrect
                behaviour for CAs that make use of certificate holds or other
                reversible revocation methods.
        :param revinfo_manager:
            Internal API, to be elaborated.
        :param trust_manager:
            Internal API, to be elaborated.
        :param certificate_registry:
            Internal API, to be elaborated.
        :param algorithm_usage_policy:
            Internal API, to be elaborated.
        N)rM   zFDealing with post-expiry revocation info has not been implemented yet.zrevocation data is not optional and allow_fetching is False, however crls and ocsps are both None, meaning that no validation can happenFz^moment is a naive datetime object, meaning the tzinfo attribute is not set to a valid timezoneTzkbest_signature_time is a naive datetime object, meaning the tzinfo attribute is not set to a valid timezoneascii  :r9   cert_fetcher)r@   rA   )rS   registry)rR   rP   rG   rH   rU   r   )validation_timerE   point_in_time_validation)rL   )3r   r!   from_legacy!expected_post_expiry_revinfo_timeNotImplementedError_revinfo_policyrevocation_checking_policy	essential
ValueErrorr   nowr   utc	utcoffsetset_whitelisted_certs
isinstancebytesdecodereplaceaddbinascii	unhexlifyencoder   	frozensetalgorithm_policyr   get_fetchersr\   r"   buildrR   r$   
iter_certsregisterr#   path_builderr)   r*   r+   r   _revinfo_manager_validate_map_soft_fail_exceptionsabsr   r   r   timing_params_acceptable_ac_targets)selfr@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rev_essentialr_   whitelisted_certr\   roots                               r;   __init__zValidationContext.__init__F   s0   t !/(44_E$7N ==I%#   .&AAKK#0  >\\(,,/F',$'; 
 (,$&"( **,4; 
 /2e($5 
 .6'7'>'>w'G$ $4#;#;C#D#L#L$  ''++&&'7'>'>w'GH
 ")*)Eo.*& *F)G& 6 #* '>&?O*779#00LH'#6#<#<!r$  :N! .44';LM m%78%002 4$--d34 ('2F
 26'-249)%0r",%9'7:<!O !0:<68"0>^,IaL3  &$7)A
 *
 '<#r:   returnc                     | j                   S N)r{   r   s    r;   rQ   z!ValidationContext.revinfo_managerB  s    $$$r:   c                     | j                   S r   )rc   r   s    r;   rJ   z ValidationContext.revinfo_policyF  s    ###r:   c                 .    | j                   j                  S r   )rc   rM   r   s    r;   rM   z%ValidationContext.retroactive_revinfoJ  s    ##777r:   c                 .    | j                   j                  S r   )r   rL   r   s    r;   rL   z ValidationContext.time_toleranceN  s    !!000r:   c                 .    | j                   j                  S r   )r   r^   r   s    r;   rD   zValidationContext.momentR  s    !!111r:   c                 .    | j                   j                  S r   )r   rE   r   s    r;   rE   z%ValidationContext.best_signature_timeV  s    !!555r:   c                 .    | j                   j                  S r   )rQ   fetching_allowedr   s    r;   r   z"ValidationContext.fetching_allowedZ  s    ##444r:   c                 .    | j                   j                  S )zK
        A list of all cached :class:`crl.CertificateList` objects
        )r{   rG   r   s    r;   rG   zValidationContext.crls^  s    
 $$)))r:   c                 .    | j                   j                  S )zI
        A list of all cached :class:`ocsp.OCSPResponse` objects
        )r{   rH   r   s    r;   rH   zValidationContext.ocspse  s     $$***r:   c                     | j                   S )zP
        A list of soft-fail exceptions that were ignored during checks
        )r}   r   s    r;   soft_fail_exceptionsz&ValidationContext.soft_fail_exceptionsm  s     )))r:   c                 2    |j                   | j                  v S )z
        Checks to see if a certificate has been whitelisted

        :param cert:
            An asn1crypto.x509.Certificate object

        :return:
            A bool - if the certificate is whitelisted
        )sha1rk   r   certs     r;   is_whitelistedz ValidationContext.is_whitelistedu  s     yyD3333r:   ec                 :    | j                   j                  |       y r   )r}   append)r   r   s     r;   _report_soft_failz#ValidationContext._report_soft_fail  s    ""))!,r:   c                    K   | j                   j                  |       d{   }|D cg c]  }|j                   c}S 7 c c}w w)z
        :param cert:
            An asn1crypto.x509.Certificate object

        :return:
            A list of asn1crypto.crl.CertificateList objects
        N)r{   async_retrieve_crlscrl_data)r   r   resultsress       r;   r   z%ValidationContext.async_retrieve_crls  s?      --AA$GG(/000 H0s   AA AAAAc                     t        j                  dt               | j                  j                  s| j                  j
                  S t        j                  | j                  |            S )z
        .. deprecated:: 0.17.0
            Use :meth:`async_retrieve_crls` instead.

        :param cert:
            An asn1crypto.x509.Certificate object

        :return:
            A list of asn1crypto.crl.CertificateList objects
        z@'retrieve_crls' is deprecated, use 'async_retrieve_crls' instead)	warningswarnDeprecationWarningrQ   r   rG   asynciorunr   r   s     r;   retrieve_crlszValidationContext.retrieve_crls  sS     	N	
 ##44'',,,{{433D9::r:   c                    K   | j                   j                  |t        |             d{   }|D cg c]  }|j                   c}S 7 c c}w w)z
        :param cert:
            An asn1crypto.x509.Certificate object

        :param issuer:
            An asn1crypto.x509.Certificate object of cert's issuer

        :return:
            A list of asn1crypto.ocsp.OCSPResponse objects
        N)r{   async_retrieve_ocspsr   ocsp_response_data)r   r   issuerr   r   s        r;   r   z&ValidationContext.async_retrieve_ocsps  sQ      --BB#F+
 
 3::3&&::
 ;s    )AA
AAAAc                     t        j                  dt               | j                  j                  s| j                  j
                  S t        j                  | j                  ||            S )aN  
        .. deprecated:: 0.17.0
            Use :meth:`async_retrieve_ocsps` instead.

        :param cert:
            An asn1crypto.x509.Certificate object

        :param issuer:
            An asn1crypto.x509.Certificate object of cert's issuer

        :return:
            A list of asn1crypto.ocsp.OCSPResponse objects
        zB'retrieve_ocsps' is deprecated, use 'async_retrieve_ocsps' instead)	r   r   r   rQ   r   rH   r   r   r   )r   r   r   s      r;   retrieve_ocspsz ValidationContext.retrieve_ocsps  sW     	-	
 ##44''---{{444T6BCCr:   c                 6    || j                   |j                  <   y)a  
        Records that a certificate has been validated, along with the path that
        was used for validation. This helps reduce duplicate work when
        validating a ceritifcate and related resources such as CRLs and OCSPs.

        :param cert:
            An ans1crypto.x509.Certificate object

        :param path:
            A pyhanko_certvalidator.path.ValidationPath object
        N)r|   	signature)r   r   paths      r;   record_validationz#ValidationContext.record_validation  s     .24>>*r:   c                 "   | j                   j                  j                  |      rF|j                  | j                  vr.t        t        |      g d      | j                  |j                  <   | j                  j                  |j                        S )a]  
        Checks to see if a certificate has been validated, and if so, returns
        the ValidationPath used to validate it.

        :param cert:
            An asn1crypto.x509.Certificate object

        :return:
            None if not validated, or a pyhanko_certvalidator.path.ValidationPath
            object of the validation path
        N)trust_anchorintermleaf)rz   rS   is_rootr   r|   r   r   getr   s     r;   check_validationz"ValidationContext.check_validation  sr     ++33D9d&8&881?,T22D2Dt~~. !!%%dnn55r:   c                 d    |j                   | j                  v r| j                  |j                   = yy)z
        Clears the record that a certificate has been validated

        :param cert:
            An ans1crypto.x509.Certificate object
        N)r   r|   r   s     r;   clear_validationz"ValidationContext.clear_validation  s-     >>T///""4>>2 0r:   c                     | j                   S r   )r   r   s    r;   rO   z'ValidationContext.acceptable_ac_targets  s    ***r:   )3r2   r3   r4   r   r
   r&   r   r   Certificater   rm   strr   boolr   CertificateListr   OCSPResponser   r   r.   r   r+   r"   r%   r   r   r   propertyrQ   rJ   rM   rL   rD   rE   r   r	   rG   rH   r   r   	Exceptionr   r   r   r   r   r   r   r   rO   r9   r:   r;   r=   r=   E   s[    0459<@CG%)26$FJEI*7;37$-a$8$)48?C,048>B04AE'+/z<m,z< $M2z< ht'7'789	z<
 $HU5#:->$?@z< "z< &h/z< z< xeS-@-@&@ ABCz< ud.?.?'?!@ABz< z< !!34z< "(3-0z< "z< "z<  ".1!z<"  ((;<#z<$ j)%z<& ".1'z<( '':;)z<*  -+z<, !))= >-z<. 8$/z<x % % % $ 2 $ $ 8T 8 8 1	 1 1 2 2 2 6X 6 6 5$ 5 5 *d3../ * * +tD--. + + * *4-9 -	1;(; D226.	3 +x0C'D + +r:   r=   c                   4    e Zd ZU dZeed<   	 eed<   	 eed<   y)ValidationDataHandlersz
    Value class to hold 'manager'/'registry' objects. These are responsible for
    accumulating and exposing various data collections that are relevant
    for certificate validation.
    rQ   rP   cert_registryN)r2   r3   r4   r5   r+   r8   r   r"   r9   r:   r;   r   r     s.     $#  '&r:   r   r9   rU   rG   rH   certsrP   nonrevoked_assertionsr   c                    t        | t              r| j                         }nt        | t              r| }nd}|xs
 t	               }t        ||j                  nd      }|j                  |       t        ||||||      }t        |||      S )a  
    Simple bootstrapping method for a :class:`.ValidationDataHandlers`
    instance with reasonable defaults.

    :param fetchers:
        Data fetcher implementation and/or backend to use.
        If ``None``, remote fetching is disabled. The ``requests``-based
        implementation is the default.
    :param crls:
        Initial collection of CRLs to feed to the revocation info manager.
    :param ocsps:
        Initial collection of OCSP responses to feed to the revocation info
        manager.
    :param certs:
        Initial collection of certificates to add to the certificate registry.
    :param poe_manager:
        Explicit POE manager. Will instantiate an empty one if left unspecified.
    :param nonrevoked_assertions:
        Assertions about the non-revoked status of certain certificates
        that will be taken as true by fiat.
    :return:
        A :class:`.ValidationDataHandlers` object.
    Nr[   )rR   rP   rG   rH   rU   
assertions)rQ   rP   r   )
rl   r   rv   r   r   r"   r\   register_multipler+   r   )	rU   rG   rH   r   rP   r   	_fetchersr   rQ   s	            r;   "bootstrap_validation_data_handlersr      s    B (N+))+		Hh	'		-K'/8/DY++$M ##E*$*(O "'# r:   c                       e Zd ZU dZeed<   	 eed<   	  ed      Zeed<   	 dZ	e
e   ed<   	  e e       	      Ze
e   ed
<   	 dZe
e   ed<   	 dede
e   defdZy)CertValidationPolicySpeca  
    Policy object describing how to validate certificates at a high
    level.

    .. note::
        A certificate validation policy differs from a validation context
        in that :class:`ValidationContext` objects keep state as well.
        This is not the case for a certificate validation policy, which makes
        them suitable for reuse in complex validation workflows where the
        same policy needs to be applied independently in multiple steps.

    .. warning::
        While a certification policy spec is intended to be stateless,
        some of its fields are abstract classes. As such, the true behaviour
        may depend on the underlying implementation.
    rS   rJ   r   r>   rL   NrO   )defaultrT   pkix_validation_paramstiming_infohandlersr   c                 b   |$t               }t               }t        ||g g       }n$|j                  }|j                  }|j
                  }t        | j                  | j                  |||| j                  |j                  |j                  | j                  | j                  |j                        S )a  
        Build a validation context from this policy, validation timing info
        and a set of validation data handlers.

        :param timing_info:
            Timing settings.
        :param handlers:
            Optionally specify validation data handlers. A reasonable default
            will be supplied if absent.
        :return:
            A new :class:`ValidationContext` reflecting the parameters.
        )rR   rP   rG   rH   )rS   rJ   rQ   rR   rP   rT   rD   rE   rL   rO   rF   )r"   r   r+   r   rP   rQ   r=   rS   rJ   rT   r^   rE   rL   rO   r   )r   r   r   r   rP   rQ   s         r;   build_validation_contextz1CertValidationPolicySpec.build_validation_context  s    $ /1M$,K,%2'	O %22M"..K&66O ,,..+!.##'#>#>.. + ? ?.."&"<"<*;;
 	
r:   )r2   r3   r4   r5   r%   r8   r   r   rL   rO   r
   r.   r   r   rT   r   r   r    r   r   r=   r   r9   r:   r;   r   r   \  s    "   '&
 !*! 4NI4 <@8$78? >C,.>H%9: 
 >BH%9:A,
),
 12,
 
	,
r:   r   )?r   rq   r   dataclassesr   r   r   r   typingr   r   r	   r
   r   r   
asn1cryptor   r   r   asn1crypto.utilr   	authorityr   r   rU   r   r   r   fetchers.requests_fetchersr   ltv.poer   	ltv.typesr   r   r   r   policy_declr   r   r   r   r    r!   r]   r"   r#   r$   r%   r&   revinfo.archivalr'   r(   r)   r*   revinfo.managerr+   r.   r=   r   r   r   r   r9   r:   r;   <module>r      sQ      ( ( = = & & $ 9 G G >  C      , $  6{+ {+| $  : 7M6N#%%'(*(,AC9Hnd239
<
 9 M"9 D$$%	9
 *%9 $$=>9 9x $`
 `
 `
r:   