1#!/usr/bin/python 2 3# 4# Copyright 2024, The Android Open Source Project 5# 6# Licensed under the Apache License, Version 2.0 (the "License"); 7# you may not use this file except in compliance with the License. 8# You may obtain a copy of the License at 9# 10# http://www.apache.org/licenses/LICENSE-2.0 11# 12# Unless required by applicable law or agreed to in writing, software 13# distributed under the License is distributed on an "AS IS" BASIS, 14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15# See the License for the specific language governing permissions and 16# limitations under the License. 17# 18 19"""A script to sign nanoapps for testing purpose on tinysys platforms.""" 20 21import argparse 22import ctypes 23import hashlib 24from cryptography.hazmat.primitives import hashes 25from cryptography.hazmat.primitives import serialization 26from cryptography.hazmat.primitives.asymmetric import ec 27from cryptography.hazmat.primitives.asymmetric import utils 28 29 30class HeaderInfo(ctypes.LittleEndianStructure): 31 _fields_ = [ 32 ("magic_number", ctypes.c_uint32), 33 ("header_version", ctypes.c_uint32), 34 ("rollback_info", ctypes.c_uint32), 35 ("binary_length", ctypes.c_uint32), 36 ("flags", ctypes.c_uint64 * 2), 37 ("binary_sha256", ctypes.c_uint8 * 32), 38 ("reserved_chip_id", ctypes.c_uint8 * 32), 39 ("reserved_auth_config", ctypes.c_uint8 * 256), 40 ("reserved_image_config", ctypes.c_uint8 * 256), 41 ] 42 43 44def read_private_key(key_file, password): 45 with open(key_file, "rb") as file: 46 key_bytes = file.read() 47 try: 48 return serialization.load_der_private_key(key_bytes, password=password) 49 except ValueError as e: 50 pass # Not a DER private key 51 52 try: 53 return serialization.load_pem_private_key(key_bytes, password=password) 54 except ValueError: 55 pass # Not a PEM private key 56 raise ValueError("Unable to parse the key file as DER or PEM") 57 58 59def main(): 60 61 parser = argparse.ArgumentParser( 62 description="Sign a binary to be authenticated on tinysys platforms" 63 ) 64 parser.add_argument( 65 "private_key_file", 66 help="The private key (DER or PEM format) used to sign the binary", 67 ) 68 parser.add_argument( 69 "-p", 70 "--password", 71 type=str, 72 help="Optional password encrypting the private key", 73 ) 74 parser.add_argument( 75 "nanoapp", help="The name of the nanoapp binary file to be signed" 76 ) 77 parser.add_argument( 78 "output_path", help="The path where the signed binary should be stored" 79 ) 80 args = parser.parse_args() 81 82 # Load the binary file. 83 binary_data = None 84 with open(args.nanoapp, "rb") as binary_file: 85 binary_data = binary_file.read() 86 87 # Load ECDSA private key. 88 password = args.password.encode() if args.password else None 89 private_key = read_private_key(args.private_key_file, password) 90 91 # Generate a zero-filled header. 92 header = bytearray(0x1000) 93 94 # Fill the public key. 95 public_key_numbers = private_key.public_key().public_numbers() 96 header[0x200:0x220] = public_key_numbers.x.to_bytes(32, "big") 97 header[0x220:0x240] = public_key_numbers.y.to_bytes(32, "big") 98 99 # Fill header_info. 100 sha256_hasher = hashlib.sha256() 101 sha256_hasher.update(binary_data) 102 header_info = HeaderInfo( 103 magic_number=0x45524843, 104 header_version=1, 105 binary_length=len(binary_data), 106 binary_sha256=(ctypes.c_uint8 * 32)(*sha256_hasher.digest()), 107 ) 108 header_info_bytes = bytes(header_info) 109 header[0x400 : 0x400 + len(header_info_bytes)] = header_info_bytes 110 111 # Generate the signature. 112 signature = private_key.sign(header[0x200:], ec.ECDSA(hashes.SHA256())) 113 r, s = utils.decode_dss_signature(signature) 114 r_bytes = r.to_bytes(32, "big") 115 s_bytes = s.to_bytes(32, "big") 116 header[:32] = r_bytes 117 header[32:64] = s_bytes 118 119 with open(f"{args.output_path}/{args.nanoapp}", "wb") as output: 120 output.write(header) 121 output.write(binary_data) 122 123 124if __name__ == "__main__": 125 main() 126