
    Wwg`                        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jl                  d#fd e)d!ed$e7fd%Z8y)'    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enumerate_ocsp_certs   )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y)	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                    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     R/var/www/horilla/myenv/lib/python3.12/site-packages/pyhanko/sign/validation/dss.pyas_pdf_objectzVRI.as_pdf_objectB   s    
 &&(98F;K'LM::%,%8%8%DC!"99$+$7$7		$BC !!(!4!4TZZ!@HW
    N)__name__
__module____qualname____doc__
data_fieldsetr%   __annotations__r&   r'   r   r+   r0    r1   r/   r   r   '   s[     C0E30 C0E30 3/D#/w77 r1   r   c              #      K   | d   j                   }|dk(  r5| d   }|d   j                   dk(  r|d   j                  }|d   E d{    yyy7 w)	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/   r   r   P   sn     
 ,-44F&'78/*115JJ%j188H((( K  )s   AAAAc                   R   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	dededee   defd       Zy)!r   z,
    Representation of a DSS in Python.
    Nwriterc                    ||ni | _         ||ni | _        ||ng | _        ||ng | _        || _        ||nt        j                         | _        i }| j                  D ]!  }|j                         j                  }	|||	<   # || _
        i }
| j                  D ]!  }|j                         j                  }||
|<   # |
| _        d| _        y )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__b   s     +6*A;r#/UR
#/UR
 ,D"	 "- ))+ 	 


 	.H!,,.33J%-Jz"	. &	yy 	+G**,11I#*Ii 	+ $r1   c                     | j                   S N)rN   r-   s    r/   modifiedzDocumentSecurityStore.modified   s    ~~r1   c                     | j                   s:d| _         | j                  &| j                  j                  | j                         y y y )NT)rN   rI   rF   update_containerrX   s    r/   _mark_modifiedz$DocumentSecurityStore._mark_modified   s>    ~~!DN&&2,,T-D-DE 3 r1   c              #     K   |D ]  }|j                         }	 ||     y # t        $ r\ | j                  j                  t	        j
                  |            }| j                          |||<   |j                  |       | Y w xY ww)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%	  kk,,((Y? ##%"%YC 	s&   B#BA"BBBBc                 `    fd} |       D cg c]  }| j                  |       c}S c c}w )Nc               3   F   K   D ]  } t        |       E d {     y 7 wrW   )r   )respr&   s    r/   extra_certszADocumentSecurityStore._embed_certs_from_ocsp.<locals>.extra_certs   s'      6/55565s   !!)_embed_cert)r-   r&   ro   cert_s    `  r/   _embed_certs_from_ocspz,DocumentSecurityStore._embed_certs_from_ocsp   s,    	6 6A]CE  'CCCs   +c                 R   | j                   t        d      	 | j                  |j                     S # t        $ r Y nw xY w| j                   j                  t        j                  |j                                     }| 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/   rp   z!DocumentSecurityStore._embed_cert   s    ;;@AA	::d0011 		 kk$$  TYY[9
 	),

4%%&
s   2 	>>r(   c                     t        j                  |       j                         j                         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   s<     X&--/335;;=e$$r1   r9   r%   r&   r'   c                   | j                   t        d      t        |      }t        |      }t               }t               }|D ch c]  }| j	                  |       }}|r0t        | j                  || j                  | j                              }|r0t        | j                  || j                  | j                              }|j                  t        | j                  |                   |Ut        |||      }	| j                   j                  |	j                               | j                  |<   | j!                          yyc c}w )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.
        Nrt   r   )rF   ru   listr7   rp   rk   rL   r&   rM   r'   updaterr   r   rb   r0   rH   r\   )
r-   
identifierr%   r&   r'   	ocsp_refscrl_refsrw   	cert_refsr.   s
             r/   register_vriz"DocumentSecurityStore.register_vri   s&   " ;;@AAUDzE	58=>T%%d+>	>,,4++TZZI
 ,,T4??DIINH
 	T88?@A !IYXFC+/;;+A+A!!#,DZ( ! "# ?s   Ec                    | j                   }t        j                  t        | j                  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/   r0   z#DocumentSecurityStore.as_pdf_object   s     **$00djj6G6G6I1JK&778H8HIHV::+2+>+>tzz+JHXh'(99*1*=*=dii*HHXg&'r1   c              #      K   | j                   j                         D ]5  }|j                         }t        j                  |j
                        }| 7 yw)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_streamrw   s       r/   
load_certsz DocumentSecurityStore.load_certs	  sM      

))+ 	H080C0C0EK##K$4$45DJ	s   AATc                 ~   t        |      }|j                  dg       }t        | j                               |z   }|rt        |j                  dd            }| j                  D ]L  }|j                         }t        j                  j                  |j                        }|j                  |       N ||d<   t        |j                  dd            }	| j                  D ]L  }
|
j                         }t        j                  j                  |j                        }|	j                  |       N |	|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&   r9   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  s)    %))B$C!/33M2FT__&'+5266wCDE JJ #4<4G4G4I --22;3C3CDT"# 27%g.155fbABD99 !3:3E3E3G
..33JOODC ! 15%f- PUP6OPPr1   handlerc                 0   	 |j                   d   }i }t        |dt        g       }|D ]@  }|j                         }t        j                  |j                        }|||j                  <   B t        |dt        g       }	g }
|	D ]L  }|j                         }t        j                  j                  |j                        }|
j                  |       N t        |dt        g       }g }|D ]L  }|j                         }t        j                  j                  |j                        }|j                  |       N 	 t        |d         }t!        |t"              r|}nd} | |||	|||      }|S # t        $ r}t               |d}~ww xY w# t        $ r d}Y Nw xY w)	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   rv   r   r   rd   r   r   r   
isinstancer   )clsr   dss_dicter   cert_ref_listr   r   rw   r   r&   rP   r   rn   r   r'   rS   r   r   rH   rF   dsss                         r/   read_dsszDocumentSecurityStore.read_dss8  s   	+||F+H 	%h$K% 	5H080C0C0EK + 0 01A1A BD,4Id(()	5
 "(HdBG	! 	H080C0C0EK))..{/?/?@DLL	
 !7D"E 	G/6/A/A/CJ**//
@CKK		x/0K
 g01FF
 #'
 
_  	+!#*	+6  	K	s)   E+ 8F +	F4E??FFFr%   r&   r'   pathsvalidation_contextembed_rootspdf_outr   c                   	 | j                  |      }	d}
|t        j                  |      }nd}dt        t
        j                     ffd}fd}fd}|	j                  | |        |        |       	       |	j                         }|
r9|j                  |      }||j                  t        d
      <   |j                          |	S # t        $ r d}
 | |      }	Y w xY w)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   xs dE d {    xs dD ]$  } t        |       }st        |       |E d {    & y 7 27 	wNr9   )iternext)path
path_partsr%   r   r   s     r/   _certsz:DocumentSecurityStore.supply_dss_in_writer.<locals>._certs  sO     {"" &!$Z
"$%%%& # &s   
AA *AAAAc               3   `   K    xs dE d {    j                   E d {    y y 7 7 wr   )r&   )r&   r   s   r/   _ocspsz:DocumentSecurityStore.supply_dss_in_writer.<locals>._ocsps  s7     {""!--3333 . #3   
.*.,..c               3   `   K    xs dE d {    j                   E d {    y y 7 7 wr   )r'   )r'   r   s   r/   _crlsz9DocumentSecurityStore.supply_dss_in_writer.<locals>._crls  s7     zr!!!--2222 . "2r   r   r   )r   r   r   r   r   r	   r
   r   r0   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_writerv  s    t	&,,w'CG
 #.EEJ J	&!1!12 	&	4
	3
 	fhfhUW 	 	
 $$& ((2G-4GLL&)*!
U * 	&GW%C	&s   C C('C(F)	r%   r&   r'   r   r   force_writer   file_credentialstrictr   r   r   c       	   
          t        ||      }|j                  |
|j                  j                  |
       | j                  ||||||||	      }|s|j                  r|j                          yy)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.
        :param strict:
            If ``True``, enforce strict validation of the input stream.
            Default is ``True``.
        )r   Nr   )r   security_handlerauthenticater   rY   write_in_place)r   output_streamr   r%   r&   r'   r   r   r   r   r   r   r   r   s                 r/   add_dsszDocumentSecurityStore.add_dss  s    @ +=H##/O4O$$11/B&&1# ' 	
 #,,""$ 'r1   )NNNNN)T) r2   r3   r4   r5   r   r   rU   propertyrY   r\   rk   rr   rp   staticmethodr   
NameObjectr   r   r0   r   r	   r
   r   r   r   classmethodr   r   boolr   r!   r   r9   r1   r/   r   r   ]   s     *+ D  FD  %G,>,> % % 13"2 /"b*
HT%5%56 
 :>!Q	!QF ;z ;.E ; ;z   f"f f 
!f fP  ! :>M% M% M% ""67M% M% M%r1   r   Fembedded_sigr   c                   K   j                   j                  }|j                  st        j	                  d       g fd} || j
                         d{    |s&| j                   || j                         d{    S 7 .7 w)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        ||      }|j	                  t                      d {   }j                  |       y 7 w)N)intermediate_certsr   )	key_usage)r   signer_certr   r   async_validate_usager7   rd   )signed_data	cert_inforw   r   	validatorr   r   r   s         r/   _validate_signed_dataz6collect_validation_info.<locals>._validate_signed_dataW  sf     ,[9	$$++(*1
	
 33ce3DDT Es   AA+A)A+N)revinfo_policyrevocation_checking_policy	essentialloggerwarningr   attached_timestamp_data)r   r   skip_timestamprevinfo_fetch_policyr   r   s    `   @r/   r   r   0  s     : 	))DD   ))8	

 E   8 8
999lBBN#L$H$HIIIL	 :Is$   ABB'BB
B
BTr   c	                   K   | j                   }	|r$|	j                  x}
}t        j                  |       nt        j                  |      }
t        | ||       d{   }|r*| j                  j                         j                  d      }nd}t        j                  |	      }||_        t        j                  |||||      }|s|j                  r%|r|j                          nY|j!                  |
       nG|sE|	j                  j#                  d       t        j$                  t'        |      |	j                  |
       t        j(                  ||
      S 7 w)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   k  s5    p )//F "(--/ 	..v666v>)( E #11557>>wG&226:G&G)>>- ? M m,,""$MM.) 	19Z0&--P779s   AEEC9E)F)9rz   loggingdataclassesr   r   r6   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"   	getLoggerr2   r   r   r   r   r   DEFAULT_CHUNK_SIZEr   r   r9   r1   r/   <module>r     s      ! + % & (  ' I 5 + . I 0 2 6 . ? . 4 -			8	$ % % %P
)P% P%l 8&8)8| &&c8&c8)c8 c8r1   