U
    gp                     @   s  d dl 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mZmZmZmZmZmZmZ d dl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  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+m,Z, ddl-m.Z. dddddddddddddd gZ/e 0e1Z2ed!d"G d#d dZ3ed!d"G d$d dZ4ed!d"G d%d de4Z5ed!d"G d&d dZ6ed!d"G d'd de6Z7ee8 e8e9e:d(d)d*Z;G d+d dZ<G d,d dZ=ed!d"G d-d dZ>ed!d"G d.d  d Z?ed!d"G d/d de?e4Z@eG d0d de"ZAed!d"G d1d dZBed!d"G d2d deBe@ZCed!d"G d3d deBe5ZDdS )4    N)defaultdict)	dataclass)datetime)unique)
AnyClassVar
CollectionDictIterableListOptionalSetTupleUnion)cmscorecrlkeysx509)PathBuildingErrorPathValidationErrorValidationError)ValidationPath)ACValidationResult   )OrderedEnum   )AdESFailureAdESSubIndic)
DiffResultModificationLevelSuspiciousModification   )SignatureValidationErrorSigSeedValueValidationError)KeyUsageConstraintsSignatureStatusTimestampSignatureStatusX509AttributeInfoCertifiedAttributeInfoClaimedAttributesCertifiedAttributesCAdESSignerAttributeAssertionsStandardCMSSignatureStatusSignatureCoverageLevelModificationInfoPdfSignatureStatusDocumentTimestampStatusRevocationDetailsSignerAttributeStatusT)frozenc                   @   s,   e Zd ZU dZeed< eed< ejed< dS )r2   zQ
    Contains details about a certificate revocation related to a signature.
    Z
ca_revokedZrevocation_dateZrevocation_reasonN)	__name__
__module____qualname____doc__bool__annotations__r   r   Z	CRLReason r;   r;   B/tmp/pip-unpacked-wheel-owvgwkas/pyhanko/sign/validation/status.pyr2   :   s
   

c                   @   s  e Zd ZU dZeed< eed< ee ed< ej	ed< e
ed< e
ed< ee ed< ee ed	< ee ed
< dhZeee
  ed< dZeeee
   ed< ee ed< dd ZeedddZeedddZde
dddZed ee edddZee
dddZdS )!r&   zE
    Class describing the validity of a (general) CMS signature.
    intactvalidtrust_problem_indicsigning_certpkcs7_signature_mechanismmd_algorithmvalidation_pathrevocation_detailsZerror_time_horizonZnon_repudiation	key_usageNextd_key_usageZvalidation_timec                 c   s&   | j rd}n| jrd}nd}|V  d S )NZTRUSTEDZREVOKEDZ	UNTRUSTED)trustedrevoked)selfZcert_statusr;   r;   r<   summary_fields   s    zSignatureStatus.summary_fieldsreturnc                 C   s
   | j dk	S )z
        Reports whether the signer's certificate has been revoked or not.
        If this field is ``True``, then obviously :attr:`trusted` will be
        ``False``.
        N)rD   rI   r;   r;   r<   rH      s    zSignatureStatus.revokedc                 C   s    | j o| jo| jdko| jdk	S )z
        Reports whether the signer's certificate is trusted w.r.t. the currently
        relevant validation context and key usage requirements.
        N)r>   r=   r?   rC   rM   r;   r;   r<   rG      s    zSignatureStatus.trusted,c                 C   s&   | j r| jrd||   S dS dS )zQ
        Provide a textual but machine-parsable summary of the validity.
        zINTACT:INVALIDN)r=   r>   joinrJ   )rI   	delimiterr;   r;   r<   summary   s    zSignatureStatus.summary)key_usage_settingsrL   c                 C   s>   |pt  }t |jd kr| jn|j|jd kr0| jn|jd}|S )N)rE   rF   )r%   rE   rF   )clsrS   r;   r;   r<   default_usage_constraints   s    
z)SignatureStatus.default_usage_constraintsc                 C   s$   | j d k	r| j d }|jjS dS d S )Nr   zNo path to trust anchor found.)rC   subjecthuman_friendly)rI   Ztrust_anchorr;   r;   r<   _trust_anchor   s    

zSignatureStatus._trust_anchor)rN   )N)r5   r6   r7   r8   r9   r:   r   r   r   ZCertificatestrr   r2   r   rE   r   r   rF   rJ   propertyrH   rG   rR   classmethodr%   rU   rX   r;   r;   r;   r<   r&   Q   s6   
	
		 c                   @   s>   e Zd ZU dZe Zeee  e	d< dhZ
ee	d< dd ZdS )r'   zG
    Signature status class used when validating timestamp tokens.
    rE   Ztime_stamping	timestampc                 C   s\   | j }d| jr| jrdnd d|jj d|j  d|j  d| j d| j	rRdnd d	S )
Nz`This timestamp is backed by a time stamping authority.
The timestamp token is cryptographically  unz!sound.
TSA certificate subject: "z$"
TSA certificate SHA1 fingerprint: z%
TSA certificate SHA256 fingerprint: z
TSA cert trust anchor: "z"
The TSA certificate is ztrusted.)
r@   r=   r>   rV   rW   sha1hexsha256rX   rG   )rI   Ztsar;   r;   r<   describe_timestamp_trust  s    Tz1TimestampSignatureStatus.describe_timestamp_trustN)r5   r6   r7   r8   setrE   r   r   rY   r:   rF   r   rb   r;   r;   r;   r<   r'      s
   
c                   @   s*   e Zd ZU dZejed< eej	 ed< dS )r(   z%
    Info on an X.509 attribute.
    	attr_typeattr_valuesN)
r5   r6   r7   r8   r   AttCertAttributeTyper:   r
   r   Z	Asn1Valuer;   r;   r;   r<   r(     s   

c                   @   s   e Zd ZU dZee ed< dS )r)   zI
    Info on a certified attribute, including AC validation results.
    validation_resultsN)r5   r6   r7   r8   r
   r   r:   r;   r;   r;   r<   r)   #  s   
)rd   	attr_kinderrfatalc                 C   sX   | sdn
d|  d}d| d| d|j d  }|rFt|tjd|ntj||d	 d S )
Nzunknown typeztype ''zFailed to parse z of z: r   )Zades_subindication)exc_info)argsr#   r   ZFORMAT_FAILUREloggerwarning)rd   rh   ri   rj   Zattr_type_strmsgr;   r;   r<   _handle_attr_err1  s     rq   c                   @   sn   e Zd ZdZedee dddZd dddZe	e
d	d
dZdd Zdd Zdd Ze	ed	ddZdS )r+   zJ
    Container class for extracted attribute certificate information.
    F)resultsc                 C   s   t dd }|D ]}|j D ]z}|d j}zt|d }W n: tk
rv } zt|d||d W Y qW 5 d }~X Y nX || \}	}
|	| |
| qqt	 }|
 D ].\}\}	}
tt|t|	t|
d|j|< q|S )Nc                   S   s   g g fS Nr;   r;   r;   r;   r<   <lambda>I      z2CertifiedAttributes.from_results.<locals>.<lambda>typevalueszcertified attributerj   )rd   re   rg   )r   Zapproved_attributesrw   nativelist
ValueErrorrq   extendappendr+   itemsr)   r   rf   tuple_attrs)rT   rr   parse_error_fatalby_typeresultattrrd   rw   etype_valuesZtype_resultsinfosr;   r;   r<   from_resultsC  s4    


z CertifiedAttributes.from_resultsrM   c                 C   s
   i | _ d S rs   r   rM   r;   r;   r<   __init__f  s    zCertifiedAttributes.__init__itemrL   c                 C   s
   | j | S rs   r   rI   r   r;   r;   r<   __getitem__i  s    zCertifiedAttributes.__getitem__c                 C   s
   t | jS rs   lenr   rM   r;   r;   r<   __len__l  s    zCertifiedAttributes.__len__c                 C   s
   t | jS rs   r9   r   rM   r;   r;   r<   __bool__o  s    zCertifiedAttributes.__bool__c                 C   s   t | j S rs   iterr   rw   rM   r;   r;   r<   __iter__r  s    zCertifiedAttributes.__iter__c                 C   s
   || j kS rs   r   r   r;   r;   r<   __contains__u  s    z CertifiedAttributes.__contains__N)F)r5   r6   r7   r8   r[   r
   r   r   r   rY   r)   r   r   r   r   r9   r   r;   r;   r;   r<   r+   >  s    "c                   @   sp   e Zd ZdZedeej dddZd dddZ	e
ed	d
dZdd Zdd Zdd Ze
ed	ddZdS )r*   z|
    Container class for extracted information on attributes asserted
    by a signer without an attribute certificate.
    F)attrsc           
      C   s   t  }tt}|D ]l}d }z|d j}t|d }W n: tk
rn } zt|d||d W Y qW 5 d }~X Y nX || | q| D ]$\}}	tt	
|t|	d|j|< q|S )Nrv   rw   zclaimed attributerx   )rd   re   )r*   r   rz   ry   r{   rq   r|   r~   r(   r   rf   r   r   )
rT   r   r   r   r   r   rd   rw   r   r   r;   r;   r<   from_iterable  s,    
   zClaimedAttributes.from_iterablerM   c                 C   s
   i | _ d S rs   r   rM   r;   r;   r<   r     s    zClaimedAttributes.__init__r   c                 C   s
   | j | S rs   r   r   r;   r;   r<   r     s    zClaimedAttributes.__getitem__c                 C   s
   t | jS rs   r   rM   r;   r;   r<   r     s    zClaimedAttributes.__len__c                 C   s
   t | jS rs   r   rM   r;   r;   r<   r     s    zClaimedAttributes.__bool__c                 C   s   t | j S rs   r   rM   r;   r;   r<   r     s    zClaimedAttributes.__iter__c                 C   s
   || j kS rs   r   r   r;   r;   r<   r     s    zClaimedAttributes.__contains__N)F)r5   r6   r7   r8   r[   r
   r   ZAttCertAttributer   r   rY   r(   r   r   r   r   r9   r   r;   r;   r;   r<   r*   y  s    c                   @   s^   e Zd ZU dZeed< dZee ed< dZ	ee
eeef   ed< dZeed< edd	 ZdS )
r,   z
    Value type describing information extracted (and, if relevant, validated)
    from a ``signer-attrs-v2`` signed attribute.
    Zclaimed_attrsNcertified_attrsac_validation_errsFunknown_attrs_presentc                 C   s   | j  S rs   )r   rM   r;   r;   r<   r>     s    z$CAdESSignerAttributeAssertions.valid)r5   r6   r7   r8   r*   r:   r   r   r+   r   r   r   r   r   r   r9   rZ   r>   r;   r;   r;   r<   r,     s   
	c                   @   sJ   e Zd ZU dZee ed< dZeee	e
ef   ed< dZee ed< dS )r3   Nac_attrsr   cades_signer_attrs)r5   r6   r7   r   r   r+   r:   r   r   r   r   r   r   r,   r;   r;   r;   r<   r3     s   
c                       s   e Zd ZU dZdZee ed< dZee	 ed< dZ
ee	 ed< eedddZ fd	d
Zdd Zeeeef  dddZ  ZS )r-   zs
    Status of a standard "end-entity" CMS signature, potentially with
    timing information embedded inside.
    Nsigner_reported_dttimestamp_validitycontent_timestamp_validityrK   c                 C   sf   | j }|dkrd}n|jo$|jo$|j}| j}|dkr:d}n|joJ|joJ|j}| jod| jod| jod|od|S )ab  
        Formulates a general judgment on the validity of this signature.
        This takes into account the cryptographic validity of the signature,
        the signature's chain of trust and the validity of the timestamp token
        (if present).

        :return:
            ``True`` if all constraints are satisfied, ``False`` otherwise.
        NT)r   r>   r=   rG   r   )rI   tsZtimestamp_okZ
content_tsZcontent_timestamp_okr;   r;   r<   bottom_line  s$    z&StandardCMSSignatureStatus.bottom_linec                 #   sh   t   E d H  | jd k	r.d| jjdd V  | jd k	rLd| jjdd V  | jd k	rd| jjsddV  d S )NzTIMESTAMP_TOKEN<%s>|)rQ   zCONTENT_TIMESTAMP_TOKEN<%s>ZCERTIFIED_SIGNER_ATTRS_INVALID)superrJ   r   rR   r   r   r>   rM   	__class__r;   r<   rJ   ?  s    

z)StandardCMSSignatureStatus.summary_fieldsc                    sL   dd  |   }d| jrdnd d}|d|f d fd	d
|D S )Nc                 S   s   d | dt|  |dfS )N
-)rP   r   )hdrbodyr;   r;   r<   fmt_sectionQ  s    zDStandardCMSSignatureStatus.pretty_print_details.<locals>.fmt_sectionzThe signature is judged r]   INzVALID.zBottom liner   c                 3   s   | ]\}} ||V  qd S rs   r;   ).0r   r   r   r;   r<   	<genexpr>Y  s     zBStandardCMSSignatureStatus.pretty_print_details.<locals>.<genexpr>)pretty_print_sectionsr   r}   rP   )rI   sectionsr   r;   r   r<   pretty_print_detailsP  s    z/StandardCMSSignatureStatus.pretty_print_detailsc                 C   s~  | j }| jrd}n| jrd}nd}d|jj d|j  d|j  d| j d| d	}d
| j	rj| j
rjdnd d| j d| j d}d| jkr|jd d }|jdkr|j}|d|j d|j d7 }g }| j}|d k	r|d|   | j}	|	d k	r |	j}
|d|
  d|	   | j}|d k	rT|j}
|d|
  d|   |s^dnd|}d|fd|fd |fgS )!NrG   rH   Z	untrustedzCertificate subject: "z "
Certificate SHA1 fingerprint: z!
Certificate SHA256 fingerprint: z
Trust anchor: "z"
The signer's certificate is .z#The signature is cryptographically r]   r^   z'sound.

The digest algorithm used was 'z%'.
The signature mechanism used was 'z'.Zecdsa	algorithm
parametersnamedz@
The elliptic curve used for the signer's ECDSA public key was 'z' (OID: z).z$Signing time as reported by signer: zSignature timestamp token: z9
The token is guaranteed to be newer than the signature.
zContent timestamp token: z9
The token is guaranteed to be older than the signature.
z0No available information about the signing time.z

zSigner infoZ	IntegrityzSigning time)r@   rG   rH   rV   rW   r_   r`   ra   rX   r=   r>   rB   rA   Z
public_keynameZchosenry   Zdottedr   r}   	isoformatr   r\   rb   r   rP   )rI   certZtrust_statusZabout_signerZvalidity_infoZ	ec_paramsZ	curve_oidZtiming_infosZreported_tsZ
tst_statusr   Zcontent_tst_statusZtiming_infor;   r;   r<   r   [  sZ    4	*



z0StandardCMSSignatureStatus.pretty_print_sections)r5   r6   r7   r8   r   r   r   r:   r   r'   r   rZ   r9   r   rJ   r   r   r   rY   r   __classcell__r;   r;   r   r<   r-     s   
!c                   @   s    e Zd ZdZdZdZdZdZdS )r.   a"  
    Indicate the extent to which a PDF signature (cryptographically) covers
    a document. Note that this does *not* pass judgment on whether uncovered
    updates are legitimate or not, but as a general rule, a legitimate signature
    will satisfy at least :attr:`ENTIRE_REVISION`.
    r   r"   r   r   N)r5   r6   r7   r8   ZUNCLEARZCONTIGUOUS_BLOCK_FROM_STARTENTIRE_REVISIONENTIRE_FILEr;   r;   r;   r<   r.     s   c                   @   s\   e Zd ZU dZee ed< dZeee	e
f  ed< dZee ed< eee dddZdS )r/   Ncoveragediff_result	docmdp_okrK   c                 C   sR   | j }| jdkr4|tjkrdS |tjkr.tjS tjS t| jt	rH| jj
S tjS dS )z
        Indicates the degree to which the document was modified after the
        signature was applied.

        Will be ``None`` if difference analysis results are not available;
        an instance of :class:`.ModificationLevel` otherwise.
        N)r   r   r.   r   r   r    NONEOTHER
isinstancer   modification_level)rI   r   r;   r;   r<   r     s    


z#ModificationInfo.modification_level)r5   r6   r7   r   r   r.   r:   r   r   r   r!   r   r9   rZ   r    r   r;   r;   r;   r<   r/     s
   
	c                       sr   e Zd ZU dZdZeed< dZee	 ed< e
ed fddZe
edd	d
Z fddZ fddZ  ZS )r0   z;Class to indicate the validation status of a PDF signature.Fhas_seed_valuesNseed_value_constraint_errorrK   c                    s"   t  j}|o | jo | jp | jdkS )a  
        Formulates a general judgment on the validity of this signature.
        This takes into account the cryptographic validity of the signature,
        the signature's chain of trust, compliance with the document
        modification policy, seed value constraint compliance and the validity
        of the timestamp token (if present).

        :return:
            ``True`` if all constraints are satisfied, ``False`` otherwise.
        N)r   r   seed_value_okr   r   )rI   Zgeneric_checks_okr   r;   r<   r     s    zPdfSignatureStatus.bottom_linec                 C   s
   | j dkS )a  
        Indicates whether the signature satisfies all mandatory constraints in
        the seed value dictionary of the associated form field.

        .. warning::
            Currently, not all seed value entries are recognised by the signer
            and/or the validator, so this judgment may not be entirely accurate
            in some cases.

            See :class:`~.pyhanko.sign.fields.SigSeedValueSpec`.
        N)r   rM   r;   r;   r<   r   !  s    z PdfSignatureStatus.seed_value_okc                 #   s|   t   E d H  | jtjkr$dV  n4| jtjkrR| jd k	rJd| jj V  qXdV  ndV  | jrr| jtjkrxdV  ndV  d S )NZ	UNTOUCHEDZEXTENDED_WITH_ZEXTENDEDZNONSTANDARD_COVERAGEZACCEPTABLE_MODIFICATIONSZILLEGAL_MODIFICATIONS)	r   rJ   r   r.   r   r   r   r   r   rM   r   r;   r<   rJ   1  s    
z!PdfSignatureStatus.summary_fieldsc                    s   t   }| jtjkrd}nT| jd k	rl| jtjkr8d}n| jtjkrJd}nd}d| d| j	r`dnd d	}nd
}|
d|f | jr| jrd}nd| jj }|
d|f |S )Nz%The signature covers the entire file.z1All modifications relate to signature maintenancez?All modifications relate to signing and form filling operationsz&Some modifications may be illegitimatez.The signature does not cover the entire file.
z, and they appear to be r]   inz9compatible with the current document modification policy.z'Incremental update analysis was skippedZModificationsz4There were no SV issues detected for this signature.zXThe signature did not satisfy the SV constraints on the signature field.
Error message: zSeed value constraints)r   r   r   r.   r   r   r    ZLTA_UPDATESZFORM_FILLINGr   r}   r   r   r   Zfailure_message)rI   r   Zmodification_strZmodlvl_stringZsv_infor   r;   r<   r   B  s0    

z(PdfSignatureStatus.pretty_print_sections)r5   r6   r7   r8   r   r9   r:   r   r   r$   rZ   r   r   rJ   r   r   r;   r;   r   r<   r0     s   
c                   @   s   e Zd ZdZdS )r1   zDClass to indicate the validation status of a PDF document timestamp.N)r5   r6   r7   r8   r;   r;   r;   r<   r1   k  s   )Eloggingcollectionsr   Zdataclassesr   r   enumr   typingr   r   r   r	   r
   r   r   r   r   r   Z
asn1cryptor   r   r   r   r   Zpyhanko_certvalidator.errorsr   r   r   Zpyhanko_certvalidator.pathr   Zpyhanko_certvalidator.validater   Zpdf_utils.miscr   Zades.reportr   r   Zdiff_analysisr   r    r!   errorsr#   r$   settingsr%   __all__	getLoggerr5   rn   r2   r&   r'   r(   r)   rY   r{   r9   rq   r+   r*   r,   r3   r-   r.   r/   r0   r1   r;   r;   r;   r<   <module>   s~   0
 %   ;3.'  $5l