U
    ccU                  	   @   s  d dl 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mZ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"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. ddddddgZ/e 0e1Z2ede-dZ3G dd deZ4eeej5ej5dZ6eeej7ej7dZ8dd Z9e
j:ee;d d!dZ<eee' d"d#dZ=eG d$d% d%Z>e'd&d'd(Z?d)d* Z@d2e'e4ee ee ee* eAe,d,d-dZBe
jCd.d/dZDd3e
jCed0d1dZEdS )4    N)	dataclass)Enum)IteratorOptionalTypeVar)cms)pdf)ValidationContext)CertRevTrustPolicyRevocationCheckingPolicyRevocationCheckingRule)PdfFileReader   )
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.
    adobeZpadesz	pades-ltac                 C   s   t dd | D S )Nc                 s   s   | ]}|j V  qd S N)value).0m r/   U/var/www/html/project/venv/lib/python3.8/site-packages/pyhanko/sign/validation/ltv.py	<genexpr>R   s     z8RevocationInfoValidationType.as_tuple.<locals>.<genexpr>)tuple)clsr/   r/   r0   as_tupleP   s    z%RevocationInfoValidationType.as_tupleN)	__name__
__module____qualname____doc__ADOBE_STYLEPADES_LT	PADES_LTAclassmethodr4   r/   r/   r/   r0   r"   8   s   )Zee_certificate_ruleZintermediate_ca_cert_rulec                 C   sr   d|d< | |d< | dd }|d krZ|dd }|rL|dkrLtt|}qf|dkrft}n|jjsft}||d< d S )NFallow_fetchingmomentrevinfo_policyrevocation_modez	soft-fail)getpopr
   r   Zfrom_legacy DEFAULT_LTV_INTERNAL_REVO_POLICYZrevocation_checking_policyZ	essential)	timestampvalidation_context_kwargsr?   Z	legacy_rmr/   r/   r0   _strict_vc_context_kwargsd   s    
rF   )tst_signed_datavalidation_contextexpected_tst_imprintc                    sD   t | ||I dH }tf |}|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.)r   r!   ZvalidZtrustedloggerwarningsummaryr   )rG   rH   rI   Ztimestamp_status_kwargstimestamp_statusr/   r/   r0   r'      s      

)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)Z
sig_objectrA   )sigr/   r/   r0   <lambda>       z%get_timestamp_chain.<locals>.<lambda>)filterreversedZembedded_signatures)rN   r/   r/   r0   r%      s    c                   @   s.   e Zd ZU eed< eed< eed< eed< dS )_TimestampTrustData
latest_dtsearliest_ts_statusts_chain_lengthcurrent_signature_vcN)r5   r6   r7   r   __annotations__r!   intr	   r/   r/   r/   r0   rU      s   
rU   )emb_timestampc                 C   sH   z$| j | j}t|}||W S  tk
rB   tf | Y S X d S r+   )rN   Zget_historical_resolversigned_revisionr   read_dssas_validation_contextr   r	   )r\   rE   Zhist_resolverdssr/   r/   r0   _instantiate_ltv_vc   s    ra   c           	         s   t | }t|}|}d }d}d }t|D ]J\}}|j|k r> qt|  t|j||jI d H }t|j	| t
||}q(t|||d |dS )Nr   )rV   rW   rX   rY   )r%   dict	enumerater]   compute_digestr'   signed_dataexternal_digestrF   rD   ra   rU   )	rN   bootstrap_validation_contextrE   until_revisionZ
timestamps
current_vcZ	ts_statusZts_countr\   r/   r/   r0   _establish_timestamp_trust_lta   s:    
  
   rk   F)embedded_sigvalidation_typerh   diff_policykey_usage_settings	skip_diffrO   c	                    sR  t |pi }|dd |r6t|d< |dk	r^t|d< n(d|kr^|dt |dk	r^|dt | j}	|tjkrd}
|p~tf |}n@t	|	}
|dkr|
j
|dd}n|}|
 D ]}|j| q|   |   d}d}|tjkrFt|	||| jdI dH }|j}|jdkr$|tjkr$td	|tjks@|jd
ks@t|j}| j}|dk	rlt||| jI dH }n |tjkr|jd
krtd|dkrtdt|j| d}|tjkrt| j\}}||d< ||d< tf |}|dk	r^||d< ||d< tf |}nV|tjkr4|

|}|dk	r^|

|}n*|j|_ |}|dk	r^t!|j"|}|j|_ |dk	st|tjkr|dk	r|}n|j"j#}t$|t%|d|jid}|I dH }n|}| j&||d | ' }|(|j|d t)| j#t*| j+|||dI dH }t,| |d dd |dk	r"|j-| j. |(t/| j0| j1|| jd dI dH  t*f |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.
    r=   Tr?   Nr@   F)Zinclude_revinfo)rE   ri   z>Purported PAdES-LTA signature does not have a timestamp chain.r   zlPAdES-LTA signature requires separate timestamps protecting the signature & the rest of the revocation info.z+LTV signatures require a trusted timestamp.ocspscrlsrD   )
status_clsrH   status_kwargs)rn   rp   )Zsigner_reported_dtZtimestamp_validity)rs   Z
raw_digestrH   rt   ro   Zvalidation_path)Ztimestamp_foundsigned_attrs)Zsd_attr_certificatessigner_certrH   Zsd_signed_attrs)2rc   
setdefaultSTRICT_LTV_INTERNAL_REVO_POLICYrC   rN   r"   r9   r	   r   r^   r_   Z
load_certsZcertificate_registryZadd_other_certre   Zcompute_tst_digestrk   r]   rY   rW   r;   r   r:   rX   AssertionErrorZattached_timestamp_datar'   Ztst_signature_digestrF   rD   r$   signer_infor>   ra   rV   rf   r   r!   Zcompute_integrity_infoZsummarise_integrity_infoupdater   r   rg   r   Zregister_multipleZother_embedded_certsr   Zembedded_attr_certsrv   )rl   rm   rE   rh   Zac_validation_context_kwargsZforce_revinforn   ro   rp   rN   r`   rj   certZts_trust_dataZearliest_good_timestamp_strG   Zstored_ac_vcrq   rr   Z	stored_vcZts_to_validateZts_status_cororM   rt   r/   r/   r0   r&      s2   3

 
 
  	
 




 

       

	)rz   c              
   C   sl   zt | d d}W n0 ttfk
rB } ztd|W 5 d}~X Y nX t|d pPd}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.
    ru   Zadobe_revocation_info_archivalz@No revocation info archival attribute found, or multiple presentNZocspr/   Zcrl)r   r   r   r   list)rz   Zrevinfoerq   rr   r/   r/   r0   r$     s     )rz   rO   c                 C   s(   |pi }t | \}}tf ||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.
    )rq   rr   )r$   r	   )rz   rE   rq   rr   r/   r/   r0   r#     s     )NNNFNNF)N)Floggingdataclassesr   enumr   typingr   r   r   Z
asn1cryptor   r   Zasn1_pdfZpyhanko_certvalidatorr	   Zpyhanko_certvalidator.contextr
   r   r   Zpyhanko.pdf_utils.readerr   Zdiff_analysisr   Zgeneralr   r   r   r`   r   errorsr   r   r   Zgeneric_cmsr   r   r   r   Zpdf_embeddedr   r   settingsr   statusr   r    r!   __all__	getLoggerr5   rJ   r(   r"   ZCHECK_IF_DECLAREDrC   ZCRL_OR_OCSP_REQUIREDrx   rF   Z
SignedDatabytesr'   r%   rU   ra   rk   boolr&   Z
SignerInfor$   r#   r/   r/   r/   r0   <module>   s     
),           