
     h`                        d dl Z d dlZd dlmZ d dlmZ d dl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 d d
lmZ d dl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" ddl#m$Z$ ddl%m&Z&m'Z' ddl(m)Z) g dZ*ddl+m,Z, ddl-m.Z.  ej/        e0          Z1e G d d                      Z2d Z3 G d d          Z4	 d&d e)d!efd"Z5dd#dddej6        d#fd e)d!ed$e7fd%Z8dS )'    N)	dataclass)field)IterableOptional)crl)ocsp)x509)Certificate)CertificateValidatorValidationContext)ValidationPath)genericmisc)pdf_name)IncrementalPdfFileWriter)get_and_apply)
PdfHandler)BasePdfFileWriter   )extract_certificate_info   )NoDSSFoundErrorValidationInfoReadingError)EmbeddedPdfSignature)VRIDocumentSecurityStoreasync_add_validation_infocollect_validation_info   )SerialisedCredential)PdfFileReaderc                       e Zd ZU dZ ee          Zeed<   	  ee          Zeed<   	  ee          Z	eed<   	 de
j        fdZdS )	r   aA  
    VRI dictionary as defined in PAdES / ISO 32000-2.
    These dictionaries collect data that may be relevant for the validation of
    a specific signature.

    .. note::
        The data are stored as PDF indirect objects, not asn1crypto values.
        In particular, values are tied to a specific PDF handler.
    )default_factorycertsocspscrlsreturnc                 x   t          j        t          d          t          d          i          }| j        r)t          j        | j                  |t          d          <   | j        r)t          j        | j                  |t          d          <   t          j        | j                  |t          d          <   |S )zT
        :return:
            A PDF dictionary representing this VRI entry.
        z/Type/VRIz/OCSPz/CRLz/Cert)r   DictionaryObjectr   r%   ArrayObjectr&   r$   )selfvris     W/var/www/html/Sam_Eipo/venv/lib/python3.11/site-packages/pyhanko/sign/validation/dss.pyas_pdf_objectzVRI.as_pdf_objectA   s    
 &(9(98F;K;K'LMM: 	E%,%8%D%DC!!"9 	C$+$7	$B$BC  !!(!4TZ!@!@HW
    N)__name__
__module____qualname____doc__
data_fieldsetr$   __annotations__r%   r&   r   r*   r/    r0   r.   r   r   &   s           C000E3000 C000E3000 
3///D#///w7      r0   r   c              #      K   | d         j         }|dk    r6| d         }|d         j         dk    r|d         j        }|d         E d{V  dS dS dS )	zJ
    Essentially nabbed from _extract_ocsp_certs in ValidationContext
    response_status
successfulresponse_bytesresponse_typebasic_ocsp_responseresponser$   N)nativeparsed)ocsp_responsestatusr<   r?   s       r.   enumerate_ocsp_certsrD   O   s~      
 ,-4F&'78/*15JJJ%j18H((((((((((	 JJr0   c            
       j   e Zd ZdZ	 	 	 	 	 ddee         fdZed             Zd Z	d Z
d Zd	 Zed
ej        fd            ZdddddZd Zd
eej                 fdZ	 dd
efdZeded
d fd            Zeddddddddeded
d fd            Zeddddddddddededee         fd            ZdS ) r   z,
    Representation of a DSS in Python.
    Nwriterc                 v   ||ni | _         ||ni | _        ||ng | _        ||ng | _        || _        ||nt          j                    | _        i }| j        D ] }|                                j	        }	|||	<   !|| _
        i }
| j        D ] }|                                j	        }||
|<   !|
| _        d| _        d S )NF)vri_entriesr$   r%   r&   rF   r   r*   backing_pdf_object
get_objectdata_ocsps_seen
_crls_seen	_modified)r,   rF   r$   r%   r&   rH   rI   
ocsps_seenocsp_ref
ocsp_bytes	crls_seencrl_ref	crl_bytess                r.   __init__zDocumentSecurityStore.__init__a   s     +6*A;;r#/UUR
#/UUR
 ,DD"	 "- )++ 	 

 	. 	.H!,,..3J%-Jz""%	y 	+ 	+G**,,1I#*Ii  #r0   c                     | j         S N)rN   r,   s    r.   modifiedzDocumentSecurityStore.modified   s
    ~r0   c                 v    | j         s/d| _         | j        #| j                            | j                   d S d S d S )NT)rN   rI   rF   update_containerrX   s    r.   _mark_modifiedz$DocumentSecurityStore._mark_modified   sN    ~ 	F!DN&2,,T-DEEEEE	F 	F22r0   c              #   0  K   |D ]}|                                 }	 ||         V  "# t          $ rb | j                            t	          j        |                    }|                                  |||<   |                    |           |V  Y w xY wd S )Nstream_data)dumpKeyErrorrF   
add_objectr   StreamObjectr\   append)r,   objsseendestobj	obj_bytesrefs          r.   _cms_objects_to_streamsz-DocumentSecurityStore._cms_objects_to_streams   s       	 	C

I	9o%%%%   k,,(Y???  ##%%%"%YC   							 	s   
'A)BBc                 <     fd} fd |            D             S )Nc               3   @   K   D ]} t          |           E d {V  d S rW   )rD   )respr%   s    r.   extra_certszADocumentSecurityStore._embed_certs_from_ocsp.<locals>.extra_certs   sC       6 6/55555555556 6r0   c                 :    g | ]}                     |          S r8   _embed_cert).0cert_r,   s     r.   
<listcomp>z@DocumentSecurityStore._embed_certs_from_ocsp.<locals>.<listcomp>   s'    CCCE  ''CCCr0   r8   )r,   r%   ro   s   `` r.   _embed_certs_from_ocspz,DocumentSecurityStore._embed_certs_from_ocsp   s@    	6 	6 	6 	6 	6 DCCC[[]]CCCCr0   c                 <   | j         t          d          	 | j        |j                 S # t          $ r Y nw xY w| j                             t          j        |                                                    }| 	                                 || j        |j        <   |S )N"This DSS does not support updates.r^   )
rF   	TypeErrorr$   issuer_serialra   rb   r   rc   r`   r\   )r,   certrj   s      r.   rr   z!DocumentSecurityStore._embed_cert   s    ;@AAA	:d011 	 	 	D	 k$$ TYY[[999
 
 	),
4%&
s   * 
77r'   c                     t          j        |                                                                                                           }t          d|z             S )a  
        Hash the contents of a signature object to get the corresponding VRI
        identifier.

        This is internal API.

        :param contents:
            Signature contents.
        :return:
            A name object to put into the DSS.
        /)hashlibsha1digesthexupperr   )contentsidents     r.   sig_content_identifierz,DocumentSecurityStore.sig_content_identifier   sI     X&&--//3355;;==e$$$r0   r8   r$   r%   r&   c                     j         t          d          t          |          }t          |          }t                      }t                      } fd|D             }|r.t                               | j         j                            }|r.t                               | j         j                            }|	                    t           
                    |                               |\t          |||          } j                             |                                           j        |<                                     dS dS )a  
        Register validation information for a set of signing certificates
        associated with a particular signature.

        :param identifier:
            Identifier of the signature object (see `sig_content_identifier`).
            If ``None``, only embed the data into the DSS without associating
            it with any VRI.
        :param certs:
            Certificates to add.
        :param ocsps:
            OCSP responses to add.
        :param crls:
            CRLs to add.
        Nrx   c                 :    h | ]}                     |          S r8   rq   )rs   r{   r,   s     r.   	<setcomp>z5DocumentSecurityStore.register_vri.<locals>.<setcomp>   s'    >>>T%%d++>>>r0   r   )rF   ry   listr6   rk   rL   r%   rM   r&   updaterv   r   rb   r/   rH   r\   )	r,   
identifierr$   r%   r&   	ocsp_refscrl_refs	cert_refsr-   s	   `        r.   register_vriz"DocumentSecurityStore.register_vri   s]   " ;@AAAUDzzEE	55>>>>>>>	 	,,4+TZ  I
  	,,T4?DINN H
 	T88??@@AAA !IYXFFFC+/;+A+A!!##, ,DZ( !!!!! "!r0   c                    | j         }t          j        t          | j                                                            |d<   | j        rt          j        | j                  |d<   | j        r)t          j        | j                  |t          d          <   | j
        r)t          j        | j
                  |t          d          <   |S )z
        Convert the :class:`.DocumentSecurityStore` object to a python
        dictionary. This method also handles DSS updates.

        :return:
            A PDF object representing this DSS.
        /Certsr)   /OCSPs/CRLs)rI   r   r+   r   r$   valuesrH   r*   r%   r   r&   )r,   pdf_dicts     r.   r/   z#DocumentSecurityStore.as_pdf_object   s     *$0dj6G6G6I6I1J1JKK 	J&78HIIHV: 	K+2+>tz+J+JHXh''(9 	I*1*=di*H*HHXg&&'r0   c              #      K   | j                                         D ]3}|                                }t          j        |j                  }|V  4dS )z
        Return a generator that parses and yields all certificates in the DSS.

        :return:
            A generator yielding :class:`.Certificate` objects.
        N)r$   r   rJ   r
   loadrK   )r,   cert_refcert_streamr{   s       r.   
load_certsz DocumentSecurityStore.load_certs  s^       
))++ 	 	H080C0C0E0EK#K$455DJJJJ	 	r0   Tc                    t          |          }|                    dg           }t          |                                           |z   }|rt          |                    dd                    }| j        D ]O}|                                }t          j                            |j	                  }|
                    |           P||d<   t          |                    dd                    }	| j        D ]O}
|
                                }t          j                            |j	                  }|	
                    |           P|	|d<   t          dd|i|S )ag  
        Construct a validation context from the data in this DSS.

        :param validation_context_kwargs:
            Extra kwargs to pass to the ``__init__`` function.
        :param include_revinfo:
            If ``False``, revocation info is skipped.
        :return:
            A validation context preloaded with information from this DSS.
        other_certsr%   r8   r&   )dictpopr   r   r%   rJ   	asn1_ocspOCSPResponser   rK   rd   r&   asn1_crlCertificateListr   )r,   validation_context_kwargsinclude_revinforo   r$   r%   rP   ocsp_streamrn   r&   rS   
crl_streamr   s                r.   as_validation_contextz+DocumentSecurityStore.as_validation_context  sW    %))B$C$C!/33M2FFT__&&''+5 	5266wCCDDE J # #4<4G4G4I4I -22;3CDDT""""16%g.155fbAABBD9 ! !3:3E3E3G3G
.33JODDC    04%f- PPUP6OPPPr0   handlerc                 j   	 |j         d         }n!# t          $ r}t                      |d}~ww xY wi }t          |dt          g           }|D ]9}|                                }t          j        |j                  }|||j	        <   :t          |dt          g           }	g }
|	D ]O}|                                }t          j                            |j                  }|
                    |           Pt          |dt          g           }g }|D ]O}|                                }t          j                            |j                  }|                    |           P	 t          |d                   }n# t          $ r d}Y nw xY wt!          |t"                    r|}nd} | |||	|||          }|S )	a  
        Read a DSS record from a file and add the data to a validation context.

        :param handler:
            PDF handler from which to read the DSS.
        :return:
            A DocumentSecurityStore object describing the current state of the
            DSS.
        /DSSNr   )defaultr   r   r)   )rF   r$   r%   rH   r&   rI   )rootra   r   r   r   rJ   r
   r   rK   rz   r   r   rd   r   r   r   
isinstancer   )clsr   dss_dicter   cert_ref_listr   r   r{   r   r%   rP   r   rn   r   r&   rS   r   r   rH   rF   dsss                         r.   read_dsszDocumentSecurityStore.read_dss7  s   	+|F+HH 	+ 	+ 	+!##*	+ 	%h$KKK% 	5 	5H080C0C0E0EK + 01A B BD,4Id())!(HdBGGG	! 	 	H080C0C0E0EK)..{/?@@DLL 7D"EEE 	 	G/6/A/A/C/CJ*//
@@CKK	x/00KK 	 	 	KKK	 g011 	FFF
 c#'
 
 
 
s"    
.). E6 6FFr$   r%   r&   pathsvalidation_contextembed_rootspdf_outr   c                "   	 |                      |          }	d}
n# t          $ r d}
 | |          }	Y nw xY w|t                              |          }nd}dt          t
          j                 ffd}fd}fd}|	                    | |             |             |            	           |	                                }|
r@|	                    |          }||j
        t          d
          <   |                                 |	S )aD  
        Add or update a DSS, and optionally associate the new information with a
        VRI entry tied to a signature object.

        You can either specify the CMS objects to include directly, or
        pass them in as output from `pyhanko_certvalidator`.

        :param pdf_out:
            PDF writer to write to.
        :param sig_contents:
            Contents of the new signature (used to compute the VRI hash), as
            a hexadecimal string, including any padding.
            If ``None``, the information will not be added to any VRI
            dictionary.
        :param certs:
            Certificates to include in the VRI entry.
        :param ocsps:
            OCSP responses to include in the VRI entry.
        :param crls:
            CRLs to include in the VRI entry.
        :param paths:
            Validation paths that have been established, and need to be added
            to the DSS.
        :param validation_context:
            Validation context from which to draw OCSP responses and CRLs.
        :param embed_roots:
            .. versionadded:: 0.9.0

            Option that controls whether the root certificate of each validation
            path should be embedded into the DSS. The default is ``True``.

            .. note::
                Trust roots are configured by the validator, so embedding them
                typically does nothing in a typical validation process.
                Therefore they can be safely omitted in most cases.
                Nonetheless, embedding the roots can be useful for documentation
                purposes.

            .. warning::
                This only applies to paths, not the ``certs`` parameter.

        :return:
            a :class:`DocumentSecurityStore` object containing both the new
            and existing contents of the DSS (if any).
        FT)rF   Nr'   c               3   ~   K   pdE d {V  pdD ]*} t          |           }st          |           |E d {V  +d S Nr8   )iternext)path
path_partsr$   r   r   s     r.   _certsz:DocumentSecurityStore.supply_dss_in_writer.<locals>._certs  s|      {""""""" & &!$ZZ
" %$$$%%%%%%%%%& &r0   c               3   B   K    pdE d {V  j         E d {V  d S d S r   )r%   )r%   r   s   r.   _ocspsz:DocumentSecurityStore.supply_dss_in_writer.<locals>._ocsps  sR      {"""""""!--3333333333 .-r0   c               3   B   K    pdE d {V  j         E d {V  d S d S r   )r&   )r&   r   s   r.   _crlsz9DocumentSecurityStore.supply_dss_in_writer.<locals>._crls  sR      zr!!!!!!!!--2222222222 .-r0   r   r   )r   r   r   r   r   r	   r
   r   r/   rb   r   r   update_root)r   r   sig_contentsr$   r%   r&   r   r   r   r   createdr   r   r   r   r   dss_refs      ``````        r.   supply_dss_in_writerz*DocumentSecurityStore.supply_dss_in_writeru  s   t	&,,w''CGG) 	& 	& 	&G#W%%%CCC	& #.EE JJ J	&!12 	& 	& 	& 	& 	& 	& 	& 	&	4 	4 	4 	4 	4 	4
	3 	3 	3 	3 	3 	3
 	ffhhffhhUUWW 	 	
 	
 	
 $$&&  	"((22G-4GL&))*!!!
s     ;;F)r$   r%   r&   r   r   force_writer   file_credentialr   r   c          
          t          |          }|j        |
|j                            |
           |                     ||||||||	          }|s|j        r|                                 dS dS )a$  
        Wrapper around :meth:`supply_dss_in_writer`.

        The result is applied to the output stream as an incremental update.

        :param output_stream:
            Output stream to write to.
        :param sig_contents:
            Contents of the new signature (used to compute the VRI hash), as
            a hexadecimal string, including any padding.
            If ``None``, the information will not be added to any VRI
            dictionary.
        :param certs:
            Certificates to include in the VRI entry.
        :param ocsps:
            OCSP responses to include in the VRI entry.
        :param crls:
            CRLs to include in the VRI entry.
        :param paths:
            Validation paths that have been established, and need to be added
            to the DSS.
        :param force_write:
            Force a write even if the DSS doesn't have any new content.
        :param validation_context:
            Validation context from which to draw OCSP responses and CRLs.
        :param embed_roots:
            .. versionadded:: 0.9.0

            Option that controls whether the root certificate of each validation
            path should be embedded into the DSS. The default is ``True``.

            .. note::
                Trust roots are configured by the validator, so embedding them
                typically does nothing in a typical validation process.
                Therefore they can be safely omitted in most cases.
                Nonetheless, embedding the roots can be useful for documentation
                purposes.

            .. warning::
                This only applies to paths, not the ``certs`` parameter.
        :param file_credential:
            .. versionadded:: 0.13.0

            Serialised file credential, to update encrypted files.
        Nr   )r   security_handlerauthenticater   rY   write_in_place)r   output_streamr   r$   r%   r&   r   r   r   r   r   r   r   s                r.   add_dsszDocumentSecurityStore.add_dss  s    x +=99#/O4O$11/BBB&&1# ' 	
 	
  	%#, 	%""$$$$$	% 	%r0   )NNNNN)T) r1   r2   r3   r4   r   r   rU   propertyrY   r\   rk   rv   rr   staticmethodr   
NameObjectr   r   r/   r   r	   r
   r   r   r   classmethodr   r   boolr   r    r   r8   r0   r.   r   r   \   sg            *+       D   XF F F  D D D    %G,> % % % \% 13"2 /" /" /" /" /"b  *
HT%56 
 
 
 
 :>!Q !Q	!Q !Q !Q !QF ;z ;.E ; ; ; [;z   f f f"f f 
!f f f [fP  ! :>I% I% I% I% I% ""67I% I% I% [I% I% I%r0   r   Fembedded_sigr   c                    K   j         j        }|j        st                              d           g fd} || j                   d{V  |s| j         || j                   d{V  S )a  
    Query revocation info for a PDF signature using a validation context,
    and store the results in a validation context.

    This works by validating the signer's certificate against the provided
    validation context, which causes revocation info to be cached for
    later retrieval.

    .. warning::
        This function does *not* actually validate the signature, but merely
        checks the signer certificate's chain of trust.

    :param embedded_sig:
        Embedded PDF signature to operate on.
    :param validation_context:
        Validation context to use.
    :param skip_timestamp:
        If the signature has a time stamp token attached to it, also collect
        revocation information for the timestamp.
    :return:
        A list of validation paths.
    zfRevocation mode is set to soft-fail/tolerant mode; collected revocation information may be incomplete.c                    K   t          |           }|j        }|j        }t          ||          }|                    t                                 d {V }                    |           d S )N)intermediate_certsr   )	key_usage)r   signer_certr   r   async_validate_usager6   rd   )signed_data	cert_infor{   r   	validatorr   r   r   s         r.   _validate_signed_dataz6collect_validation_info.<locals>._validate_signed_dataR  s      ,[99	$+(*1
 
 
	
 33cee3DDDDDDDDTr0   N)revinfo_policyrevocation_checking_policy	essentialloggerwarningr   attached_timestamp_data)r   r   skip_timestamprevinfo_fetch_policyr   r   s    `   @r.   r   r   +  s      : 	)D   ) 
8	
 	
 	

 E       
 8
9
99999999 JlBN##L$HIIIIIIIIILr0   Tr   c	                   K   | j         }	|r|	j        x}
}t          j        |           nt          j        |          }
t          | ||           d{V }|r-| j                                                            d          }nd}t          j
        |	          }||_        t                              |||||          }|s|j        r-|r|                                 nZ|                    |
           nD|sB|	j                            d           t          j        t'          |          |	j        |
           t          j        ||
          S )aY  
    .. versionadded: 0.9.0

    Add validation info (CRLs, OCSP responses, extra certificates) for a
    signature to the DSS of a document in an incremental update.
    This is a wrapper around :func:`collect_validation_info`.

    :param embedded_sig:
        The signature for which the revocation information needs to be
        collected.
    :param validation_context:
        The validation context to use.
    :param skip_timestamp:
        If ``True``, do not attempt to validate the timestamp attached to
        the signature, if one is present.
    :param add_vri_entry:
        Add a ``/VRI`` entry for this signature to the document security store.
        Default is ``True``.
    :param output:
        Write the output to the specified output stream.
        If ``None``, write to a new :class:`.BytesIO` object.
        Default is ``None``.
    :param in_place:
        Sign the original input stream in-place.
        This parameter overrides ``output``.
    :param chunk_size:
        Chunk size parameter to use when copying output to a new stream
        (irrelevant if ``in_place`` is ``True``).
    :param force_write:
        Force a new revision to be written, even if not necessary (i.e.
        when all data in the validation context is already present in the DSS).
    :param embed_roots:
        Option that controls whether the root certificate of each validation
        path should be embedded into the DSS. The default is ``True``.

        .. note::
            Trust roots are configured by the validator, so embedding them
            typically does nothing in a typical validation process.
            Therefore they can be safely omitted in most cases.
            Nonetheless, embedding the roots can be useful for documentation
            purposes.
    :return:
        The (file-like) output object to which the result was written.
    )r   Nascii)r   r   r   r   )readerstreamr   !assert_writable_and_random_accessprepare_rw_output_streamr   pkcs7_contentr   encoder   from_readerIO_CHUNK_SIZEr   r   rY   r   writeseekchunked_write	bytearrayfinalise_output)r   r   r   add_vri_entryin_placeoutputr   
chunk_sizer   r   working_outputr   r   r   resulting_dsss                  r.   r   r   f  s     p )/F  	?"(-/ 	.v66666v>>)(        E  #15577>>wGG&26::G&G)>>- ?  M  	Qm, 	Q 	*""$$$$MM.)))) Q 	19Z00&-PPP777r0   )F)9r~   loggingdataclassesr   r   r5   typingr   r   
asn1cryptor   r   r   r   r	   asn1crypto.x509r
   pyhanko_certvalidatorr   r   pyhanko_certvalidator.pathr   pyhanko.pdf_utilsr   r   pyhanko.pdf_utils.genericr   $pyhanko.pdf_utils.incremental_writerr   pyhanko.pdf_utils.miscr   pyhanko.pdf_utils.rw_commonr   pyhanko.pdf_utils.writerr   generalr   errorsr   r   pdf_embeddedr   __all__pdf_utils.cryptr    pdf_utils.readerr!   	getLoggerr1   r   r   rD   r   r   DEFAULT_CHUNK_SIZEr   r   r8   r0   r.   <module>r     s     ! ! ! ! ! ! + + + + + + % % % % % % % % & & & & & & ( ( ( ( ( (       ' ' ' ' ' ' I I I I I I I I 5 5 5 5 5 5 + + + + + + + + . . . . . . I I I I I I 0 0 0 0 0 0 2 2 2 2 2 2 6 6 6 6 6 6 . . . . . . ? ? ? ? ? ? ? ? . . . . . .   4 3 3 3 3 3 - - - - - -		8	$	$ % % % % % % % %P
) 
) 
)L% L% L% L% L% L% L% L%d 8 8&8)8 8 8 8| &c8 c8&c8)c8 c8 c8 c8 c8 c8 c8r0   