o
    vh\                     @   sN  d dl 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 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 ddlmZmZ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%m&Z& ddl'm(Z(m)Z) ddl*m+Z+ ddl,m-Z-m.Z.m/Z/ g dZ0e 1e2Z3e	de.dZ4G dd deZ5eej6ej6dZ7dd Z8eej9ej9dZ:dd Z;ded e<fd!d"Z=d#ej>d$ed%e?fd&d'Z@d(ed)ee( fd*d+ZAeG d,d- d-ZBd.e(fd/d0ZCd)eBfd1d2ZD				3			3dAd4e(d5e5d ee< d6ee d7ee d8ee+ d9eEd)e-fd:d;ZFd<ejGfd=d>ZH	dBd<ejGd)efd?d@ZIdS )C    N)	dataclass)datetime)Enum)IteratorOptionalTypeVar)cms)pdf)PdfFileReader)ValidationContext)CertRevTrustPolicyRevocationCheckingPolicyRevocationCheckingRule   )
DiffPolicy)MultivaluedAttributeErrorNonexistentAttributeErrorfind_unique_cms_attribute   )DocumentSecurityStore)NoDSSFoundErrorSignatureValidationErrorValidationInfoReadingError)async_validate_cms_signaturecms_basic_validationcollect_signer_attr_statusvalidate_tst_signed_data)EmbeddedPdfSignaturereport_seed_value_validation)KeyUsageConstraints)PdfSignatureStatusSignatureStatusTimestampSignatureStatus)RevocationInfoValidationTypeapply_adobe_revocation_inforetrieve_adobe_revocation_infoget_timestamp_chain async_validate_pdf_ltv_signatureestablish_timestamp_trust
StatusType)boundc                   @   s.   e Zd ZdZdZ	 dZ	 dZ	 edd ZdS )r#   zP
    Indicates a validation profile to use when validating revocation info.
    adobepadesz	pades-ltac                 C   s   t dd | D S )Nc                 s   s    | ]}|j V  qd S N)value).0m r1   Y/var/www/html/hyperkenya/venv/lib/python3.10/site-packages/pyhanko/sign/validation/ltv.py	<genexpr>U   s    z8RevocationInfoValidationType.as_tuple.<locals>.<genexpr>)tuple)clsr1   r1   r2   as_tupleS   s   z%RevocationInfoValidationType.as_tupleN)	__name__
__module____qualname____doc__ADOBE_STYLEPADES_LT	PADES_LTAclassmethodr6   r1   r1   r1   r2   r#   ;   s    r#   )ee_certificate_ruleintermediate_ca_cert_rulec                  K      t ddti| S Nrevocation_checking_policyr1   )r   &DEFAULT_LTV_INTERNAL_REVO_CHECK_POLICYkwargsr1   r1   r2   !_default_ltv_internal_revo_policy^   
   rG   c                  K   rA   rB   )r   %STRICT_LTV_INTERNAL_REVO_CHECK_POLICYrE   r1   r1   r2    _strict_ltv_internal_revo_policyk   rH   rJ   	timestampvalidation_context_kwargsc                 C   s   d|d< | |d< | dd }| dd}|d u r6|dd }|r,|dkr,tt|}n|dkr5t|d}n	|jjs?t|d}||d< d S )	NFallow_fetchingmomentrevinfo_policyretroactive_revinforevocation_modez	soft-failrP   )	getpopr   r   from_legacyrG   rC   	essentialrJ   )rK   rL   rO   retroactive	legacy_rmr1   r1   r2   _strict_vc_context_kwargsr   s(   rY   tst_signed_datavalidation_contextexpected_tst_imprintc                    sJ   t | ||I dH }tdi |}|jr|js#td|  td|S )a  
    Wrapper around :func:`validate_tst_signed_data` for use when analysing
    timestamps for the purpose of establishing a timestamp chain.
    Its main purpose is throwing/logging an error if validation fails, since
    that amounts to lack of trust in the purported validation time.

    This is internal API.

    :param tst_signed_data:
        The ``SignedData`` value to validate; must encapsulate a ``TSTInfo``
        value.
    :param validation_context:
        The validation context to apply to the timestamp.
    :param expected_tst_imprint:
        The expected message imprint for the ``TSTInfo`` value.
    :return:
        A :class:`.TimestampSignatureStatus` if validation is successful.
    :raises:
        :class:`SignatureValidationError` if validation fails.
    Nz0Could not validate embedded timestamp token: %s.z\Could not establish time of signing, timestamp token did not validate with current settings.r1   )r   r"   validtrustedloggerwarningsummaryr   )rZ   r[   r\   timestamp_status_kwargstimestamp_statusr1   r1   r2   r(      s   
r(   readerreturnc                 C   s   t dd t| jS )a:  
    Get the document timestamp chain of the associated reader, ordered
    from new to old.

    :param reader:
        A :class:`.PdfFileReader`.
    :return:
        An iterable of
        :class:`~pyhanko.sign.validation.pdf_embedded.EmbeddedPdfSignature`
        objects representing document timestamps.
    c                 S   s   | j dd dkS )Nz/Typez/DocTimeStamp)
sig_objectrS   )sigr1   r1   r2   <lambda>   s    z%get_timestamp_chain.<locals>.<lambda>)filterreversedembedded_signatures)rd   r1   r1   r2   r&      s   r&   c                   @   s6   e Zd ZU ee ed< ee ed< eed< eed< dS )_TimestampTrustData
latest_dtsearliest_ts_statusts_chain_lengthcurrent_signature_vc_kwargsN)	r7   r8   r9   r   r   __annotations__r"   intdictr1   r1   r1   r2   rl      s
   
 rl   emb_timestampc                 C   s^   z| j | j}t|}||W S  ty.   |dd |dd tdi | Y S w )Ncrlsr1   ocsps)	rd   get_historical_resolversigned_revisionr   read_dssas_validation_contextr   
setdefaultr   )rt   rL   hist_resolverdssr1   r1   r2   _instantiate_ltv_vc   s   
r~   c           
         s   t | }t|}|}d }d}d }t|D ]$\}}|j|k r  n| }	t|j||	I d H }t|j| t	||}qt
|||d |dS )Nr   )rm   rn   ro   rp   )r&   rs   	enumeraterx   compute_digestr(   signed_datarY   rK   r~   rl   )
rd   bootstrap_validation_contextrL   until_revision
timestamps
current_vc	ts_statusts_countrt   external_digestr1   r1   r2   _establish_timestamp_trust_lta   s4   

r   Fembedded_sigvalidation_typer   diff_policykey_usage_settings	skip_diffc	                    s  t |pi }	|	dd |	dd |	d }
|r,t|
d|	d< |dur+t|
d|d< nd|	vrF|	dt|
d |durF|dt|
d | j}|tjkrZd}|pXtdi |	}nt	|}|du rk|j
|	dd	}n
|}|j|  |   |   d}d}d
}|tjkrt|||	| jdI dH }|j}|j}	|jrt|j|	}|jdu r|tjkrtd|tjks|jdksJ |j}|j}| j}|dur| j}|dusJ t|||I dH }|dusJ |j}||	d< |dur||d< n|tjkr|dkrtd|du rtdt|j|	 d}|tjkrAt| j \}}||	d< ||	d< tdi |	}|dur@||d< ||d< tdi |}n3|tjkr^|dusNJ |
|	}|dur]|
|}n|duseJ t||	}|durtt||}|dus|tjkr|dur|}n
|dusJ |j!}t"|t#|d|jid}|I dH }n|}| j$||d | % }|&|j|d t'(|}t)| j!| j*|||dI dH }t+| |d dd |dur|j| j, |&t-| j.| j/|| j d dI dH  t'di |S )a   
    .. versionadded:: 0.9.0

    Validate a PDF LTV signature according to a particular profile.

    :param embedded_sig:
        Embedded signature to evaluate.
    :param validation_type:
        Validation profile to use.
    :param validation_context_kwargs:
        Keyword args to instantiate
        :class:`.pyhanko_certvalidator.ValidationContext` objects needed over
        the course of the validation.
    :param ac_validation_context_kwargs:
        Keyword arguments for the validation context to use to
        validate attribute certificates.
        If not supplied, no AC validation will be performed.

        .. note::
            :rfc:`5755` requires attribute authority trust roots to be specified
            explicitly; hence why there's no default.
    :param bootstrap_validation_context:
        Validation context used to validate the current timestamp.
    :param force_revinfo:
        Require all certificates encountered to have some form of live
        revocation checking provisions.
    :param diff_policy:
        Policy to evaluate potential incremental updates that were appended
        to the signed revision of the document.
        Defaults to
        :const:`~pyhanko.sign.diff_analysis.DEFAULT_DIFF_POLICY`.
    :param key_usage_settings:
        A :class:`.KeyUsageConstraints` object specifying which key usages
        must or must not be present in the signer's certificate.
    :param skip_diff:
        If ``True``, skip the difference analysis step entirely.
    :return:
        The status of the signature.
    rM   TrP   FrR   rO   NrQ   )include_revinfor   )rL   r   z>Purported PAdES-LTA signature does not have a timestamp chain.r   rN   zlPAdES-LTA signature requires separate timestamps protecting the signature & the rest of the revocation info.z+LTV signatures require a trusted timestamp.rv   ru   rK   )
status_clsr[   status_kwargs)r   r   )signer_reported_dttimestamp_validity)
raw_digestr[   r   r   validation_path)timestamp_foundsigned_attrs)sd_attr_certificatessigner_certr[   sd_signed_attrsr1   )0rs   r{   rG   rJ   rd   r#   r;   r   r   ry   rz   certificate_registryregister_multiple
load_certsr   compute_tst_digestr   rx   ro   rp   rm   r~   rn   r=   r   r<   attached_timestamp_datatst_signature_digestr(   rK   rY   r%   signer_infor   r   r"   compute_integrity_infosummarise_integrity_infoupdater    default_usage_constraintsr   r   r   other_embedded_certsr   embedded_attr_certsr   )r   r   rL   r   ac_validation_context_kwargsforce_revinfor   r   r   	vc_kwargsrW   rd   r}   r   earliest_good_timestamp_strm   ro   ts_trust_datarZ   r   signature_poestored_ac_vcrv   ru   	stored_vcts_to_validatets_status_cororc   r   r1   r1   r2   r'     sH  4






	



	










	r'   r   c              
   C   sb   z	t | d d}W n ttfy } ztd|d}~ww t|d p#d}t|d p+d}||fS )a'  
    Retrieve Adobe-style revocation information from a ``SignerInfo`` value,
    if present.

    Internal API.

    :param signer_info:
        A ``SignerInfo`` value.
    :return:
        A tuple of two (potentially empty) lists, containing OCSP
        responses and CRLs, respectively.
    r   adobe_revocation_info_archivalz@No revocation info archival attribute found, or multiple presentNocspr1   crl)r   r   r   r   list)r   revinfoerv   ru   r1   r1   r2   r%   B  s   r%   c                 C   s(   |pi }t | \}}td||d|S )ag  
    Read Adobe-style revocation information from a CMS object, and load it
    into a validation context.

    :param signer_info:
        Signer info CMS object.
    :param validation_context_kwargs:
        Extra kwargs to pass to the ``__init__`` function.
    :return:
        A validation context preloaded with the relevant revocation information.
    )rv   ru   Nr1   )r%   r   )r   rL   rv   ru   r1   r1   r2   r$   ]  s   r$   )NNNFNNFr-   )Jloggingdataclassesr   r   enumr   typingr   r   r   
asn1cryptor   r	   asn1_pdfpyhanko.pdf_utils.readerr
   pyhanko_certvalidatorr   !pyhanko_certvalidator.policy_declr   r   r   diff_analysisr   generalr   r   r   r}   r   errorsr   r   r   generic_cmsr   r   r   r   pdf_embeddedr   r   settingsr   statusr    r!   r"   __all__	getLoggerr7   r_   r)   r#   CHECK_IF_DECLAREDrD   rG   CRL_OR_OCSP_REQUIREDrI   rJ   rs   rY   
SignedDatabytesr(   r&   rl   r~   r   boolr'   
SignerInfor%   r$   r1   r1   r1   r2   <module>   s    


#
*


0	

  -