
    WwgZ              	          d dl Z d dlZd dlmZ d dlmZ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mZmZ d dlmZ d dlmZmZ d	d
lmZmZmZmZmZmZm Z m!Z! d	dl"m#Z#m$Z$ d	dl%m&Z&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l0m1Z1 ddl2m3Z3 ddl4m5Z5 g dZ6 e- ej^                  d       ej^                  d      dddde.jn                        Z8 e9g d      Z:	  G d d e      Z; G d! d"      Z<d#e5d$e=d%ee=   fd&Z>d' Z?d( Z@d)ej                  d*ej                  fd+ZCd*e	ej                  e=f   fd,ZDe:e<fd-e1d.eeE   d/e
e<   fd0ZF G d1 d2e#      ZGd3ddej                  fd4e3d5eEfd6ZIy)7    N)compare_digest)AnyDict	FrozenSetOptionalTupleType)algoscmscore)VOID)hasheshmackeywrap)hkdf)genericmisc   )CMSStructuralErrorMultivaluedAttributeErrorNonexistentAttributeErrorValueErrorWithMessagebyte_range_digestfind_unique_cms_attributeget_pyca_cryptography_hashsimple_cms_attribute)PdfByteRangeDigestPreparedByteRangeDigest)CMSAlgorithmProtectionErrorDisallowedAlgorithmError)validate_algorithm_protection)extract_contents   )DeveloperExtensionDevExtensionMultivalued)pdf_name)PdfFileReader)BasePdfFileWriter   )PdfMacIntegrityInfo)PdfMacTokenHandlervalidate_pdf_macadd_standalone_macISO32004ALLOWED_MD_ALGSz/ISO_z/2.0i}  z:2024z'https://www.iso.org/standard/45877.htmlF)prefix_namebase_versionextension_levelextension_revisionurlcompare_by_levelmultivalued)sha256sha3_256sha384sha3_384sha512sha3_512c                       e Zd Zy)PdfMacValidationErrorN)__name__
__module____qualname__     U/var/www/horilla/myenv/lib/python3.12/site-packages/pyhanko/pdf_utils/crypt/pdfmac.pyr>   r>   J   s    rC   r>   c                      e Zd ZdZ ej
                  ddi      Zd Zede	de	de
fd       Zeefde	de	d	ej                  d
ee
   fd       ZdedefdZede	de	de	fd       Zde	dej(                  fdZdedee	ej.                  f   fdZde	dee	   dee	e	f   fdZdej.                  de	dej(                  de	dej                  f
dZde	de	de	fdZdd de	dee	   dedej:                  fd!Zd"ej>                  de	fd#Z d$ej(                  d%e!jD                  fd&Z#d	ej                  fd'Z$d	ej                  de%fd(Z&d	ej                  de	dee	   fd)Z'y*)+r+   a:  
    Internal utility class to create and validate PDF MAC tokens.

    .. warning::
        This is a class to simplify local overrides for creating test documents
        with various defects.

        Instances of this class should never be created or manipulated directly
        during regular operation.
    	algorithmr7   c                     || _         || _        y Nmac_kekmd_algorithm)selfrJ   rK   s      rD   __init__zPdfMacTokenHandler.__init__\   s    (rC   file_encryption_keykdf_saltrK   c                 :    | j                  ||      } | ||      S )NrI   )_derive_mac_kek)clsrN   rO   rK   rJ   s        rD   from_key_matzPdfMacTokenHandler.from_key_mat`   s$     %%&98D7>>rC   	auth_dataallowed_mdsc                     |d   }|d   j                   }|dk7  rt        d      |d   }|d   j                   }||vrt        |t        j                  d      | j                  |||      S )	Nmac_algorithmrF   r7   z:Only HMAC-SHA256 is currently supported for PDF MAC tokensdigest_algorithmT)oid_type	permanent)rN   rO   rK   )nativeNotImplementedErrorr    r
   DigestAlgorithmIdrS   )	rR   rN   rO   rT   rU   mac_algo_objmac_algodigest_algo_objmd_algos	            rD   for_validationz!PdfMacTokenHandler.for_validationg   s     -6o,F,33 x%L  2;;M1N!+.55+%*00	   3    
 	
rC   include_signature_digestreturnc                     t        j                  t        | j                              j	                         }| j                  ||r|nd d      }t        |j                               S )NT)document_digestsignature_digestdry_run)r   Hashr   rK   finalizebuild_pdfmac_tokenlendump)rL   rc   
dummy_hashdummy_tokens       rD   determine_token_sizez'PdfMacTokenHandler.determine_token_size   sb    [[&t'8'89

(* 	 --&+CZ . 
 ;##%&&rC   c                 z    t        j                  t        j                         d|d      }|j	                  |      S )N    s   PDFMAC)rF   lengthsaltinfo)r   HKDFr   SHA256derive)rR   rN   rO   kdfs       rD   rQ   z"PdfMacTokenHandler._derive_mac_kek   s6    
 iimmo	
 zz-..rC   message_digestc                     t        j                  | j                  t        j                  d| j                  i      d      }t        j
                  t        dd      t        d|      t        d|      g      S )NrF   )rW   rX   content_typepdf_mac_integrity_inforz   cms_algorithm_protection)r   CMSAlgorithmProtectionmac_algo_identDigestAlgorithmrK   CMSAttributesr   )rL   rz   algo_protections      rD   _format_auth_attrsz%PdfMacTokenHandler._format_auth_attrs   sy    44!%!4!4$'$7$7 $"3"34%
   $^5MN$%5~F$.
 	
rC   rh   c           	      D   |rt        d      }nt        j                  d      }t        j                  | j
                  |      }t        j                  d|t        j                  ddi      t        j                  ddi      d      }|t        j                  d|i      fS )	Nrr   )wrapping_keykey_to_wrapr   rF   pdf_mac_wrap_kdfaes256_wrap)versionencrypted_keykey_derivation_algorithmkey_encryption_algorithmpwri)bytessecretstoken_bytesr   aes_key_wraprJ   r   PasswordRecipientInfor
   KdfAlgorithmKeyEncryptionAlgorithmRecipientInfo)rL   rh   mac_keyr   r   s        rD   _get_mac_keying_infoz'PdfMacTokenHandler._get_mac_keying_info   s     BiG))"-G,,7
 ((!.,1,>,>#%7-
 -0,F,F -0-
 ))64.999rC   rf   rg   c                     d|i}|||d<   d|d<   t        |      }|j                         }t        | j                        }t	        j
                  |      }|j                  |       |j                         }||fS )Ndata_digestrg   r   r   )r*   rm   r   rK   r   ri   updaterj   )	rL   rf   rg   message_kwargsmessagemessage_bytesmd_specmd_funrz   s	            rD   _format_messagez"PdfMacTokenHandler._format_message   s     +8)I'1AN-.$%y!%n5,T->->?W%m$*n,,rC   recipient_infor   
auth_attrsmacc                     t        j                  d|gt        j                  ddi      t        j                  d| j                  i      t        j
                  dt        j                  |      d      ||d      S )Nr   rF   r7   r}   r|   content)r   recipient_infosrW   rX   encap_content_infor   r   )r   AuthenticatedDataHmacAlgorithmr   rK   EncapsulatedContentInfor   ParsableOctetString)rL   r   r   r   r   s        rD   _format_auth_dataz$PdfMacTokenHandler._format_auth_data   s     $$$2#3!$!2!2K3J!K$'$7$7 $"3"34% '*&A&A(@#'#;#;M#J' )
 	
rC   r   data_to_macc                     t        j                  |t        j                               }|j	                  |       |j                         S )N)keyrF   )r   HMACr   rw   r   rj   )rL   r   r   hmac_funs       rD   compute_maczPdfMacTokenHandler.compute_mac   s3    99FMMOD$  ""rC   Frh   c                0   | j                  |      \  }}| j                  ||      \  }}| j                  |      }| j                  ||j	                         j                               }	| j                  ||||	      }
t        j                  d|
d      S )Nr   )r   r   )r   r   r   r   authenticated_datar   )	r   r   r   r   untagrm   r   r   ContentInfo)rL   rf   rg   rh   r   rir   rz   r   r   authed_datas              rD   rk   z%PdfMacTokenHandler.build_pdfmac_token  s     ///@(,(<(<-)
%~ ,,^<
)9)9);)@)@)B  
 ,,'!	 - 
 1kJ
 	
rC   
recp_infosc                    d }	 |\  }|j                   }t        |t        j                        st        d      |d   }|t        u s|d   j                  dk7  rt        d      |d   d   }|j                  dk7  rt        d|j                  d	      |d
   j                  }	 t        j                  | j                  |      }|S # t        $ r Y w xY w# t        j                  $ r t        d      w xY w)NzWPDF MAC requires exactly one recipientInfo, which must be of PasswordRecipientInfo typer   rF   r   z_PDF MAC tokens must have their key derivation algorithm explicitly identified as pdfMacWrapKdf.r   r   zPPDF MAC only supports unpadded 256-bit AES key wrapping for key encryption; not .r   )r   wrapped_keyzFailed to unwrap MAC key)chosen
ValueError
isinstancer   r   r>   r   r[   r\   dottedr   aes_key_unwraprJ   InvalidUnwrap)rL   r   r   recpry   kea_objr   r   s           rD   _retrieve_mac_keyz$PdfMacTokenHandler._retrieve_mac_key  s+   	 GT;;D $ 9 9:'0 
 -.$;#k*115GG': 
 12;?>>]*%44;NN3EQH 
 _-44	D,,!\\}G ?  		8 $$ 	D'(BCC	Ds   C #!C 	CCC4attrsencap_contentc                 6   t        | j                        }t        j                  |      }|j	                  t        |             |j                         }	 t        |d      }|j                  |k7  rt        d      y # t        t        f$ r t        d      w xY w)Nrz   zMValue of messageDigest attribute does not match hash of encapsulated content.zcMessage digest not found in authenticated attributes, or multiple messageDigest attributes present.)r   rK   r   ri   r   r   rj   r   r[   r>   r   r   )rL   r   r   r   mdrz   claimed_message_digests          rD   _validate_message_digestz+PdfMacTokenHandler._validate_message_digestD  s     -T->->?[[!
		%&'	%>'&" &,,>+,  ?
 *+DE 	'= 	s   &A= =Bc                     |d   }t        |       	 t        |d |d   |d          |d   d   }| j                  ||       y # t        $ r}t        d|j                  z         |d }~ww xY w)	Nr   rX   rW   )claimed_signature_algorithm_objclaimed_digest_algorithm_objclaimed_mac_algorithm_objz%CMS alg protection validation error: r   r   )r   )_validate_content_type_attrr!   r   r>   failure_messager   )rL   rT   r   eint_info_objs        rD   _validate_auth_attrsz'PdfMacTokenHandler._validate_auth_attrsZ  s    |,
 	$J/
	)04-67I-J*3O*D	 !!56yA%%j%M + 	'7!:K:KK	s   A 	A*A%%A*c                    |d   }|t         urt        d      |d   }|d   }| j                  |      }| j                  ||j	                         j                               }t        ||d   j                        st        d      	 | j                  |       |d	   d
   j                  }|dk7  rt        d      |d	   d   j                  S # t        $ r}t        d|j                  z         |d }~ww xY w)Nunauth_attrsz5PDF MAC tokens cannot have unauthenticated attributesr   r   )r   r   zPDF MAC token has invalid MACzCMS structural error: r   r|   r}   z_The content type of the encapsulated content in a PDF MAC token must be id-pdfMacIntegrityInfo.r   )r   r>   r   r   r   rm   r   r[   r   r   r   parsed)	rL   rT   r   r   r   r   computed_macr   eci_cts	            rD   #_validate_and_extract_encap_contentz6PdfMacTokenHandler._validate_and_extract_encap_contentq  s+    !0t#'G  |,
)23D)E
((4''!1!1!3!8!8!: ( 
 lIe,<,C,CD'(GHH	%%i0 /0@GG--'8  -.y9@@@ " 	'(1+<+<<	s   C 	C4C//C4c                @    | j                  |      }t        |||       y rH   )r    _validate_pdf_mac_integrity_info)rL   rT   rf   rg   r   s        rD   validate_pdfmac_token_cmsz,PdfMacTokenHandler.validate_pdfmac_token_cms  s$     @@K(?,<	
rC   N)(r?   r@   rA   __doc__r   r   r   rM   classmethodr   strrS   r/   r   r   rb   boolintrp   rQ   r   r   r   r   r   r   r   r   r   r   rk   RecipientInfosr   r   r   r   r   r*   r   r   rB   rC   rD   r+   r+   N   sx   	 'S&&X'>?N) ?"'?38?HK? ?  '6
"
 
 ((	

 s^
 
@'T 'c ' 
/"'
/38
/	
/ 
/
 
3;L;L 
&::	uc'''	(::-$-8@-	ue|	-$
))
 
 %%	

 
 
		
4#5 #u # # 
 
 #5/	

 
 

6$C,>,> $5 $L&&7;7O7O,Nc.C.C N.&A..&A	&AP
 ((
 	

 #5/
rC   r+   int_inforf   rg   c                     | d   j                   }||k7  rt        d      | d   }||t        urt        d      y |j                   }|t        d      ||k7  rt        d      y )Nr   z;Document digest does not match value in PdfMacIntegrityInforg   z;PdfMacIntegrityInfo contains an unexpected signature digestz6Could not find signature digest in PdfMacIntegrityInfoz<Signature digest does not match value in PdfMacIntegrityInfo)r[   r>   r   )r   rf   rg   claimed_data_digestsig_digest_objclaimed_signature_digests         rD   r   r     s    
 #=188o-#I
 	
 01N%'M  &
 $2#8#8 #+'H  $'77'N  8rC   c                     	 t        | d      }|j                  dk7  rt        d|j                        y # t        t
        f$ r t        d      w xY w)Nr|   r}   zRThe content type attribute of a PDF MAC token must be id-pdfMacIntegrityInfo, not z`Content type not found in authenticated attributes, or multiple content-type attributes present.)r   r[   r>   r   r   r   )r   r|   s     rD   r   r     st    
0^L"::'//;/B/B.EG  ;
 &'@A 
#8
 	

s	   36 Ac                    	 | j                  d      }t        |t        j                        st        d      t        |      dk(  r(|\  }}}}d|z  dz   }|dk(  r||z   |k(  r|||z   |z   k(  ry t        d      # t        $ r d }Y sw xY w)N
/ByteRangez(No sensible /ByteRange found in AuthCode   r#   r   z;PDF MAC token must have /ByteRange covering the entire file)raw_getKeyErrorr   r   ArrayObjectr>   rl   )	pdf_dictfile_lenpayload_len
byte_rangeo1l1o2l2value_lit_lens	            rD   _validate_byte_ranger     s    %%l3
 j'"5"56#$NOO
:!#BBK!+!G]"b(BGm33
E !  
s   A9 9BBac_dictrd   c                 H   	 | j                  d      j                  }t
        j                  j                  |      }t        |      }t        |j                               }||k7  rt	        d| d| d      t        | ||       |S # t        t        f$ r t	        d      w xY w)N/MACz'Failed to retrieve standalone MAC valuez<Standalone MACs must not have trailing CMS data: payload is z bytes long, but token is z bytes.)r   original_bytesr   AttributeErrorr>   r   r   loadrl   rm   r   )r   r   	mac_bytesmac_cir   	token_lens         rD   _extract_standalone_macr    s    OOOF+::	 __!!),Fi.KFKKM"Ii#%&@ L
 	
 (K8M! n% O#$MNNOs   B B!c                    	 t        |       }t        j                  j                  |      }t        |      }t        | ||       d }|d   j                  dk(  r|d   }t        |d         dk(  r|d   d   }|t        d      	 t        |d	   d
      }||d   j                  fS # t        t        t        j                  f$ r t        d      w xY w# t        t        f$ r t        d      w xY w)Nz%Failed to retrieve signature contentsr|   signed_datar   signer_infosr)   r   zQSignature dictionary must contain a SignedData message with exactly 1 signerInfo.unsigned_attrspdf_mac_dataz;Signature must have exactly 1 pdfMacData unsigned attribute	signature)r"   r   r  r   PdfReadErrorr>   r   r   r  rl   r   r[   r   r   r   )sig_dictr   	sig_bytessig_cir   signer_infosdr  s           rD   _extract_mac_in_sigr    s   M$X.	 __!!),Fi.K8[9Kn$$5Ir.!"a'^,Q/K#)
 	


*()>
 ;{+22229 nd&7&78 M#$KLLM. &'@A 
#I
 	

s   B$ C $*CC,readerrU   handler_clsc                    	 | j                   j                  d      }t        |t        j
                        rt        d      t        |t        j                        st        d      d}d}	 |j                  d      }t        |t        j                        r|dk(  rd}n|dk(  rd}| j                  j                  d	t        j                        }|rt        ||      }|d
   }	d }
ni|r\	 |j                  d      }|j!                         }t        |t        j                        st        d      t#        ||      \  }}
|d
   }	nt        d      |d   j$                  dk7  rt        d      | j&                  }|J |d   }|d   d   j$                  j)                         }t+        | j                  |	|      \  }}|
@t-        j.                  t1        |            }|j3                  |
       |j5                         }nd }	 |j7                         }|j=                  |j?                         |||      jA                  |||       y # t        $ r d }Y 8w xY w# t        $ r Y w xY w# t        j                  $ r t        d      t        $ r t        d      w xY w# t8        j:                  $ r}t        d      |d }~ww xY w)N	/AuthCodez&AuthCode dictionary cannot be indirectz$Failed to locate AuthCode dictionaryF/MACLocation/StandaloneTz/AttachedToSigr   r   z
/SigObjRefz7Value of /SigObjRef entry must be an indirect referencez"/AttachedToSig requires /SigObjRefz)/SigObjRef does not point to a dictionaryz Failed to locate MAC in documentr|   r   z0MAC tokens must be of CMS type AuthenticatedDatar   rX   rF   )r   rK   zError retrieving salt)rN   rO   rT   rU   )rT   rf   rg   )!trailer_viewr   r   r   r   IndirectObjectr>   DictionaryObject
NameObjectstreamseekosSEEK_ENDr  get_value_as_referenceIndirectObjectExpected
get_objectr  r[   security_handlerlowerr   r   ri   r   r   rj   get_kdf_saltr   r  rb   get_file_encryption_keyr   )r  rU   r  r   is_standaloneis_in_signaturemac_locationr   r  r   signature_valuesig_refr  shrT   rK   _rf   sig_mdrg   rt   r   s                         rD   r,   r,   &  s   
%%--k: '7112#$LMMgw778#$JKKMO~6lG$6$67}, $!11"& }}!!!R[[1H((;\*
		N44\BG %%'(G$<$<=';  #6h"Il+
#$FGGn$$(<<#>
 	
 
	 	 B>>y!I/0=DDJJLL**<A "7EFo&!??,D  668	  
  ')   U  "   -- 	'I   	N'(LMM	NB  D#$;<!CDsG   I ,:I )I) J II	I&%I&)2JK1J==Kc                        e Zd Z fdZ xZS )StandalonePdfMacc                V    t         |   t        d      |       t        d      | d<   y )Nr   )data_keybytes_reservedr  r  )superrM   r&   )rL   r5  	__class__s     rD   rM   zStandalonePdfMac.__init__  s0    f%n 	 	
  (6^rC   )r?   r@   rA   rM   __classcell__)r7  s   @rD   r2  r2  ~  s    7 7rC   r2  r7   wrK   c                    | j                  |      }|j                  d      }t        d|z        }| j                  t	        d      |       |j                  | |j                  |||      }t        |      \  }	}
|j                  |	j                  d       }|	j                  |
|	       t        j                  ||
      S )
N)rK   F)rc   r#   )r5  r  )rK   in_place
chunk_sizeoutput)rf   rg   )cms_data)_init_mac_handlerrp   r2  set_custom_trailer_entryr&   fillrK   nextrk   rf   fill_with_cmsr   finalise_output)r9  rK   r;  r=  r<  handlertok_sizemac_dict
cms_writerprepared_br_digest
res_outputpdfmac_tokens               rD   r-   r-     s     #$"5"5<"5"PG++!& , H  q8|<Hx4h? 	 ))  J &**%5"
--*:: . L $$Z,$G
33rC   )Jr   r   r   r   typingr   r   r   r   r   r	   
asn1cryptor
   r   r   asn1crypto.corer   cryptography.hazmat.primitivesr   r   "cryptography.hazmat.primitives.kdfr   pyhanko.pdf_utilsr   r   sign.generalr   r   r   r   r   r   r   r   sign.signers.pdf_byteranger   r   sign.validation.errorsr   r    sign.validation.generic_cmsr!   sign.validation.pdf_embeddedr"   
extensionsr$   r%   r&   r  r'   writerr(   _iso32004_asn1r*   __all__ALWAYSr.   	frozensetr/   r>   r+   r   r   r   r   r  r   r  r  r   r,   r2  DEFAULT_CHUNK_SIZEr-   rB   rC   rD   <module>r^     s   	   > > ' '   @ @ 3 +	 	 	 I < D  " & /    )!!!&)1'.. 	
	1 	V
 V
r
! uo:
 0%%__03uS__e5K/L 3H #2,>UU3U ()Up7) 7 !&& 4 4 4rC   