o
    CZcr                     @   s  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Zd dl	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 dd	lmZ dd
lmZ ddl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% ej&G dd dej'Z(eddG dd dZ)e)e(j*e(j*e)e(j+e(j+e)e(j,e(j,dZ-ej&G dd dej'Z.eddG dd dZ/eddG dd dZ0G dd dZ1eddG dd dZ2dS )     N)	dataclassfield)datetime	timedelta)OptionalIterableUnionList)crlocspx509)timezone   )pretty_message)	type_name)OCSPFetchError)FetchersFetcherBackenddefault_fetcher_backend)default_permitted_subtreesPKIXSubtreesdefault_excluded_subtrees)ValidationPath)CertificateRegistryc                   @   s   e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dZ		 dZ
	 ed	efd
dZed	efddZed	efddZed	efddZed	efddZed	efddZdS )RevocationCheckingRulezg
    Rules determining in what circumstances revocation data has to be checked,
    and what kind.
    clrcheck	ocspcheck	bothcheckeitherchecknocheckifdeclaredcheckifdeclaredsoftcheckreturnc                 C   s   | t jt jt jfvS N)r   CHECK_IF_DECLAREDCHECK_IF_DECLARED_SOFTNO_CHECKself r)   S/var/www/chikooza/env/lib/python3.10/site-packages/pyhanko_certvalidator/context.pystrictS   s
   zRevocationCheckingRule.strictc                 C      | t jt jfv S r#   )r   r%   r&   r'   r)   r)   r*   tolerant\      zRevocationCheckingRule.tolerantc                 C   r,   r#   )r   CRL_REQUIREDCRL_AND_OCSP_REQUIREDr'   r)   r)   r*   crl_mandatoryc   r.   z$RevocationCheckingRule.crl_mandatoryc                 C      | t jt jfvS r#   )r   r&   OCSP_REQUIREDr'   r)   r)   r*   crl_relevantj   r.   z#RevocationCheckingRule.crl_relevantc                 C   r,   r#   )r   r3   r0   r'   r)   r)   r*   ocsp_mandatoryq   r.   z%RevocationCheckingRule.ocsp_mandatoryc                 C   r2   r#   )r   r&   r/   r'   r)   r)   r*   ocsp_relevantx   r.   z$RevocationCheckingRule.ocsp_relevantN)__name__
__module____qualname____doc__r/   r3   r0   CRL_OR_OCSP_REQUIREDr&   r$   r%   propertyboolr+   r-   r1   r4   r5   r6   r)   r)   r)   r*   r      s8    r   T)frozenc                   @   sJ   e Zd ZU dZeed< 	 eed< 	 edefddZe	de
fdd	Zd
S )RevocationCheckingPolicyzu
    Class describing a revocation checking policy
    based on the types defined in the ETSI TS 119 172 series.
    ee_certificate_ruleintermediate_ca_cert_rulepolicyc                 C   s*   zt | W S  ty   td| dw )N'z ' is not a valid revocation mode)LEGACY_POLICY_MAPKeyError
ValueError)clsrB   r)   r)   r*   from_legacy   s
   
z$RevocationCheckingPolicy.from_legacyr"   c                 C   s   | j jo| j j S r#   )r@   r-   r'   r)   r)   r*   	essential   s   z"RevocationCheckingPolicy.essentialN)r7   r8   r9   r:   r   __annotations__classmethodstrrH   r<   r=   rI   r)   r)   r)   r*   r?      s   
 r?   )	soft-failz	hard-failrequirec                   @   s   e Zd Ze Ze ZdS )FreshnessReqTypeN)r7   r8   r9   enumautoMAX_DIFF_REVOCATION_VALIDATIONTIME_AFTER_SIGNATUREr)   r)   r)   r*   rO      s    rO   c                   @   sN   e Zd ZU dZeed< 	 dZee ed< 	 e	j
Ze	ed< 	 dZee ed< dS )CertRevTrustPolicyzz
    Class describing conditions for trusting revocation info.
    Based on CertificateRevTrust in ETSI TS 119 172-3.
    revocation_checking_policyN	freshnessfreshness_req_type!expected_post_expiry_revinfo_time)r7   r8   r9   r:   r?   rJ   rV   r   r   rO   rR   rW   rX   r)   r)   r)   r*   rT      s   
 
rT   c                   @   sD   e Zd ZU dZeedZeej	 e
d< 	 eedZeej	 e
d< dS )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)r7   r8   r9   r:   r   listr\   r	   r   GeneralNamerJ   r]   r)   r)   r)   r*   rY      s   
 	rY   c                !   @   s  e Zd ZU dZdZdZdZdZdZdZ	dZ
dZdZdZdZeed< dZdddddddddddeddddddfdeeej  deeej  d	eeej  d
eeeeef   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 dedede!dee" def ddZ#e$defddZ%e$dd Z&e$dd Z'e$d d! Z(e$d"d# Z)d$d% Z*d&e+fd'd(Z,d)d* Z-d+d, Z.d-d. Z/d/d0 Z0d1d2 Z1d3d4 Z2d5d6 Z3d7d8 Z4d9d: Z5d;d< Z6e$de"fd=d>Z7dS )?ValidationContextNF	_fetchersrM   r   )secondstrust_rootsextra_trust_rootsother_certswhitelisted_certsmomentallow_fetchingcrlsocspsrevocation_moderevinfo_policyweak_hash_algostime_toleranceretroactive_revinfofetcher_backendacceptable_ac_targetsfetchersc                 C   s  |
du rt t|	}
n|
jdurtd|
jdurtd|
| _|durMg }|D ]!}t|tj	sEt|t
s?ttdt|tj	|}|| q)|}|duryg }|D ]!}t|tjsqt|t
skttdt|tj|}|| qU|}|
jj}|dur|rttdn|s|du r|du r|rttd|du rttj}n| du rttdt | _|dur|D ]"}t|t
r|d	}|d
ddd}| jt |!d	 q|durt|| _"nh d| _"d}|r|dur|| _#n|du rt$ }|%  | _#}|j&}t'||||d| _(|| _)i | _*i | _+i | _,g | _-|r,|| _-g | _.|r@|| _.|D ]}| /| q7t0|| _1g | _2|rOt3|nt4d| _5|| _6|| _7dS )aH  
        :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 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.
        Nz'Freshness has not been implemented yet.zFDealing with post-expiry revocation info has not been implemented yet.z
                            crls must be a list of byte strings or
                            asn1crypto.crl.CertificateList objects, not %s
                            z
                            ocsps must be a list of byte strings or
                            asn1crypto.ocsp.OCSPResponse objects, not %s
                            z_
                    allow_fetching must be False when moment is specified
                    z
                revocation data is not optional and allow_fetching is False,
                however crls and ocsps are both None, meaning that no validation
                can happen
                z
                moment is a naive datetime object, meaning the tzinfo
                attribute is not set to a valid timezone
                ascii  :>   md2md5sha1)cert_fetcherr   )8rT   r?   rH   rV   NotImplementedErrorrX   rl   
isinstancer
   CertificateListbytes	TypeErrorr   r   loadappendr   OCSPResponserU   rI   rF   r   nowr   utc	utcoffsetset_whitelisted_certsdecodereplaceaddbinascii	unhexlifyencoderm   ra   r   get_fetchersrz   r   certificate_registryrg   _validate_map_crl_issuer_map_revocation_certs_crls_ocsps_extract_ocsp_certsr=   _allow_fetching_soft_fail_exceptionsabsr   rn   ro   _acceptable_ac_targets)r(   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   new_crlscrl_	new_ocspsocsp_rev_essentialwhitelisted_certrz   ocsp_responser)   r)   r*   __init__(  s   b









zValidationContext.__init__r"   c                 C      | j S r#   )r   r'   r)   r)   r*   fetching_allowed     z"ValidationContext.fetching_allowedc                 C      | j s| jS t| jj S )zM
        A list of all cached asn1crypto.crl.CertificateList objects
        )r   r   r^   ra   crl_fetcherfetched_crlsr'   r)   r)   r*   ri     s   zValidationContext.crlsc                 C   r   )zK
        A list of all cached asn1crypto.ocsp.OCSPResponse objects
        )r   r   r^   ra   ocsp_fetcherfetched_responsesr'   r)   r)   r*   rj   #  s   zValidationContext.ocspsc                 C   s   t | j S )z
        A list of newly-fetched asn1crypto.x509.Certificate objects that were
        obtained from OCSP responses and CRLs
        )r^   r   valuesr'   r)   r)   r*   new_revocation_certs.  s   z&ValidationContext.new_revocation_certsc                 C   r   )zP
        A list of soft-fail exceptions that were ignored during checks
        )r   r'   r)   r)   r*   soft_fail_exceptions7  s   z&ValidationContext.soft_fail_exceptionsc                 C   s   |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
        )ry   r   r(   certr)   r)   r*   is_whitelisted?  s   z ValidationContext.is_whitelistedec                 C   s   | j | d S r#   )r   r   )r(   r   r)   r)   r*   _report_soft_failL  s   z#ValidationContext._report_soft_failc                    sN   | j s| jS | j}z	|j|}W |S  ty&   |j|I dH }Y |S w )z
        :param cert:
            An asn1crypto.x509.Certificate object

        :return:
            A list of asn1crypto.crl.CertificateList objects
        N)r   r   ra   r   fetched_crls_for_certrE   fetch)r(   r   rr   ri   r)   r)   r*   async_retrieve_crlsO  s   z%ValidationContext.async_retrieve_crlsc                 C   s(   t dt | js| jS t| |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DeprecationWarningr   r   asynciorunr   r   r)   r)   r*   retrieve_crlsa  s   zValidationContext.retrieve_crlsc                    sh   | j s| jS | j}|j|}|s2|j||I dH }z| | W n ty.   tdw |g}|S )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
        Nz9Failed to extract certificates from fetched OCSP response)	r   r   ra   r   fetched_responses_for_certr   r   rF   r   )r(   r   issuerrr   rj   r   r)   r)   r*   async_retrieve_ocspsu  s    z&ValidationContext.async_retrieve_ocspsc                 C   s*   t dt | js| jS t| ||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   r   r   r   r   r   )r(   r   r   r)   r)   r*   retrieve_ocsps  s   z ValidationContext.retrieve_ocspsc                 C   sp   |d j }|dkr0|d }|d j dkr2|d j}|d r4|d D ]}| j|r/|| j|j< q!dS dS dS dS )	z
        Extracts any certificates included with an OCSP response and adds them
        to the certificate registry

        :param ocsp_response:
            An asn1crypto.ocsp.OCSPResponse object to look for certs inside of
        response_status
successfulresponse_bytesresponse_typebasic_ocsp_responseresponsecertsN)nativeparsedr   add_other_certr   issuer_serial)r(   r   statusr   r   
other_certr)   r)   r*   r     s   
	
z%ValidationContext._extract_ocsp_certsc                 C      || j |j< dS )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   pathr)   r)   r*   record_validation     z#ValidationContext.record_validationc                 C   s6   | j |r|j| jvrt|| 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
        )r   is_car   r   r   getr   r)   r)   r*   check_validation  s   z"ValidationContext.check_validationc                 C   s   |j | jv r| j|j = dS dS )z
        Clears the record that a certificate has been validated

        :param cert:
            An ans1crypto.x509.Certificate object
        N)r   r   r   r)   r)   r*   clear_validation  s   z"ValidationContext.clear_validationc                 C   r   )aU  
        Records the certificate that issued a certificate list. Used to reduce
        processing code when dealing with self-issued certificates and multiple
        CRLs.

        :param certificate_list:
            An ans1crypto.crl.CertificateList object

        :param cert:
            An ans1crypto.x509.Certificate object
        N)r   r   )r(   certificate_listr   r)   r)   r*   record_crl_issuer  r   z#ValidationContext.record_crl_issuerc                 C   s   | j |jS )a3  
        Checks to see if the certificate that signed a certificate list has
        been found

        :param certificate_list:
            An ans1crypto.crl.CertificateList object

        :return:
            None if not found, or an asn1crypto.x509.Certificate object of the
            issuer
        )r   r   r   )r(   r   r)   r)   r*   check_crl_issuer  s   z"ValidationContext.check_crl_issuerc                 C   r   r#   )r   r'   r)   r)   r*   rq     r   z'ValidationContext.acceptable_ac_targets)8r7   r8   r9   r   rm   r   r   r   r   r   r   r   r   rg   ra   r   rJ   r   r   r   r   r   Certificater   r~   rL   r   r=   r
   r}   r   r   rT   r   rY   r   r<   r   ri   rj   r   r   r   	Exceptionr   r   r   r   r   r   r   r   r   r   r   rq   r)   r)   r)   r*   r`      s   
 	

 n
	



 r`   c                   @   sr   e Zd ZU edgZeed< 	 dZeed< 	 dZeed< 	 dZ	eed< 	 e
edZeed< 	 e
edZeed	< d
S )PKIXValidationParams
any_policyuser_initial_policy_setFinitial_policy_mapping_inhibitinitial_explicit_policyinitial_any_policy_inhibitrZ   initial_permitted_subtreesinitial_excluded_subtreesN)r7   r8   r9   	frozensetr   rJ   r   r=   r   r   r   r   r   r   r   r   r)   r)   r)   r*   r     s    
 	

r   )3r   rP   r   dataclassesr   r   r   r   r   typingr   r   r   r	   
asn1cryptor
   r   r   asn1crypto.utilr   _errorsr   _typesr   errorsr   rr   r   r   r   
name_treesr   r   r   r   r   registryr   uniqueEnumr   r?   r%   r$   r;   rD   rO   rT   rY   r`   r   r)   r)   r)   r*   <module>   s\    i     $