
    ;)diM                    r   d dl Z d dlmZ d dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
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 d dl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$Z$d dl%m&Z& dZ'dZ(dZ)d Z*dZ+dZ,dZ-dZ.dZ/dZ0de1de2fdZ3de1de1fdZ4de1de1fdZ5	 ddede6de6fdZ7dede8dz  d edz  d!efd"Z9d#ej:        de8fd$Z;d%e2d&e8dz  de8fd'Z<dedej=        fd(Z>dedej=        fd)Z?dedej@        fd*ZAd+e1dejB        ej=        z  fd,ZCd+e1dejD        ej@        z  fd-ZEdedejD        ej@        z  fd.ZFe G d/ d0                      ZGd1ejD        deGfd2ZHd3e2d4e2d5e2de1fd6ZId%e2deJe         de8dz  d7e6d8e6d9edz  d:eJe         d;eJe         d<efd=ZKdeJe         de8dz  d8e6d:eJe         d>eJe         d<efd?ZLdeJe         de8dz  d7e6d8e6d9edz  d:eJe         d;eJe         d<efd@ZMdAe jN        dBe1deJe         fdCZOd;eJe         d:eJe         dBe1de1fdDZPdEeJe         dBe1de1fdFZQdGe1dHeGd;e1de1fdIZRdGe1d#e2dJe1dKe1de1f
dLZSd%e2d8e6d9edz  ded<ef
dMZTded<efdNZUdOe1dPe2de1dz  fdQZVd8e6d9edz  ded<efdRZWd%e8dedSefdTZXdAe jN        deJe         fdUZYdV ZZdW Z[d<efdXZ\dede1fdYZ]dede8fdZZ^d[ Z_ded\e2d]efd^Z`g d_Za ebea          d`k    sJ ddbe2de2fdcZcddZddeZedfZfdgZgdhe2die2dje2de1fdkZhdledmedne2dedoe2dpe6fdqZidledmedne2dedpe6f
drZjddte1due2fdvZkdededwe2doe2de6dxefdyZldededwe2doe2de6dzefd{Zmd| Zndmee8z  dz  dlee8z  dz  fd}Zo G d~ de$jp        jq                  Zq ejr        eqd esddgd          de$jt         d          d             Zueuv                    d           ejw        dd ejx        d          dd           ejw        dd ejy                    d           ejw        d ejx        d          d           ejz        d! ejx        d                    d                                                             Z{euv                    d           ejw        dd ej|        ddg          dd           ejw        dd ej|        g d          dd           ejz        d ejy                              d                                                 Z}euv                    d           ejw        dd ej|        ddg          dd           ejw        dd ejx        d          e!ddd           ejw        dd ejy                    d           ejw        dddd           ejw        ddd           ejw        d ejx        d          dd           ejw        d ejx        d          e!dd           ejw        d ejx        d          e!ddd           ejz        d< ejx        d                    d                                                                                                                         Z~euv                    d           ejw        dd ej|        ddg          dd           ejw        ddd           ejw        dd ejx        d          d           ejw        dd ejx        d          d           ejz        d< ejx        d                    d                                                                         Zeuv                    d           ejw        dd ej|        ddg          dd           ejw        dd ejx        d          dd           ejz        d ejx        ddæ                    dĄ                                                 Zeuv                    ddƦ           ejw        dd ejx        d          dd           ejw        dd ejy                    ddǬ          dȄ                                     Zeuv                    dɦ           ejw        dd ejx        d          dd           ejw        dd ejy                    ddǬ          dʄ                                     Zeuv                    d˦           ejz        d< ejx        d                    d̄                         Zeuv                    dͦ           ejw        dd ejx        d          ddά           ejw        dde2d`dѬ           ejz        d ejx        ddæ                    dӄ                                                 Zeuv                    dԦ           ejw        dde2d`dѬ           ejz        d ejx        ddæ                    d\e2defdׄ                                    Zeuv                    dئ           ejw        dd ejx        d          dd٬           ejw        dd ejx        ddæ          ddڬ           ejw        dde$jp                                        ddܬ           ejw        de$jp                                        dadެ           ejw        ddddᬫ           ejz        d ejx        d                    d                                                                                     Zeuv                    d           ejw        dd ejx        d          dd٬           ejw        dd ejx        ddæ          dd嬎           ejw        dde$jp                                        dd           ejw        de$jp                                        dadެ           ejw        dddd笫           ejz        d ejx        d                    d                                                                                     ZddeJe8         dz  fdZd Zedk    r e             dS dS )    N)	dataclass)IO)
exceptions)default_backend)hashes)serialization)ecpaddingrsautils)Cipher
algorithmsmodes)int_to_bytes)OptionEatAll)log)check_deprecated_py_suffix               i  source	chunk_lenc                 \      fdt          dt                               D             S )z7Returns an iterator over 'chunk_len' chunks of 'source'c              3   2   K   | ]}||z            V  d S N ).0ir   r   s     Y/var/www/menimich/repos/protonApp/venv/lib/python3.11/site-packages/espsecure/__init__.py	<genexpr>zget_chunks.<locals>.<genexpr>5   s1      PP!F1q9}$%PPPPPP    r   )rangelen)r   r   s   ``r!   
get_chunksr&   3   s3    PPPPPuQFY/O/OPPPPr#   returnc                     t          |           dz  dk    sJ dt          |           dz  z  }t          j        d|z   gt          j        d|z   |           R  S )z+Endian-swap each word in 'source' bitstring   r   I<>)r%   structpackunpackr   wordss     r!   endian_swap_wordsr2   8   s^    v;;?a3v;;!#$E;sU{HV]3;%G%GHHHHr#   c           	          t          |           dz  dk    sJ dt          |           dz  z  }t          j        |gt          t          j        ||                     R  S )z1Swap the order of the words in 'source' bitstringr)   r   r*   )r%   r-   r.   reversedr/   r0   s     r!   swap_word_orderr5   ?   s^    v;;?a3v;;!#$E;uFxeV(D(DEEFFFFr#   Fkeyfileis_flash_encryption_keyaes_xtsc                    |                                  }t          |          dvr%t          j        dt          |           d          |ru|r:t          |          dvr(t          j        dt          |          dz   d          n9t          |          dvr(t          j        d	t          |          dz   d
          t          |          dk    r$t	          |          }t          j        d           nt          |          dk    r7||dd         z   }t          |          dk    sJ t          j        d           n<t          |          dk    rt          j        d           nt          j        d           |S )a
  Load a 128/256/512-bit key, similar to stored in efuse, from a file

    128-bit keys will be extended to 256-bit using the SHA256 of the key
    192-bit keys will be extended to 256-bit using the same algorithm used
    by hardware if 3/4 Coding Scheme is set.
    )          @   z Key file contains wrong length (z# bytes), 16, 24, 32 or 64 expected.)r:   r<   r=   zBAES_XTS supports only 128, 256, and 512-bit keys. Provided key is    z bits.)r;   r<   z:ESP32 supports only 192 and 256-bit keys. Provided key is z% bits. Use --aes_xts for other chips.r:   zUsing 128-bit key (extended).r;   r<   zUsing 192-bit key (extended).zUsing 256-bit key.zUsing 512-bit key.)readr%   esptool
FatalError_sha256_digestr   print)r6   r7   r8   keys       r!   _load_hardware_keyrE   F   s    ,,..C
3xx''' )s3xx ) ) )
 
 	
   	3xx|++(<'*3xx!|< < <   , 3xxx''(K3xx!|K K K   3xx2~~S!!	12222	SRC"Io3xx2~~~~	12222	SR	&''''	&'''Jr#   outputiv_fileimagec                 X   t          | |           t          ||           t          ||           |*t          j        d           |                    d          }nt	          j        d          }|                                }|                    d           t          j        	                    |          }|j
        rBt          |          dz  dk    r,t          |          t          |          dz  z
  }|d|         }t          |          dz  dk    r|ddt          |          dz  z
  z  z  }||z   }t          | d          }	t                      }
t          t          j        |	          t#          j                    |
          }|                                }t)          j                    }t-          |d	          D ]^}|ddd
         }|                    |          }|ddd
         }t-          |d          D ] }|                    |ddd
                    !_|-t          j                            |j                  d         dz   }t7          |d          5 }|                    |           t-          |                                d          D ] }|                    |ddd
                    !|                    dd|                                z
  z             |                    |           ddd           n# 1 swxY w Y   t          j        d| d           dS )zCalculate the digest of a bootloader image, in the same way the hardware
    secure boot engine would do so. Can be used with a pre-loaded key to update a
    secure bootloader.Nz*--iv argument is for TESTING PURPOSES ONLY   r   r<      Fbackendr:   r)   z-digest-0x0000.binwbr   zDigest + image written to "") _check_output_is_not_inputr   warningr?   osurandomseekr@   	bin_imageESP32FirmwareImageappend_digestr%   rE   r   r   r   AESr   ECB	encryptorhashlibsha512r&   updatepathsplitextnameopenwritedigesttellrC   )r6   rF   rG   rH   ivplaintext_imagefw_imagenew_len	plaintextrD   rM   cipherr[   rd   blockcipher_blockfwords                     r!   digest_secure_bootloaderrp   p   sP    w///uf---w///@AAA\\#Z__jjllO	JJqMMM  33E::H 8#%++ /**c/.B.BS.HIG-hwh7O ?c!Q&&7cS-A-AC-G&HII_$I We
,
,CGJN3''gFFFF  ""I^FIr** ' 'ddd ''..#DDbD)a00 	' 	'EMM%"+&&&&	' ~!!%*--a03GG	fd		 !q	v}}22 	  	 DGGD2J	6AFFHH,-...	   ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! I5F55566666s    BLLLcurve_idc                    | t           j        t           j        t           j        fvrt	          d|  d          t          j         |                       }|                    t          j        j	        t          j
        j        t          j                              }t          |d          5 }|                    |           d d d            d S # 1 swxY w Y   d S )NzUnsupported curve: z2, only NIST192p, NIST256p, NIST384p are supported.encodingformatencryption_algorithmrO   )r	   	SECP192R1	SECP256R1	SECP384R1
ValueErrorgenerate_private_keyprivate_bytesr   EncodingPEMPrivateFormatTraditionalOpenSSLNoEncryptionrb   rc   )rq   r6   private_keypemrn   s        r!   _generate_ecdsa_signing_keyr      s   blBLAAA?( ? ? ?
 
 	

 )((**55K

#
#'+*=*799 $  C 
gt		 	                 s   ,CCCversionschemec                 V   t           j                            |          rt          j        d| d          | dk    rS||dk    r|t          j        d          	 t          t          j        |           t          j	        d| d           d S | dk    r|d	k    s|	 t          j        d
dt                                                    t          j        j        t          j        j        t          j                              }t)          |d          5 }|                    |           d d d            n# 1 swxY w Y   t          j	        d| d           d S |dk    r5	 t          t          j        |           t          j	        d| d           d S |dk    r5	 t          t          j        |           t          j	        d| d           d S |dk    r5	 t          t          j        |           t          j	        d| d           d S t          j        d| d          d S )NzERROR: Key file z already exists.1ecdsa256z!ERROR: V1 only supports ECDSA256.z5ECDSA NIST256p private key in PEM format written to "".2rsa3072i     )public_exponentkey_sizerM   rs   rO   z/RSA 3072 private key in PEM format written to "ecdsa192z5ECDSA NIST192p private key in PEM format written to "ecdsa384z5ECDSA NIST384p private key in PEM format written to "z"ERROR: Unsupported signing scheme .)rS   r_   existsr@   rA   r   r	   rx   r   rC   r   r{   r   r|   r   r}   r~   r   r   r   rb   rc   rw   ry   )r   r   r6   r   rn   s        r!   generate_signing_keyr      s   	w~~g O !MG!M!M!MNNN#~~##(:()LMMM	 	$BL':::	U'UUUVVVVV	CY&.P2 %o>O>O  m&/3$2E%2%?%A%A     gt$$ %$$$% % % % % % % % % % % % % % %ISSSSTTTTTz!!Q'g>>>ISSSS     z!!Q'g>>>ISSSS     z!!Q'g>>>ISSSS     $%S&%S%S%STTTA 
s   D;;D?D?c                 R   	 t          j        |                                 dt                                }n"# t          $ r t          j        d          w xY wt          |j        t          j
        t          j        z  t          j        z            st          j        d          |S )zLoad ECDSA signing keyNpasswordrM   zLIncorrect ECDSA private key specified. Please check algorithm and/or format.z3Supports NIST192p, NIST256p and NIST384p keys only.)r   load_pem_private_keyr?   r   rz   r@   rA   
isinstancecurver	   rw   rx   ry   r6   sks     r!   load_ecdsa_signing_keyr      s    
/LLNNT?3D3D
 
 
  
 
 
 4
 
 	


 bhr| ;bl JKK X !VWWWIs	   58 Ac                     t          |           }t          |j        t          j                  st          j        d          |S )z.Load ECDSA signing key for Secure Boot V1 onlysSigning key uses incorrect curve. ESP32 Secure Boot only supports NIST256p (openssl calls this curve 'prime256v1').)r   r   r   r	   rx   r@   rA   r   s     r!   _load_ecdsa_signing_keyr     sG    		(	(Bbh-- 
 @
 
 	
 Ir#   c                    	 t          j        |                                 t                                }n"# t          $ r t          j        d          w xY wt          |j        t          j
                  st          j        d          |S )z0Load ECDSA verifying key for Secure Boot V1 onlyrL   zKIncorrect ECDSA public key specified. Please check algorithm and/or format.r   )r   load_pem_public_keyr?   r   rz   r@   rA   r   r   r	   rx   )r6   vks     r!   _load_ecdsa_verifying_keyr     s    
.LLNNO$5$5
 
 
  
 
 
 4
 
 	


 bh-- 
 @
 
 	
 Is	   47 Akeydatac                    t          j        | dt                                }t          |t          j                  r*|j        dk    rt          j        d|j         d          |S t          |t          j
                  rOt          |j        t          j        t          j        z  t          j        z            st          j        d          |S t          j        d          )ze
    Load Secure Boot V2 signing key

    can be rsa.RSAPrivateKey or ec.EllipticCurvePrivateKey
    Nr   r   Key file has length - bits. Secure boot v2 only supports RSA-3072.Key file uses incorrect curve. Secure Boot V2 + ECDSA only supports NIST192p, NIST256p, NIST384p (aka prime192v1 / secp192r1, prime256v1 / secp256r1, secp384r1).z+Unsupported signing key for Secure Boot V2.)r   r   r   r   r   RSAPrivateKeyr   r@   rA   r	   EllipticCurvePrivateKeyr   rw   rx   ry   )r   r   s     r!   _load_sbv2_signing_keyr   !  s     
	+$(9(9
 
 
B "c'(( ;$$%r{ % % %   	"b011 "(BL2<$?",$NOO 	$6  
 	

J
K
KKr#   c                    t          j        | t                                }t          |t          j                  r*|j        dk    rt          j        d|j         d          |S t          |t          j
                  rOt          |j        t          j        t          j        z  t          j        z            st          j        d          |S t          j        d          )z^
    Load Secure Boot V2 public key, can be rsa.RSAPublicKey or ec.EllipticCurvePublicKey
    rL   r   r   r   r   z*Unsupported public key for Secure Boot V2.)r   r   r   r   r   RSAPublicKeyr   r@   rA   r	   EllipticCurvePublicKeyr   rw   rx   ry   )r   r   s     r!   _load_sbv2_pub_keyr   ?  s     
	*7O<M<M	N	N	NB"c&'' ;$$%r{ % % %   	"b/00 "(BL2<$?",$NOO 	$6  
 	

I
J
JJr#   c                     |                                  }d|v sd|v sd|v r!t          |                                          S d|v rt          |          }nt	          j        d          |S )Ns   -BEGIN RSA PRIVATE KEY   -BEGIN EC PRIVATE KEYs   -BEGIN PRIVATE KEY   -BEGIN PUBLIC KEYz_Verification key does not appear to be an RSA Private or Public key in PEM format. Unsupported.)r?   r   
public_keyr   r@   rA   )r6   key_datar   s      r!   _get_sbv2_pub_keyr   W  s    ||~~H!X--#x// H,,%h//::<<<		)	))) 5
 
 	
 Ir#   c                   8    e Zd ZU eed<   eed<   eed<   eed<   dS )
PrimitivesnemrinvN)__name__
__module____qualname__int__annotations__r   r#   r!   r   r   i  s4         
FFF
FFF
FFF
IIIIIr#   r   r   c                     t          dddd          }|                                 }|j        |_        |j        |_        t	          j        |j        d           |_        d| j        dz  z  }||j        z  |_        |S )Nr   l        r   r   )	r   public_numbersr   r   r   _modinvr   r   r   )r   
primitivesnumbersrrs       r!   _get_sbv2_rsa_primitivesr   q  sx    Aq!Q''J''))G9JL9JL K
g666JL	
z"Q&	'B:<'JOr#   ab	curve_lenc                     t          |dz            }t          | |          ddd         t          ||          ddd         z   }t          |          dv sJ |S )z
    Given two numbers (curve coordinates or (r,s) signature), write them out as a
    little-endian byte sequence suitable for micro-ecc
    "native little endian" mode
    r>   NrN   )0   r=   `   )r   r   r%   )r   r   r   byte_lenabs        r!   _microecc_formatr     se     9q=!!HQ))$$B$/,q(2K2KDDbD2QQBr77l""""Ir#   append_signatureshsm
hsm_configpub_key	signaturedatafilec	           
          |r|D ]}	t          |	|           t          ||           | dk    rt          ||||||          S | dk    rt          ||||||||          S d S Nr   r   )rQ   sign_secure_boot_v1sign_secure_boot_v2)
r   r6   rF   r   r   r   r   r   r   files
             r!   	sign_datar     s      5 	5 	5D&tV4444x000#~~"7FC)XVVV	C"	
 	
 		
 
r#   
signaturesc                 0   |                                 }|rt          j        d          |rt          j        d           t          |          dk    rt          j        d          |d                                          }t                              |dd         d          }t                              |dd         d          }	t          j	        ||	          }
t          |d                   }nt          |           dk    rt          j        d          t          | d                   }|                    |t          j        t          j                    d	
                    }
|                                }|                    |
|t          j        t          j                                         t          j        |
          \  }}	|                    dd          }|	                    dd          }||z   }
|Et*          j                            |          t*          j                            |j                  k    r*|                                 t5          |j        d          }n%t5          |d          }|                    |           |                    t9          j        dd                     |                    |
           |                                 t          j        dt          |           d|j         d           dS )z]
    Sign a data file with a ECDSA private key, append binary signature to file contents
    zXSecure Boot V1 does not support signing using an external Hardware Security Module (HSM)"Pre-calculated signatures found...r   z-Secure Boot V1 only supports one signing key.r   Nr<   bigT)deterministic_signing	byteorderr   rO   r*   Signed  bytes of data from "r   )r?   r@   rA   r   rC   r%   r   
from_bytesr   encode_dss_signaturer   r   signr	   ECDSAr   SHA256r   verifydecode_dss_signatureto_bytesrS   r_   abspathra   closerb   rc   r-   r.   )r6   rF   r   r   r   r   binary_contentraw_signaturersr   r   r   r_bytess_bytesoutfiles                   r!   r   r     s    ]]__N
 
 6
 
 	

  	6777w<<!$%TUUU"1**,,NN="-u55NN=-u55.q!44	&wqz22w<<!$%TUUU$WQZ00 GGBHV]__DQQQ
 
	 ]]__ II>28FMOO#<#<  
 %i00DAqjjuj--Gjjuj--G'!I~00BGOO5 5   	x}d++vt$$n%%%MMC   MM)MMOOOISN++SS(-SSSTTTTTr#   c           	      b   d}|                                 }	d}
d}t          |	          t          z  dk    rV|rt          j        d          t          t          |	          t          z  z
  }t          j        d| d           |	d|z  z  }	n|r|
|k     r#t          |	|
          }|n||z  }|
d	z  }
|
|k     #t          |          t          z  dk    rt          j        d
          |
dk    rt          j        d           nTt          j        |
 d           |
|k    rt          j        d| d          |	dt          |	          t          z
           }	|r|t          j        d          ddl	m
} 	 |                    |          }n*# t          $ r}t          j        d| d          d}~ww xY wt          |          dk    rt          |          }t          ||	          }|r_t          j        d           t          |          }t          |          |k    r(t          j        d| dt          |           d          nt          |           }||
z
  }||k    rt          j        d| d| d          t          j        | d           |rt          |||	          }nt!          | |	          }|t          |          dk    rt          j        d          ||z  }t          |          dk     rJt          |          t          dz  k    r/t          |          t          z  dk    rt          j        d          t          |          t          z  }|dt          t          |          z
  z  z   }t          |          t          k    rt          j        d
          ||                                 |j        }t'          |d          5 }|                    |	|z              ddd           n# 1 swxY w Y   t          j        dt          |	           d|j         d| d           dS )z
    Sign a firmware app image with an RSA private key using RSA-PSS,
    or ECDSA private key using P192 or P256 or P384.

    Write output file with a Secure Boot V2 header appended.
    r   r   r#   zSecure Boot V2 requires the signature block to start from a 4KB aligned sector but the datafile supplied is not sector aligned.zPadding data contents by z5 bytes so signature sector aligns at sector boundary.rK   Nr   z Incorrect signature sector size.zgNo valid signature blocks found. Discarding --append-signature and proceeding to sign the image afresh.zB valid signature block(s) already present in the signature sector.zUp to zU signature blocks are supported (For ESP32-ECO3 only 1 signature block is supported).zDConfig file is required to generate signature using an external HSM."Incorrect HSM config file format ().r   zNumber of public keys (z)) not equal to the number of signatures (zNumber of keys (z() more than the empty signature blocks (z signing key(s) found.z"Signature Block generation failed.z&Incorrect signature sector generation.rO   r   r   z". Signature sector now has z signature blocks.)r?   r%   SECTOR_SIZEr@   rA   r   rC   validate_signature_blockSIG_BLOCK_SIZEespsecure.esp_hsm_signesp_hsm_signread_hsm_config	Exceptionextract_pubkey_from_hsmgenerate_signature_using_hsm7generate_signature_block_using_pre_calculated_signature*generate_signature_block_using_private_keyr   ra   rb   rc   )r6   rF   r   r   r   r   r   r   SIG_BLOCK_MAX_COUNTcontentssig_block_numsignature_sectorpad_by	sig_blockhsm_signconfigr   	key_countempty_signature_blockssignature_blocktotal_sig_blocksrn   s                         r!   r   r     s     }}HM
8}}{"a'' 	)$C   !CMMK$?@FIAF A A A   &((HH	 ?1110=III  QM 111   >1Q66$%GHHHAIY   
 I  + + +    333(L0 L L L     =#h--+"= =>H
 C$V   	211111	Q--j99FF 	Q 	Q 	Q$%O!%O%O%OPPP	Qw<<1-f55G0BB	 	!	6777LL	y>>Y&&$@) @ @-0^^@ @ @   ' LL	0=@))) +y + +&+ + +
 
 	

 I222333  XQw
 

 EWhWW#o"6"6!";"; !EFFF' 	!! !!NQ$666 !!N2a77 !IJJJ+,,> (;%5!6!667 ++ !CDDD ~	fd		 -q	++,,,- - - - - - - - - - - - - - -I	I#h-- 	I 	Ihm 	I 	I$4	I 	I 	I    s*   4F
 

F1F,,F1O44O8;O8r  r  c                 :   dd l m} |                    |           }|                    ||           }|                    ||          }|                    |           t          j                    }|                    |           |	                    d           |gS )Nr   )
r   r   establish_sessionget_privkey_infosign_payloadclose_connectiontempfileTemporaryFilerc   rU   )r  r  r   sessionr   r   temp_signature_files          r!   r  r    s     )(((((##F++G&&w77K  h77I!!!"022i(((Q  r#   c                 D   d}t          | |          D ]\  }}	 t          |          }|                                }t          |t          j                  rt          |          }t          |          }	|                    ||t          j
        t          j        t          j                              d          t          j        t          j                                         t!          ||	|          }
n|                                }t          |j        t&          j                  r,d}t*          }t          j                    }t          |          }nt          |j        t&          j                  r,d}t.          }t          j                    }t          |          }n_t          |j        t&          j                  r,d}t2          }t          j                    }t7          |          }nt9          j        d          |                    ||t'          j        t          j        |                               t?          |j         |j!        |          }t          j"        |          \  }}t?          |||          }tG          ||||          }
n'# tH          j%        $ r t9          j        d          w xY w|
tM          j'        d	tQ          j)        |
          d
z            z  }
|
dz  }
tU          |
          tV          k    rt9          j        d          ||
z  }|S )Nr#   r<   mgfsalt_length        Invalid ECDSA curve instance.z}Signature verification failed: Invalid Signature
The pre-calculated signature has not been signed using the given public key.<I                       Incorrect signature block size.),zipr   r?   r   r   r   rB   r   r   r
   PSSMGF1r   r   r   	Prehashedgenerate_rsa_signature_blockr   r   r	   rw   CURVE_ID_P192rx   CURVE_ID_P256ry   CURVE_ID_P384SHA384_sha384_digestr@   rA   r   r   xyr   generate_ecdsa_signature_blockr   InvalidSignaturer-   r.   zlibcrc32r%   r   )r   r   r  signature_blockssigpkr   	sig_bytesrd   rsa_primitivesr  r   r   rq   	hash_typepubkey_pointr   r   signature_rss                      r!   r  r    s    y'** @, @,R8	*2..J

I*c&677 /'11!9*!E!E!!KGL$A$ArRRROFMOO44	   #?NI# #
 %3355gmR\:: N #I,H &I+H55FFr|<< N #I,H &I+H55FFr|<< N #I,H &I+H55FF!,-LMMM !!vrx	0J0J'K'K    0	79iPP1)<<1/1i@@"@HlL# # * 	 	 	$.  	 	6;tTZ-H-H:-UVVV<'>11$%FGGGO+s   I9J$J8keyfilesc           
         d}| D ]}t          |                                          }t          |t          j                  rt          |          }|                    |t          j        t          j	        t          j                              d          t          j        t          j                                        }t          |                                          }t!          |||          }n|                                                                }	t          |j        t&          j                  r,d}
t*          }t          j                    }t          |          }nt          |	j        t&          j                  r,d}
t.          }t          j                    }t          |          }n_t          |	j        t&          j                  r,d}
t2          }t          j                    }t7          |          }nt9          j        d          |                    |t'          j        t          j        |                              }t?          |	j         |	j!        |
          }t          j"        |          \  }}t?          |||
          }tG          ||||          }|tI          j%        dtM          j'        |          d	z            z  }|d
z  }tQ          |          tR          k    rt9          j        d          ||z  }|S )Nr#   r<   r  r  r   r!  r"  r#  r$  r%  r&  )*r   r?   r   r   r   rB   r   r
   r(  r)  r   r   r   r*  r   r   r+  r   r   r	   rw   r,  rx   r-  ry   r.  r/  r0  r@   rA   r   r   r1  r2  r   r3  r-   r.   r5  r6  r%   r   )r?  r  r7  r6   r   rd   r   r;  r  r   r   rq   r<  r=  r   r   r>  s                    r!   r  r    s     8, 8,,W\\^^<< k3#455 ,	#H--F#((V]__55 "   00 I 6k6L6L6N6NOON:	 OO ",,..==??G++R\:: J	("MOO	'11GM2<88 J	("MOO	'11GM2<88 J	("MOO	'11()HIII $((%/):T:T1U1UVVI+GIwy)LLL-i88DAq+Aq)<<L<, O 	6;tTZ-H-H:-UVVV<'>11$%FGGGO+r#   rd   r;  c                     t          j        dt          t          | t	          |j                  ddd         |j        t	          |j                  ddd         |j        dz  |ddd         	  	        }|S )a  
    Encode in rsa signature block format

    Note: the [::-1] is to byte swap all of the bignum
    values (signatures, coefficients) to little endian
    for use with the RSA peripheral, rather than big endian
    which is conventionally used for RSA.
    z<BBxx32s384sI384sI384sNrN   r$  )	r-   r.   SIG_BLOCK_MAGICSIG_BLOCK_VERSION_RSAr   r   r   r   r   )rd   r;  r   r  s       r!   r+  r+    sy     k ^%&&ttt,^())$$B$/:%$$B$
 
O r#   r=  r>  c           
         |t           t          fv r+t          j        dt          t
          t          | |||          }nJ|t          k    r+t          j        dt          t
          t          | |||          }nt          j
        d          |S )z
    Encode in rsa signature block format

    # block is padded out to the much larger size
    # of the RSA version of this structure
    z<BBBx32sB64s64s1031xz<BBBx48sB96s96s951xzGInvalid ECDSA curve ID detected while generating ECDSA signature block.)r,  r-  r-   r.   rB  SIG_BLOCK_VERSION_ECDSAECDSA_SHA_256r.  ECDSA_SHA_384r@   rA   )rd   rq   r=  r>  r  s        r!   r3  r3  3  s     M=111 +"#	
 	
 
]	"	" +!#	
 	
  U
 
 	
 r#   c                 b    | dk    rt          ||          S | dk    rt          ||||          S d S r   )verify_signature_v1verify_signature_v2r   r   r   r6   r   s        r!   verify_signaturerL  [  sA     #~~"7H555	C"3
GXFFF 
r#   c                 t   |                                  }d|v r8t          j        |dt                                }|                                }nd|v r#t          j        |t                                }nt          |          dk    rt                              |dd         d	          }t                              |dd         d	          }t          j
        ||t          j                              }|                    t                                }nt          j        d
          t          |j        t          j                  st          j        d          |                                 }|dd         }	t!          j        d|dd                   \  }
}|
dk    rt          j        d|
 d          t%          j        dt          |	           d           	 t                              |dd         d	          }t                              |dd         d	          }t)          j        ||          }|                    ||	t          j        t1          j                                         t%          j        d           dS # t4          j        $ r t          j        d          w xY w)zCVerify a previously signed binary image, using the ECDSA public keyr   Nr   r   rL   r=   r<   r   r   ziVerification key does not appear to be an EC key in PEM format or binary EC public key data. Unsupported.zrPublic key uses incorrect curve. ESP32 Secure Boot only supports NIST256p (openssl calls this curve 'prime256v1').r   iI64szSignature block has version z4. This version of espsecure only supports version 0.z
Verifying z bytes of data...zSignature is valid.zSignature is not valid.)r?   r   r   r   r   r   r%   r   r   r	   EllipticCurvePublicNumbersrx   r@   rA   r   r   r-   r/   r   rC   r   r   r   r   r   r   r   r4  )r6   r   r   r   r   r1  r2  r   r   datasig_versionr   r   r   der_signatures                  r!   rI  rI  h  s   ||~~H8++/t_->->
 
 
 ]]__		)	).xARARSSS	X"		NN8CRC=EN::NN8BCC=EN::/1blnnEE(9(9:: 9
 
 	

 bh-- 
 @
 
 	

 ]]__N!C% D#]6>#$$3GHHKa '; ' ' '
 
 	
 I73t99777888	<NN9SbS>UN;;NN9RSS>UN;;21a88
		-rx'@'@AAA	'(((((& < < < !:;;;<s   &B+J $J7image_contentsig_blk_numc           	         t            |t          z  z   }| ||t          z            }t          |          t          k    sJ t          j        d|          \	  }}}}}}}}}t          j        |d d                   }|t          k    }	|	|t          t          fvz  }	|	s	||dz  k    rd S |t          k    rdnd}
t          j        d| d|
 d           |S )	Nz<BBxx32s384sI384sI384sI16xi  r$  RSAr   Signature block z is valid (r   )r   r   r%   r-   r/   r5  r6  rB  rC  rE  r   rC   )rS  rT  offsetsig_blkmagicr   _blk_crccalc_crcis_invalid_blockkey_types              r!   r   r     s    \K.88FFVn%<<=Gw<<>)))) 17$g1 1-E7Aq!Q1g z'%4%.))H/(=?V'WWW 7h&;;;t#888uugHIEEEEEEFFFNr#   c                 	   | rr|t          j        d          ddlm} 	 |                    |          }n*# t
          $ r}t          j        d| d          d}~ww xY wt          |          d         }t          |          }t          |t          j
                  rd}nt          |t          j                  rd}|                                }	t          |	          t          k     st          |	          t          z  dk    rt          j        d          d	}
t!          |          D ]}t#          |	|          }|t%          j        d
| d           .t)          j        d|dd                   \  }}}|t,          k    rL|t.          k    rAt)          j        d|dd                   d         }t1          |	dt                              }n@t)          j        d|dd                   d         }t3          |	dt                              }||k    rt          j        d| d| d          	 t          |t          j
                  rt)          j        d|dd                   \  }}}}}}|                    |ddd         |t7          j        t7          j        t=          j                              d          tA          j!        t=          j                                         nl|tD          k    r"t)          j        d|dd                   \  }}}n,|t.          k    r!t)          j        d|dd                   \  }}}|tF          tH          tJ          fv sJ |tF          k    rd}t=          j                    }nA|tH          k    rd}t=          j                    }n |tJ          k    rd}t=          j&                    }tN          (                    |d|         d          }tN          (                    |||dz           d          }tA          j)        ||          }|                    ||t          j*        tA          j!        |                               t          |t          j
                  rdnd }t%          j        d
| d!| d           d"}
l# tV          j,        $ r t%          j        d
| d#           Y w xY w|
st          j        d$          dS )%zJVerify a previously signed binary image, using the RSA or ECDSA public keyNzCConfig file is required to extract public key from an external HSM.r   r   r   r   r   DInvalid datafile. Data size should be non-zero & a multiple of 4096.FrW  z invalid. Skipping.<BBBxr)   z<48s4   z<32s$   zDSignature block image digest does not match the actual image digest z. Expected r   z<384sI384sI384sI16xrN   r<   r  B64s64s1031x4x16xB96s96s951x4x16xr;   r   littler   rV  r   z1 verification successful using the supplied key (Tz> is not signed by the supplied key. Checking the next block...zJChecked all blocks. Signature could not be verified with the provided key.)-r@   rA   r   r   r   r  r  r   r   r   r   r	   r   r?   r%   r   r$   r   r   rC   r-   r/   rE  rG  r0  rB   r   r
   r(  r)  r   r   r   r*  rF  r,  r-  r.  r/  r   r   r   r   r   r4  )r   r   r6   r   r  r  r   r   r  rS  validrT  rY  r[  r   ecdsa_sha_version
blk_digestrd   r   rq   _pubkey
encoded_rskeylenr<  r   r   r_  s                              r!   rJ  rJ    sT     5$U   	211111	Q--j99FF 	Q 	Q 	Q$%O!%O%O%OPPP	Q *&11!4	7	#	#B"c&''  	B1	2	2  MMOOM
=K''3}+=+=+Kq+P+P R
 
 	
 E011 J J*=+FF?IIIIIJJJ(.gwrr{(K(K%7%---2C}2T2Tvwqt}==a@J#M-K<-$@AAFFvwqt}==a@J#M-K<-$@AAF$L+1L L>HL L L  
6	"c.// &S+1=)7233<, ,(1aIq 		dddOKGL$A$ArRRROFMOO44	    %554:M+WRSS\5 51Hgzz '-774:M*GBCCL5 51Hgz  M=-#PPPPP },,F &II..F &II..F &INN:gvg#6AANN:fvz.A#BHMM!6q!<<			)VRXeoi6P6P-Q-QRRR *2s/? @ @MuugHI2; 2 2%-2 2 2   EE* 	 	 	I-; - - -   H	  
 X
 
 	

 
s(   6 
A AA1I"R'S ?S public_keyfilec                 h   t          ||           | dk    rr	 t          |          }|                                                                }|j                            dd          }|j                            dd          }||z   }no| dk    ri	 t          |                                          }|                                	                    t          j        j        t          j        j                  }|                    |           t!          j        d|j         d|j         d           d S )	Nr   r<   r   r   rt   ru   rP   z" public key extracted to "r   )rQ   r   r   r   r1  r   r2  r   r?   public_bytesr   r}   r~   PublicFormatSubjectPublicKeyInforc   r   rC   ra   )r   r6   rn  r   r   x_bytesy_bytesr   s           r!   extract_public_keyrv  #  s"   w777#~~	 %W--7799 "++B66 "++B66w	C	 $GLLNN33]]__))"+/ -B * 
 
 IR',RR>;NRRRSSSSSr#   c                 x   dd l m} |                    |           }|                    ||           }|                    |           |                    t          j        j        t          j	        j
                  }t          j                    }|                    |           |                    d           |gS )Nr   rp  )r   r   r  
get_pubkeyr  rq  r   r}   r~   rr  rs  r  r  rc   rU   )r  r   r  r   r   temp_pub_key_files         r!   r  r  >  s    ((((((##F++G00J!!!

!
!'+)> "  C !.00C   1r#   c                 z    t          j                    }|                    |            |                                S r   )r\   sha256r^   rd   )rP  rd   s     r!   rB   rB   P  s/    ^F
MM$==??r#   c                 z    t          j                    }|                    |            |                                S r   )r\   sha384r^   rd   )r  rd   s     r!   r0  r0  V  s/    ^F
MM(==??r#   c                    d}|                                  }t          |          t          k     st          |          t          z  dk    rt          j        d          t          |          D ]}t          ||          }|t          j        d| d            dS t          j
        d|dd                   \  }}}|t          k    r>|t          k    r3t          j
        d	|          }t          |dt                              }	n2t          j
        d
|          }t          |dt                              }	|d         |	k    rt          j        d| d          t           |t          z  z   }
||
|
t          z            }|d         t           k    rt          |dd                   }nd|d         t          k    r;|t          k    rt          |dd                   }n0t          |dd                   }nt          j        d| d          t          j        d| dd                    d t%          |          D                                   dS )zg
    Validates the signature block and prints the RSA/ECDSA public key
    digest for valid blocks
    r   r   ra  NrW  z1 absent/invalid. Skipping checking next blocks...rb  r)   z<BBxx48s1164xz<BBxx32s1180xr   zDigest in signature block z  doesn't match the image digest.r   rd  i,  rc     e   z&Unsupported scheme in signature block r   zPublic key digest for block z:  c              3      K   | ]}|d V  	dS )02xNr   )r   cs     r!   r"   z$signature_info_v2.<locals>.<genexpr>  s&      BBq1

BBBBBBr#   )r?   r%   r   r@   rA   r$   r   r   rC   r-   r/   rE  rG  r0  rB   r   rC  join	bytearray)r   r  rS  rT  rY  r[  r   ri  sig_datard   rX  r  
key_digests                r!   signature_info_v2r  ]  s   
 MMOOM
=K''3}+=+=+Kq+P+P R
 
 	
 011 )
 )
*=+FF?I!; ! ! !   FF(.gwrr{(K(K%7%---2C}2T2T}_g>>H#M-K<-$@AAFF}_g>>H#M-K<-$@AAFA;&  $$[ $ $ $  
 n <<!&6N+B"BC	A;///'	"S&(9::JJa[333 M11+Ibf,=>>

+Ibf,=>>

$GGGG   		E; E ExxBBIj,A,ABBBBBE E	
 	
 	
 	
M)
 )
r#   c           	      8   t          |           }t          |t          j                  rkt	          |          }t          j        dt          |j                  d d d         |j	        t          |j
                  d d d         |j        dz            }n|                                }t          |j        t          j                  r
d}t           }nQt          |j        t          j                  r
d}t$          }n(t          |j        t          j                  r	d}t(          }t+          |j        |j        |          }|t(          k    rt          j        d||          }nt          j        d||          }t1          j        |                                          S )	Nz<384sI384sIrN   r$  r  r   r!  z<B96sz<B64s)r   r   r   r   r   r-   r.   r   r   r   r   r   r   r   r	   rw   r,  rx   r-  ry   r.  r   r1  r2  r\   r{  rd   )r6   r   r;  binary_formatr   r   rq   r=  s           r!   _digest_sbv2_public_keyr    s|   "7++J*c.// )1*== )**44R40,--ddd3z)
 
 ++--j&55 	%I$HH
(",77 	%I$HH
(",77 	%I$H'	79iHH}$$"K MM #K M >-((//111r#   c                     t          | |           t          |           }t          |d          5 }t          j        d| j         d| d           |                    |           d d d            d S # 1 swxY w Y   d S )NrO   z"Writing the public key digest of "z" to "r   )rQ   r  rb   r   rC   ra   rc   )r6   rF   public_key_digestrn   s       r!   digest_sbv2_public_keyr    s    w////88	fd		 #q	Uw|UU6UUUVVV	!"""# # # # # # # # # # # # # # # # # #s   6A33A7:A7c                 t    |                                  j                            | j        dz   dz  d          S )N   r>   r   )lengthr   )private_numbersprivate_valuer   r   )r   s    r!   get_ecdsa_signing_key_raw_bytesr    s>    -66aA% 7   r#   rm  digest_filec           	      \   t          | |           t          |           }t          |          }t          j        |                                          }|dk    r
|dd         }|                    |           |dk    rdnd}t          j        d| j	         d| d	|j	         d
           d S )Nr  r   r;   r    z (truncated to 192 bits)zSHA-256 digest of private key "rP   z written to "r   )
rQ   r   r  r\   r{  rd   rc   r   rC   ra   )r6   rm  r  r   r|   resultlen_msgs          r!   digest_private_keyr    s    w444	 	)	)B3B77M^M**1133F}}"fcMMbb'AGI	,', 	, 	, 	, 	,"'	, 	, 	,    r#   (                        r:                  
   	   r>   r        r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r  r  r  r  r  r  r  r:   r  r  r  r  r  r  r  r>   r  r  r  r>   r  r  r  r   r  flash_crypt_configc                 z    d}| dz  dk    r|dz  }| dz  dk    r|dz  }| dz  dk    r|dz  }| dz  dk    r|d	z  }|S )
zReturn bits (in reverse order) that the "key tweak" applies to,
    as determined by the FLASH_CRYPT_CONFIG 4 bit efuse value.
    r   r   l                            ~ r   l                   r)   l	            r>   l    r   )r  tweak_ranges     r!   "_flash_encryption_tweak_range_bitsr    s     KQ1$$N	
 	Q1$$N	
 	Q1$$N	
 	Q1$$N	
 r#   l                        l                         l   p l          ~              ~ rD   rX  r  c                     |dz	  }| t           |z  t          |z  t          z  z  |z  z  } t                              | ddd          S )a=  Apply XOR "tweak" values to the key, derived from flash offset
    'offset'. This matches the ESP32 hardware flash encryption.

    tweak_range is a list of bit indexes to apply the tweak to, as
    generated by _flash_encryption_tweak_range() from the
    FLASH_CRYPT_CONFIG efuse value.

    Return tweaked key
    r  r<   r   F)r  r   signed)mul1mul2	mul2_maskr   r   )rD   rX  r  addrs       r!   _flash_encryption_tweak_keyr    sH     Q;DTD[dTkY67;FFC<<B%<FFFr#   output_file
input_fileflash_addressflash_crypt_conf
do_decryptc                 x   t          |dd          }|dz  dk    rt          j        d|dd          |dk    rt          j        d	           t          |          }t                              |d
d          }t                      }d}	|}
	 |	                    d          }t          |          dk    rdS t          |          dk     rW|rt          j        d          dt          |          z
  }|t          j        |          z   }t          j        d| d           |
dz  dk    s|	It          ||
|          }|	`t          t!          j        |          t%          j                    |          }	|r|	                                n|	                                }n	 |j        j        }|j                            |j        j        |j        j        |j        j        |j                            |          |j        j        |j        j                  }|                    |dk               nF# t>          $ r9 ||	j         _!        |r|	                                n|	                                }Y nw xY w|ddd         }|"                    |          }| #                    |ddd                    |
dz  }
.)a@  
    Perform flash encryption or decryption operation for ESP32.

    This function handles the encryption or decryption of flash data for ESP32 chip.
    It reads data from the input file, processes it in 16-byte blocks, and writes the
    processed data to the output file. The function ensures that the key length is
    either 192 or 256 bits, as required by the ESP32 chip. It also checks that the flash
    address is a multiple of 16.

    Note: This function is specific to the ESP32 chip. For other chips, use the
    --aes_xts flag to call the correct function.
    TFr8   r:   r   Starting flash address #x must be a multiple of 16.z4Setting FLASH_CRYPT_CONF to zero is not recommended.r   )r   r  Nz*Data length is not a multiple of 16 bytes.zNote: Padding with zI bytes of random data (encrypted data must be multiple of 16 bytes long).r<   rL   rN   )$rE   r@   rA   r   rR   r  r   r   r   r?   r%   rS   rT   rC   r  r   r   rY   r   rZ   r[   	decryptor_ctx_backend_libEVP_CipherInit_ex_ffiNULLfrom_buffer
_operationopenssl_assertAttributeError	algorithmrD   r^   rc   )r  r  r  r6   r  r  rD   r  rM   rk   
block_offsrl   pad	block_keyactorress                   r!   !_flash_encryption_operation_esp32r  -  s   ( WdE
:
:
:CrQ RmRRRR
 
 	
 1JKKK45EFFK
..e.
<
<CGFJ6##u::??EZZ"__ W()UVVVs5zz/CBJsOO+EIFc F F F  
 ?a6> 4C[QQI~
y 9 959;;PWXXX
 /9P((***f>N>N>P>PU#j1G!,88
))00;;)
- C **3!84444% U U U ,5F$(2<TF,,...&BRBRBTBTEEE	U dddU##%"+&&&b
m6s   "BH1 1A I43I4c                 L   t                      }t          |dd          }|                                }|dz  dk    rt          j        d|dd          t          |          dz  dk    r%t          j        dt          |           d	          t          |          dk    rt          j        d
          |dz  }d|z  |z   }t          |          dz  }	|	dk    rd|	z
  }	|d|	z  z   }t          |d          }
g }|
D ]}t          j        d|dz            dz   }|dz  }t          |          dk    r%t          j        dt          |           d          t          t          j        |          t          j        |          |          }|r|                                n|                                }|ddd         }|                    |          }|                    |ddd                    d                    |          }|	dk    r|d|	          }|dk    r
||d         }t          |          t          |          |z
  |	z
  k    r;t          j        dt          |          |z
  |	z
   dt          |           d          |                     |           dS )a  
    Apply the AES-XTS algorithm with the hardware addressing scheme used by Espressif

    key = AES-XTS key (32 or 64 bytes)
    flash_address = address in flash to encrypt at. Must be multiple of 16 bytes.
    indata = Data to encrypt/decrypt. Must be multiple of 16 bytes.
    encrypt = True to Encrypt indata, False to decrypt indata.

    Returns a bitstring of the ciphertext or plaintext result.
    Tr  r:   r   r  r  r  zInput data length (z) must be a multiple of 16.z!Input data must be longer than 0.rJ       r#  is               z Length of tweak must be 16, was r   rL   NrN   r#   zLength of input data (z ) should match the output data (r   )r   rE   r?   r@   rA   r%   _split_blocksr-   r.   r   r   rY   r   XTSr  r[   r^   appendr  rc   )r  r  r  r6   r  rM   rD   indatapad_left	pad_rightinblocksoutput_listinblocktweakrk   r[   outblockrF   s                     r!   #_flash_encryption_operation_aes_xtsr    s    G
WdD
9
9
9C__FrQ RmRRRR
 
 	
 6{{R1 J#f++JJJ
 
 	
 6{{a !DEEE t#H F*F Fd"I1}}9$	w*+FVT**HK + +D=5#8::lKu::$%UE

%U%U%UVVV
s++UYu-=-=wOOO*4LF$$&&&&:J:J:L:L	$$B$-##G,,8DDbD>****XXk""F A~~)$1}}		" 6{{c&kkH,y888 =S[[8%;i%G = =-0[[= = =
 
 	

 fr#   r:   text	block_lenc              #      K   t          |           |z  dk    sJ d}|t          |           k     r)| |||z            V  ||z   }|t          |           k     'dS dS )z4Take bytes, split it into chunks of "block_len" eachr   N)r%   )r  r  poss      r!   r  r    sr      t99y A%%%%
C
D		//3y())))Io D		//////r#   addressencrypted_filec                     t          | |           t          ||           |rt          |||| d          S t          |||| |d          S )NTrQ   r  r  r6   rF   r  r  r8   r  s         r!   decrypt_flash_datar    so     w///~v666 
2NGWd
 
 	
 1
 
 	
r#   plaintext_filec                     t          | |           t          ||           |rt          |||| d          S t          |||| |d          S )NFr  r6   rF   r  r  r8   r  s         r!   encrypt_flash_datar    so     w///~v666 
2NGWe
 
 	
 1
 
 	
r#   c                     t           j                            t           j                            |                     t           j                            t           j                            |                    k    S r   )rS   r_   normcasenormpath)p1p2s     r!   	_samefiler    sV    7BG,,R0011RW5E5E
6 6  r#   c                    t          | d|           }t          |d|          }t          |t                    rt          |t                    rt          nt          j        } |||          rt          j        d| d| d          d S )Nra   zThe input "z" and output "z" should not be the same!)getattrr   strr  operatoreqr@   rA   )r  r  r    ocheck_fs        r!   rQ   rQ     s     	
FJ//AV[11A
 &a--U*Q2D2DUii(+Gwq!}} 
 G!GG1GGG
 
 	

 
r#   c                       e Zd ZddddZdS )Group	--aes-xts--flash-crypt-conf--append-signatures)z	--aes_xtsz--flash_crypt_confz--append_signaturesN)r   r   r   DEPRECATED_OPTIONSr   r#   r!   r  r  (  s&         24 r#   r  Tz-hz--helpx   )help_option_namesmax_content_widthespsecure vz, - ESP32 Secure Boot & Flash Encryption tool)clsno_args_is_helpcontext_settingshelpc                  H    t          j        dt          j                    d S )Nr  )r   rC   r@   __version__r   r#   r!   clir  0  s&     I1G/1122222r#   zdigest-secure-bootloaderz	--keyfilez-krbz#256 bit key for secure boot digest.)typerequiredr	  z--outputz-oz$Output file for signed digest image.)r  r	  z--ivzl128 byte IV file. Supply a file for testing purposes only, if not supplied an IV will be randomly generated.)r  c                 *    t          | |||           dS )zTake a bootloader binary image and a secure boot key, and output a combined
    digest+binary suitable for flashing along with the precalculated secure boot key.N)rp   )r6   rF   rf   rH   s       r!   digest_secure_bootloader_clir  ;  s    * Wfb%88888r#   zgenerate-signing-keyz	--versionz-vr   r   z1Version of the secure boot signing scheme to use.)r  defaultr	  z--schemez-s)r   r   r   r   zScheme of secure boot signing.)r  r	  r  c                 (    t          | ||           dS )zYGenerate a private key for signing secure boot images as per the secure boot
    version.N)r   )r   r   r6   s      r!   generate_signing_key_clir  S  s    & &'22222r#   z	sign-dataz3Private key file for signing. Key is in PEM format.)r  r  r  multipler	  zGOutput file for signed digest image. Default is to sign the input file.r   z-azTAppend signature block(s) to already signed image. Not valid for ESP32 and ESP32-C2.)is_flagr	  z--hsmzWUse an external Hardware Security Module to generate signature using PKCS#11 interface.z--hsm-configr   zWConfig file for the external Hardware Security Module to be used to generate signature.z	--pub-keyzPublic key files corresponding to the private key used to generate the pre-calculated signatures. Keys should be in PEM format.)r  r  r  r	  z--signaturezdPre-calculated signatures. Signatures generated using external private keys e.g. keys stored in HSM.)r  r  r  r  r	  c	                 4    t          | ||||||||	  	         dS )z*Sign a data file for use with secure boot.N)r   )	r   r6   rF   r   r   r   r   r   r   s	            r!   sign_data_clir  i  s<    R 
 
 
 
 
r#   zverify-signaturez)Version of the secure boot scheme to use.zUUse an external Hardware Security Module to verify signature using PKCS#11 interface.zUConfig file for the external Hardware Security Module to be used to verify signature.)r  r  r	  zMPublic key file for verification. Can be private or public key in PEM format.c                 ,    t          | ||||           dS )zIVerify a data file previously signed by "sign_data" using the public key.N)rL  rK  s        r!   verify_signature_clir    s     > Wc:wAAAAAr#   zextract-public-keyzJPrivate key file (PEM format) to extract the public verification key from.zpublic-keyfilerO   )lazyc                 (    t          | ||           dS )zUExtract the public verification key for signatures, save it as a raw binary
    file.N)rv  )r   r6   rn  s      r!   extract_public_key_clir    s    & w88888r#   zdigest-rsa-public-key)
deprecatedzOutput file for the digest.c                 &    t          | |           dS )z1Generate an SHA-256 digest of the RSA public key.Nr  r6   rF   s     r!   digest_rsa_public_keyr"        $ 7F+++++r#   zdigest-sbv2-public-keyc                 &    t          | |           dS )z-Generate an SHA-256 digest of the public key.Nr   r!  s     r!   digest_sbv2_public_key_clir%    r#  r#   zsignature-info-v2c                 $    t          |            dS )zGReads the signature block and provides the signature block information.N)r  )r   s    r!   signature_info_v2_clir'  !  s     hr#   zdigest-private-keyz8Private key file (PEM format) to generate a digest from.z--keylenz-lz`Length of private key digest file to generate (in bits). 3/4 Coding Scheme requires 192 bit key.zdigest-filec                 (    t          | ||           dS )z5Generate a SHA-256 digest of the private signing key.N)r  )r6   rm  r  s      r!   digest_private_key_clir)  (  s    & w44444r#   zgenerate-flash-encryption-keyzkey-filekey_filec                     t          j        d|  d|j         d           |                    t	          j        | dz                       dS )zAGenerate a development-use flash encryption key with random data.zWriting z random bits to key file "r   r>   N)r   rC   ra   rc   rS   rT   )rm  r*  s     r!   generate_flash_encryption_keyr,  >  sP     ILLL8=LLLMMMNN2:fk**+++++r#   zdecrypt-flash-datazFile with flash encryption key.zOutput file for plaintext data.z	--addressz0Address offset in flash that file was read from.r  zSOverride FLASH_CRYPT_CONF eFuse value (default is 0xF) (applicable only for ESP32).r  z-xz6Decrypt data using AES-XTS (not applicable for ESP32).zencrypted-filec                 .    t          | |||||           dS )z>Decrypt some data read from encrypted flash (using known key).N)r  r  s         r!   decrypt_flash_data_clir.  N  /    P "2G^    r#   zencrypt-flash-datazOutput file for encrypted data.z3Address offset in flash where file will be flashed.z6Encrypt data using AES-XTS (not applicable for ESP32).zplaintext-filec                 .    t          | |||||           dS )zAEncrypt some data suitable for encrypted flash (using known key).N)r  r  s         r!   encrypt_flash_data_clir1  {  r/  r#   argvc                 p    	 t          |            dS # t          $ r}|j        dk    r Y d}~dS d}~ww xY w)aA  
    Main function for espsecure

    argv - Optional override for default arguments parsing
    (that uses sys.argv), can be a list of custom arguments as strings.
    Arguments and their values need to be added as individual items to the list
    e.g. "--port /dev/ttyUSB1" thus becomes ['--port', '/dev/ttyUSB1'].
    )argsr   N)r  
SystemExitcode)r2  r   s     r!   mainr7    sT       6Q;; ;;;;;s    
505c                     t          t                     	 t                       d S # t          j        $ r6} t          j        d|             t          j        d           Y d } ~ d S d } ~ wt          $ r1} 	 d | j
        D             rt          j        d            #  xY wd } ~ wt          $ r, t          j        d           t          j        d           Y d S w xY w)Nz
A fatal error occurred: r   c                     g | ]}d |v |	S )zCould not deserialize key data.r   )r   args     r!   
<listcomp>z_main.<locals>.<listcomp>  s#    RRR)Jc)Q)Q)Q)Q)Qr#   zNote: This error originates from the cryptography module. It is likely not a problem with espsecure, please make sure you are using a compatible OpenSSL backend.z)KeyboardInterrupt: Run cancelled by user.)r   r   r7  r@   rA   r   errorsysexitrz   r4  KeyboardInterrupt)r   s    r!   _mainr@    s   x(((   	2q22333 	 	 		RRqvRRR 	S   EEEE   	=>>>s8   & C+A&&C4%BBBB5CC__main__)F)r  )r:   r   )configparserdataclassesr   
rich_clickclickr\   r  rS   r-   r=  r  r5  typingr   cryptographyr   cryptography.hazmat.backendsr   cryptography.hazmat.primitivesr   r   )cryptography.hazmat.primitives.asymmetricr	   r
   r   r   &cryptography.hazmat.primitives.ciphersr   r   r   cryptography.utilsr   esptool.cli_utilr   esptool.loggerr   r@   esptool.utilr   rB  rC  rE  rF  rG  r,  r-  r.  r   r   bytesr   r&   r2   r5   boolrE   r  rp   EllipticCurver   r   r   r   r   r   r   r   r   r   r   r   r   r   r   listr   r   r   SectionProxyr  r  r  r+  r3  rL  rI  r   rJ  rv  r  rB   r0  r  r  r  r  r  _FLASH_ENCRYPTION_TWEAK_PATTERNr%   r  r  r  	mul1_maskr  r  r  r  r  r  r  r  rQ   cli_utilr  groupdictr  r  commandoptionFilePathargumentr  Choicer  r  r  r  r"  r%  r'  r)  r,  
AnyIntTyper.  r1  r7  r@  r   r   r#   r!   <module>ra     s       ! ! ! ! ! !       				  



         # # # # # # 8 8 8 8 8 8 1 1 1 1 1 1 8 8 8 8 8 8 M M M M M M M M M M M M L L L L L L L L L L + + + + + + ) ) ) ) ) )        3 3 3 3 3 3      
Qu Q Q Q Q Q
Ie I I I I IGE Ge G G G G AF' ''*.'9=' ' ' 'T?7?7t?7.04i?7@B?7 ?7 ?7 ?7D"*: S    $,U# ,UsTz ,UC ,U ,U ,U ,U^B 2+E     R B,F    r b.G    &LL33L L L L<K K#*:R=V*V K K K K0r c&69R&R    $        )9 j    	 	 	 	 	 	 	 	

"X
 $J
 	

 

 T	
 "X
 Bx
 
 
 
 
<BU"XBU$JBU 
BU "X	BU
 RBU BU BU BU BUJO"XO$JO O 
	O
 T	O "XO BxO O O O Od!%!16!	"X! ! ! !"EBxE"&r(E6;E
E E E EP=2h="'=
= = = =@#-:?
   2%% %05%EJ%
% % % %P
G
G	
G T	
G 	
G
 
G 
G 
G 
G-< -<r -< -< -< -<`E  PT    2o
T o
rDy o
2 o
QS o
 o
 o
 o
dT Tb T" T T T T6L$= $r(    $    6
 6
 6
 6
 6
r.2R .2E .2 .2 .2 .2b#B # # # # #   C b    &# # # $ s*++s2222 3     2 JIN	N	GS G# GC GE G G G G[[[ [ 	[
 [ [ [ [ [|II!#I47IBDIRVI I I IX  #    


 
 	

 
 
 
 
 
2


 
 	

 
 
 
 
 
2  
S4
.03ho
 
 
 
     G"    TT8,<PSTTT
w* 
 
 
	  3 3 3 '((	D			.   :5:<<.T   
	D		
&   jej..///9 9 0/    )($9 #$$	sCj	!	!	<   	EEE	F	F	)   	

---3 3 .-   %$ 3 [	sCj	!	!	<   	D			>   		R	   
	   
   	C
	   	D		
?   	D		
   
D!1!1222  32         z2   	sCj	!	!	4   
   	C
	   	D		
2	   
D!1!1222B B 32     ! :B
 !""	sCj	!	!	<   	D			U    zuz$T'B'B'BCCC9 9 DC   #" 9 $66	D		
2   		&  , ,   76 ,
 %&&	D		
2   		&  , ,   '& ,
  !!
D!1!1222    32 "! 
 !""	D			C   	
   JEJt$$?$?$?@@@5 5 A@   #""5
 ,--	
   
Dt!<!<!<===,# , , , , >=  .-, !""	D			*   	Dt	$	$	$	*   			$	$	&	&	;   			$	$	&	&
	   	A	    zuz$'7'7888  98      #"H !""	D			*   	Dt	$	$	$	*   			$	$	&	&	>   			$	$	&	&
	   	A	    zuz$'7'7888  98      #"H tCy4       , z	EGGGGG r#   