
    Wwg\                        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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/ g dZ0 e jb                  e2      Z3 e	de.      Z4 G d de      Z5 eejl                  ejl                        Z7d Z8 eejr                  ejr                        Z:d Z;dede<fdZ=d ej|                  d!ed"e?fd#Z@d$ed%ee(   fd&ZAe G d' d(             ZBd)e(fd*ZCd%eBfd+ZD	 	 	 	 	 	 	 d6d,e(d-e5dee<   d.ee   d/ee   d0ee+   d1eEd%e-fd2ZFd3ej                  fd4ZH	 d7d3ej                  d%efd5ZIy)8    N)	dataclass)datetime)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                   2    e Zd ZdZdZ	 dZ	 dZ	 ed        Zy)r$   zP
    Indicates a validation profile to use when validating revocation info.
    adobepadesz	pades-ltac                 &    t        d | D              S )Nc              3   4   K   | ]  }|j                     y wN)value).0ms     R/var/www/horilla/myenv/lib/python3.12/site-packages/pyhanko/sign/validation/ltv.py	<genexpr>z8RevocationInfoValidationType.as_tuple.<locals>.<genexpr>U   s     *QWW*s   )tuple)clss    r5   as_tuplez%RevocationInfoValidationType.as_tupleS   s    *c***    N)	__name__
__module____qualname____doc__ADOBE_STYLEPADES_LT	PADES_LTAclassmethodr9    r:   r5   r$   r$   ;   s?     K
 H
 I + +r:   r$   )ee_certificate_ruleintermediate_ca_cert_rulec                  $    t        ddt        i| S Nrevocation_checking_policyrC   )r   &DEFAULT_LTV_INTERNAL_REVO_CHECK_POLICYkwargss    r5   !_default_ltv_internal_revo_policyrL   ^   s     #I
 r:   c                  $    t        ddt        i| S rG   )r   %STRICT_LTV_INTERNAL_REVO_CHECK_POLICYrJ   s    r5    _strict_ltv_internal_revo_policyrO   k   s     #H
 r:   	timestampvalidation_context_kwargsc                 F   d|d<   | |d<   |j                  dd       }|j                  dd      }|J|j                  dd       }|r$|dk7  rt        t        j                  |            }n4|dk(  r/t        |      }n"|j                  j                  st        |      }||d<   y )	NFallow_fetchingmomentrevinfo_policyretroactive_revinforevocation_modez	soft-failrV   )	getpopr   r   from_legacyrL   rH   	essentialrO   )rP   rQ   rU   retroactive	legacy_rms        r5   _strict_vc_context_kwargsr_   r   s     38./*3h'
 *C)F)F$*N ,//0EuMK-112CTJ	k1/(44Y?N +%>$/N 66@@9 +
 3A./r:   tst_signed_datavalidation_contextexpected_tst_imprintc                    K   t        | ||       d{   }t        di |}|j                  r|j                  s/t        j                  d|j                                t        d      |S 7 Xw)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.rC   )r   r#   validtrustedloggerwarningsummaryr   )r`   ra   rb   timestamp_status_kwargstimestamp_statuss        r5   r)   r)      s     2 %=+-A%  0J2IJ!!)9)A)A>$$&	
 '.
 	
 s   A.A,AA.readerreturnc                 B    t        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                 @    | j                   j                  dd       dk(  S )Nz/Typez/DocTimeStamp)
sig_objectrY   )sigs    r5   <lambda>z%get_timestamp_chain.<locals>.<lambda>   s    CNN&&w5H r:   )filterreversedembedded_signatures)rk   s    r5   r'   r'      s"     H++, r:   c                   <    e Zd ZU eed<   ee   ed<   eed<   eed<   y)_TimestampTrustData
latest_dtsearliest_ts_statusts_chain_lengthcurrent_signature_vc_kwargsN)	r;   r<   r=   r   __annotations__r   r#   intdictrC   r:   r5   rv   rv      s     $$ !9::!%%r:   rv   emb_timestampc                    	 | j                   j                  | j                        }t        j                  |      }|j                  |      S # t        $ r2 |j                  dd       |j                  dd       t        di |cY S w xY w)NcrlsrC   ocsps)	rk   get_historical_resolversigned_revisionr   read_dssas_validation_contextr   
setdefaultr   )r~   rQ   hist_resolverdsss       r5   _instantiate_ltv_vcr      s    	>%,,DD))
 $,,];(()BCC >!,,VR8!,,Wb9 =#<==>s   A
A 8BBc                 X  K   t        |       }t        |      }|}d }d}d }t        |      D ]g  \  }}|j                  |k  r nS|j	                         }	t        |j                  ||	       d {   }t        |j                  |       t        ||      }i t        |||dz   |      S 7 :w)Nr   )rw   rx   ry   rz   )r'   r}   	enumerater   compute_digestr)   signed_datar_   rP   r   rv   )
rk   bootstrap_validation_contextrQ   until_revision
timestamps
current_vc	ts_statusts_countr~   external_digests
             r5   _establish_timestamp_trust_ltar      s      %V,J $%> ?-JIHM#,Z#8 
-((>9'6683%%z?
 
	 	"!:	

 )4


$  $ 1$=	 
s   A+B*-B(.;B*embedded_sigvalidation_typer   diff_policykey_usage_settings	skip_diffc	           	      	  K   t        |xs i       }	|	j                  dd       |	j                  dd       |	d   }
|r!t        |
      |	d<   |Nt        |
      |d<   n>d|	vr:|	j                  dt        |
             ||j                  dt        |
             | j                  }|t
        j                  k(  rd}|xs t        di |	}nVt        j                  |      }||j                  |	d	      }n+|}|j                  j                  |j                                | j                          | j                          d}d}d
}|t
        j                  k7  rt!        |||	| j"                         d{   }|j$                  }|j&                  }	|j(                  rt+        |j(                  |	      }|j,                  |t
        j.                  k(  rt1        d      |t
        j2                  k(  s|j$                  dk\  sJ |j,                  }|j(                  }| j4                  }|B| j6                  }|J t9        |||       d{   }|J |j:                  }||	d<   |)||d<   n#|t
        j.                  k(  r|dk(  rt1        d      |t1        d      t=        |j:                  |	       d}|t
        j                  k(  rEt?        | j@                        \  }}||	d<   ||	d<   t        di |	}|p||d<   ||d<   t        di |}nZ|t
        j2                  k(  r)|J |j                  |	      }|0|j                  |      }n|J t+        ||	      }|t+        ||      }||t
        j2                  k(  r?||}n|J |jB                  }tE        |tF        |d|j:                  i      }| d{   }n|}| jI                  ||       | jK                         }|jM                  |j:                  |d       tO        jP                  |      }tS        | jB                  | jT                  |||       d{   }tW        | |d   d       |%|j                  j                  | jX                         |jM                  t[        | j\                  | j^                  || j@                  d          d{          tO        di |S 7 Q7 7 7 7 w)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.
    rS   TrV   FrX   rU   NrW   )include_revinfor   )rQ   r   z>Purported PAdES-LTA signature does not have a timestamp chain.r   rT   zlPAdES-LTA signature requires separate timestamps protecting the signature & the rest of the revocation info.z+LTV signatures require a trusted timestamp.r   r   rP   )
status_clsra   status_kwargs)r   r   )signer_reported_dttimestamp_validity)
raw_digestra   r   r   validation_path)timestamp_foundsigned_attrs)sd_attr_certificatessigner_certra   sd_signed_attrsrC   )0r}   r   rL   rO   rk   r$   r?   r   r   r   r   certificate_registryregister_multiple
load_certsr   compute_tst_digestr   r   ry   rz   rw   r   rx   rA   r   r@   attached_timestamp_datatst_signature_digestr)   rP   r_   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   rQ   r   ac_validation_context_kwargsforce_revinfor   r   r   	vc_kwargsr]   rk   r   r   earliest_good_timestamp_strw   ry   ts_trust_datar`   r   signature_poestored_ac_vcr   r   	stored_vcts_to_validatets_status_cororj   r   s                                r5   r(   r(     s    h 4:;I )40.6 12K&G +'
	"# (30(3 ))9:
 
)	+-+N	
 (3(33 1(3   F6BBB1 
5F 6
6


 $,,V4'/225 3 J 6J++==cnn>NO!##% FJ15JO6BBB<&/'77	
 
 (77!==	##,(()J ,,4#?#I#II*P 
 ;DDD,,1	
2 &3%E%E""--
 #::O"+@@#///+DZ)=,
 &
" *5552<<+	('35B(27AAAq  '?
 	
 ")&9
 	
 8BBINL6BBB4\5M5MNt"	' 	&%2	2	'349(137(0,L/KLL	8AA	A --i8	'344,L %%%'
I>	'3.8L 	#:CCC&,N
 )))'33N5/(&(B(L(LM	
 <J5I
 6''9 (  !99;M"<"F"F"2	
 ,EE /  //$#- M !m$56 ));;--	
 (!-!A!A$00+(44^D	
 	
 ...c
R&
x 6J( 	
s^   E6S8S	9CSSE)S5S6BS:S;A:S5S6SSSSSr   c                     	 t        | d   d      }t	        |d   xs d      }t	        |d   xs d      }||fS # t        t        f$ r}t        d      |d}~ww xY w)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ocsprC   crl)r   r   r   r   list)r   revinfoer   r   s        r5   r&   r&   D  sy    3L')I4
 &B'E$"%D$; &'@A (N
	s   9 AAAc                 F    |xs 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.
    )r   r   rC   )r&   r   )r   rQ   r   r   s       r5   r%   r%   _  s<     !: ?R0=KE4 $"; r:   )NNNFNNFr1   )Jloggingdataclassesr   r   enumr   typingr   r   r   
asn1cryptor	   r
   asn1_pdfpyhanko_certvalidatorr   !pyhanko_certvalidator.policy_declr   r   r   pyhanko.pdf_utils.readerr   diff_analysisr   generalr   r   r   r   r   errorsr   r   r   generic_cmsr   r   r   r   pdf_embeddedr   r   settingsr    statusr!   r"   r#   __all__	getLoggerr;   rf   r*   r$   CHECK_IF_DECLAREDrI   rL   CRL_OR_OCSP_REQUIREDrN   rO   r}   r_   
SignedDatabytesr)   r'   rv   r   r   boolr(   
SignerInfor&   r%   rC   r:   r5   <module>r      s)    !   . .  & 3  3 & 
 ' 
  M )  
		8	$\9
+4 +: *B.@@4FF* & )A.CC4II) %"A"A48"AJ'^^')'  'T"#( & & &>'>#
 #` 15@D!%(,8<h/&h/1h/  (~h/ #++<"=	h/ *%h/ !!45h/ h/ h/V	 8 <@r:   