Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 1 | #! /usr/bin/env python3 |
| 2 | # |
| 3 | # Copyright 2017 Linaro Limited |
David Vincze | db32b21 | 2019-04-16 17:43:57 +0200 | [diff] [blame] | 4 | # Copyright (c) 2018-2019, Arm Limited. |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 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 | |
Gabor Kertesz | 33e9b23 | 2018-09-12 15:38:41 +0200 | [diff] [blame] | 18 | from __future__ import print_function |
Oliver Swede | 2144044 | 2018-07-10 09:31:32 +0100 | [diff] [blame] | 19 | import os |
Oliver Swede | 05e5ded | 2018-07-19 16:40:49 +0100 | [diff] [blame] | 20 | import re |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 21 | import argparse |
Gabor Kertesz | 33e9b23 | 2018-09-12 15:38:41 +0200 | [diff] [blame] | 22 | from imgtool_lib import keys |
| 23 | from imgtool_lib import image |
| 24 | from imgtool_lib import version |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 25 | import sys |
Sverteczky, Marcell | 7d069e8 | 2019-07-04 18:17:33 +0200 | [diff] [blame] | 26 | import macro_parser |
Ludovic Barre | 8a77bdd | 2020-03-26 19:53:07 +0100 | [diff] [blame^] | 27 | import fileinput |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 28 | |
Sverteczky, Marcell | 7d069e8 | 2019-07-04 18:17:33 +0200 | [diff] [blame] | 29 | sign_bin_size_re = re.compile(r"^\s*RE_SIGN_BIN_SIZE\s*=\s*(.*)") |
| 30 | image_load_address_re = re.compile(r"^\s*RE_IMAGE_LOAD_ADDRESS\s*=\s*(.*)") |
Oliver Swede | 05e5ded | 2018-07-19 16:40:49 +0100 | [diff] [blame] | 31 | |
Oliver Swede | 2144044 | 2018-07-10 09:31:32 +0100 | [diff] [blame] | 32 | # Returns the last version number if present, or None if not |
| 33 | def get_last_version(path): |
| 34 | if (os.path.isfile(path) == False): # Version file not present |
| 35 | return None |
| 36 | else: # Version file is present, check it has a valid number inside it |
| 37 | with open(path, "r") as oldFile: |
| 38 | fileContents = oldFile.read() |
| 39 | if version.version_re.match(fileContents): # number is valid |
| 40 | return version.decode_version(fileContents) |
| 41 | else: |
| 42 | return None |
| 43 | |
| 44 | def next_version_number(args, defaultVersion, path): |
| 45 | newVersion = None |
David Vincze | d8fbe0e | 2019-08-12 15:58:57 +0200 | [diff] [blame] | 46 | versionProvided = False |
Oliver Swede | 2144044 | 2018-07-10 09:31:32 +0100 | [diff] [blame] | 47 | if (version.compare(args.version, defaultVersion) == 0): # Default version |
| 48 | lastVersion = get_last_version(path) |
| 49 | if (lastVersion is not None): |
| 50 | newVersion = version.increment_build_num(lastVersion) |
| 51 | else: |
| 52 | newVersion = version.increment_build_num(defaultVersion) |
| 53 | else: # Version number has been explicitly provided (not using the default) |
David Vincze | d8fbe0e | 2019-08-12 15:58:57 +0200 | [diff] [blame] | 54 | versionProvided = True |
Oliver Swede | 2144044 | 2018-07-10 09:31:32 +0100 | [diff] [blame] | 55 | newVersion = args.version |
| 56 | versionString = "{a}.{b}.{c}+{d}".format( |
| 57 | a=str(newVersion.major), |
| 58 | b=str(newVersion.minor), |
| 59 | c=str(newVersion.revision), |
| 60 | d=str(newVersion.build) |
| 61 | ) |
David Vincze | d8fbe0e | 2019-08-12 15:58:57 +0200 | [diff] [blame] | 62 | if not versionProvided: |
| 63 | with open(path, "w") as newFile: |
| 64 | newFile.write(versionString) |
Oliver Swede | 2144044 | 2018-07-10 09:31:32 +0100 | [diff] [blame] | 65 | print("**[INFO]** Image version number set to " + versionString) |
| 66 | return newVersion |
| 67 | |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 68 | def gen_rsa2048(args): |
Tamas Ban | 861835c | 2019-05-13 08:59:38 +0100 | [diff] [blame] | 69 | keys.RSAutil.generate().export_private(args.key) |
| 70 | |
| 71 | def gen_rsa3072(args): |
| 72 | keys.RSAutil.generate(key_size=3072).export_private(args.key) |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 73 | |
| 74 | keygens = { |
Tamas Ban | 861835c | 2019-05-13 08:59:38 +0100 | [diff] [blame] | 75 | 'rsa-2048': gen_rsa2048, |
| 76 | 'rsa-3072': gen_rsa3072, } |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 77 | |
| 78 | def do_keygen(args): |
| 79 | if args.type not in keygens: |
| 80 | msg = "Unexpected key type: {}".format(args.type) |
| 81 | raise argparse.ArgumentTypeError(msg) |
| 82 | keygens[args.type](args) |
| 83 | |
| 84 | def do_getpub(args): |
| 85 | key = keys.load(args.key) |
| 86 | if args.lang == 'c': |
| 87 | key.emit_c() |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 88 | else: |
Tamas Ban | 581034a | 2017-12-19 19:54:37 +0000 | [diff] [blame] | 89 | msg = "Unsupported language, valid are: c" |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 90 | raise argparse.ArgumentTypeError(msg) |
| 91 | |
| 92 | def do_sign(args): |
| 93 | if args.rsa_pkcs1_15: |
| 94 | keys.sign_rsa_pss = False |
David Vincze | db32b21 | 2019-04-16 17:43:57 +0200 | [diff] [blame] | 95 | |
| 96 | version_num = next_version_number(args, |
| 97 | version.decode_version("0"), |
| 98 | "lastVerNum.txt") |
| 99 | |
| 100 | if args.security_counter is None: |
| 101 | # Security counter has not been explicitly provided, |
| 102 | # generate it from the version number |
| 103 | args.security_counter = ((version_num.major << 24) |
| 104 | + (version_num.minor << 16) |
| 105 | + version_num.revision) |
| 106 | |
David Vincze | 4b84de5 | 2019-09-27 17:40:29 +0200 | [diff] [blame] | 107 | if "_s.c" in args.layout: |
| 108 | sw_type = "SPE" |
| 109 | elif "_ns.c" in args.layout: |
| 110 | sw_type = "NSPE" |
| 111 | else: |
| 112 | sw_type = "NSPE_SPE" |
| 113 | |
Sverteczky, Marcell | 7d069e8 | 2019-07-04 18:17:33 +0200 | [diff] [blame] | 114 | pad_size = macro_parser.evaluate_macro(args.layout, sign_bin_size_re, 0, 1) |
Oliver Swede | 2144044 | 2018-07-10 09:31:32 +0100 | [diff] [blame] | 115 | img = image.Image.load(args.infile, |
David Vincze | db32b21 | 2019-04-16 17:43:57 +0200 | [diff] [blame] | 116 | version=version_num, |
| 117 | header_size=args.header_size, |
| 118 | security_cnt=args.security_counter, |
| 119 | included_header=args.included_header, |
Sverteczky, Marcell | 7d069e8 | 2019-07-04 18:17:33 +0200 | [diff] [blame] | 120 | pad=pad_size) |
Tamas Ban | 32d8464 | 2019-07-11 08:25:11 +0100 | [diff] [blame] | 121 | key = keys.load(args.key, args.public_key_format) if args.key else None |
Sverteczky, Marcell | 7d069e8 | 2019-07-04 18:17:33 +0200 | [diff] [blame] | 122 | ram_load_address = macro_parser.evaluate_macro(args.layout, image_load_address_re, 0, 1) |
David Vincze | 4b84de5 | 2019-09-27 17:40:29 +0200 | [diff] [blame] | 123 | img.sign(sw_type, key, ram_load_address, args.dependencies) |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 124 | |
Sverteczky, Marcell | 7d069e8 | 2019-07-04 18:17:33 +0200 | [diff] [blame] | 125 | if pad_size: |
| 126 | img.pad_to(pad_size, args.align) |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 127 | |
| 128 | img.save(args.outfile) |
| 129 | |
Ludovic Barre | 8a77bdd | 2020-03-26 19:53:07 +0100 | [diff] [blame^] | 130 | def do_flash(args): |
| 131 | image_value_re = re.compile(r"^\s*"+args.macro+"\s*=\s*(.*)") |
| 132 | value = macro_parser.evaluate_macro(args.layout, image_value_re, 0, 1, |
| 133 | True) |
| 134 | if args.setting == 1: |
| 135 | begin_line="set "+args.begin |
| 136 | else: |
| 137 | begin_line=args.begin |
| 138 | |
| 139 | for line in fileinput.input(args.infile, inplace=True): |
| 140 | if line.startswith(begin_line): |
| 141 | if args.division: |
| 142 | value = int(value/int(args.division)) |
| 143 | if args.phexa == 0: |
| 144 | line = begin_line+"="+str(value)+"\n" |
| 145 | else: |
| 146 | line = begin_line+"="+hex(value)+"\n" |
| 147 | sys.stdout.write(line) |
| 148 | |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 149 | subcmds = { |
| 150 | 'keygen': do_keygen, |
| 151 | 'getpub': do_getpub, |
Ludovic Barre | 8a77bdd | 2020-03-26 19:53:07 +0100 | [diff] [blame^] | 152 | 'sign': do_sign, |
| 153 | 'flash': do_flash, } |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 154 | |
David Vincze | 9ec0f54 | 2019-07-03 18:09:47 +0200 | [diff] [blame] | 155 | |
| 156 | def get_dependencies(text): |
| 157 | if text is not None: |
| 158 | versions = [] |
| 159 | images = re.findall(r"\((\d+)", text) |
| 160 | if len(images) == 0: |
| 161 | msg = "Image dependency format is invalid: {}".format(text) |
| 162 | raise argparse.ArgumentTypeError(msg) |
| 163 | raw_versions = re.findall(r",\s*([0-9.+]+)\)", text) |
| 164 | if len(images) != len(raw_versions): |
| 165 | msg = '''There's a mismatch between the number of dependency images |
| 166 | and versions in: {}'''.format(text) |
| 167 | raise argparse.ArgumentTypeError(msg) |
| 168 | for raw_version in raw_versions: |
| 169 | try: |
| 170 | versions.append(version.decode_version(raw_version)) |
| 171 | except ValueError as e: |
| 172 | print(e) |
| 173 | dependencies = dict() |
| 174 | dependencies[image.DEP_IMAGES_KEY] = images |
| 175 | dependencies[image.DEP_VERSIONS_KEY] = versions |
| 176 | return dependencies |
| 177 | |
| 178 | |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 179 | def alignment_value(text): |
| 180 | value = int(text) |
| 181 | if value not in [1, 2, 4, 8]: |
| 182 | msg = "{} must be one of 1, 2, 4 or 8".format(value) |
| 183 | raise argparse.ArgumentTypeError(msg) |
| 184 | return value |
| 185 | |
| 186 | def intparse(text): |
| 187 | """Parse a command line argument as an integer. |
| 188 | |
| 189 | Accepts 0x and other prefixes to allow other bases to be used.""" |
| 190 | return int(text, 0) |
| 191 | |
| 192 | def args(): |
| 193 | parser = argparse.ArgumentParser() |
| 194 | subs = parser.add_subparsers(help='subcommand help', dest='subcmd') |
| 195 | |
| 196 | keygenp = subs.add_parser('keygen', help='Generate pub/private keypair') |
| 197 | keygenp.add_argument('-k', '--key', metavar='filename', required=True) |
| 198 | keygenp.add_argument('-t', '--type', metavar='type', |
Oliver Swede | 2144044 | 2018-07-10 09:31:32 +0100 | [diff] [blame] | 199 | choices=keygens.keys(), required=True) |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 200 | |
| 201 | getpub = subs.add_parser('getpub', help='Get public key from keypair') |
| 202 | getpub.add_argument('-k', '--key', metavar='filename', required=True) |
| 203 | getpub.add_argument('-l', '--lang', metavar='lang', default='c') |
| 204 | |
| 205 | sign = subs.add_parser('sign', help='Sign an image with a private key') |
Sverteczky, Marcell | 7d069e8 | 2019-07-04 18:17:33 +0200 | [diff] [blame] | 206 | sign.add_argument('-l', '--layout', required=True, |
| 207 | help='Location of the file that contains preprocessed macros') |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 208 | sign.add_argument('-k', '--key', metavar='filename') |
Tamas Ban | 32d8464 | 2019-07-11 08:25:11 +0100 | [diff] [blame] | 209 | sign.add_argument("-K", "--public-key-format", |
| 210 | help='In what format to add the public key to the image manifest: full or hash', |
| 211 | metavar='pub_key_format', choices=['full', 'hash'], default='hash') |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 212 | sign.add_argument("--align", type=alignment_value, required=True) |
Oliver Swede | 2144044 | 2018-07-10 09:31:32 +0100 | [diff] [blame] | 213 | sign.add_argument("-v", "--version", type=version.decode_version, |
| 214 | default="0.0.0+0") |
David Vincze | 9ec0f54 | 2019-07-03 18:09:47 +0200 | [diff] [blame] | 215 | sign.add_argument("-d", "--dependencies", type=get_dependencies, |
| 216 | required=False, help='''Add dependence on another image, |
| 217 | format: "(<image_ID>,<image_version>), ... "''') |
David Vincze | db32b21 | 2019-04-16 17:43:57 +0200 | [diff] [blame] | 218 | sign.add_argument("-s", "--security-counter", type=intparse, |
| 219 | help='Specify explicitly the security counter value') |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 220 | sign.add_argument("-H", "--header-size", type=intparse, required=True) |
| 221 | sign.add_argument("--included-header", default=False, action='store_true', |
Oliver Swede | 2144044 | 2018-07-10 09:31:32 +0100 | [diff] [blame] | 222 | help='Image has gap for header') |
Oliver Swede | 2144044 | 2018-07-10 09:31:32 +0100 | [diff] [blame] | 223 | sign.add_argument("--rsa-pkcs1-15", |
| 224 | help='Use old PKCS#1 v1.5 signature algorithm', |
| 225 | default=False, action='store_true') |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 226 | sign.add_argument("infile") |
| 227 | sign.add_argument("outfile") |
| 228 | |
Ludovic Barre | 8a77bdd | 2020-03-26 19:53:07 +0100 | [diff] [blame^] | 229 | flash = subs.add_parser('flash', help='modify flash script') |
| 230 | flash.add_argument("infile") |
| 231 | flash.add_argument('-l', '--layout', required=True, |
| 232 | help='Location of the file that contains preprocessed macros') |
| 233 | flash.add_argument('-m', '--macro', required =True, |
| 234 | help='macro symbol string to grep in preprocessed file') |
| 235 | flash.add_argument('-b', '--begin', required=True, |
| 236 | help='begin of line to replace ') |
| 237 | flash.add_argument('-s', '--setting',type=intparse,required=False,default=0, |
| 238 | help='search for window batch set variable') |
| 239 | flash.add_argument('-d', '--division', |
| 240 | required=False,type=intparse,default=0, |
| 241 | help='search for window batch set variable') |
| 242 | flash.add_argument('-p', '--phexa', |
| 243 | required=False,type=intparse,default=1, |
| 244 | help='print value in hexa') |
| 245 | |
Tamas Ban | f70ef8c | 2017-12-19 15:35:09 +0000 | [diff] [blame] | 246 | args = parser.parse_args() |
| 247 | if args.subcmd is None: |
| 248 | print('Must specify a subcommand', file=sys.stderr) |
| 249 | sys.exit(1) |
| 250 | |
| 251 | subcmds[args.subcmd](args) |
| 252 | |
| 253 | if __name__ == '__main__': |
David Vincze | db32b21 | 2019-04-16 17:43:57 +0200 | [diff] [blame] | 254 | args() |