diff --git a/requirements.txt b/requirements.txt index de08793b17..d821df819e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -21,3 +21,4 @@ fuzzywuzzy>=0.11,<=0.17 pyelftools>=0.24,<=0.25 git+https://github.com/armmbed/manifest-tool.git@v1.4.6 icetea>=1.2.1,<1.3 +pycryptodome>=3.7.2,<=3.7.3 diff --git a/tools/psa/tfm/__init__.py b/tools/psa/tfm/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tools/psa/tfm/bin_utils/__init__.py b/tools/psa/tfm/bin_utils/__init__.py new file mode 100644 index 0000000000..3aaffc4847 --- /dev/null +++ b/tools/psa/tfm/bin_utils/__init__.py @@ -0,0 +1,21 @@ +# Copyright (c) 2017-2018 ARM Limited +# +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .assemble import Assembly + +__all__ = [ + 'Assembly' +] diff --git a/tools/psa/tfm/bin_utils/assemble.py b/tools/psa/tfm/bin_utils/assemble.py new file mode 100644 index 0000000000..0bb41f122e --- /dev/null +++ b/tools/psa/tfm/bin_utils/assemble.py @@ -0,0 +1,105 @@ +#! /usr/bin/env python3 +# +# Copyright 2017 Linaro Limited +# Copyright (c) 2017-2018, Arm Limited. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Assemble multiple images into a single image that can be flashed on the device. +""" + +import argparse +import errno +import io +import re +import os +import shutil + +offset_re = re.compile(r"^#define ([0-9A-Z_]+)_IMAGE_OFFSET\s+((0x)?[0-9a-fA-F]+)") +size_re = re.compile(r"^#define ([0-9A-Z_]+)_IMAGE_MAX_SIZE\s+((0x)?[0-9a-fA-F]+)") + +class Assembly(): + def __init__(self, layout_path, output): + self.output = output + self.layout_path = layout_path + self.find_slots() + try: + os.unlink(output) + except OSError as e: + if e.errno != errno.ENOENT: + raise + + def find_slots(self): + offsets = {} + sizes = {} + + if os.path.isabs(self.layout_path): + configFile = self.layout_path + else: + scriptsDir = os.path.dirname(os.path.abspath(__file__)) + configFile = os.path.join(scriptsDir, self.layout_path) + + with open(configFile, 'r') as fd: + for line in fd: + m = offset_re.match(line) + if m is not None: + offsets[m.group(1)] = int(m.group(2), 0) + m = size_re.match(line) + if m is not None: + sizes[m.group(1)] = int(m.group(2), 0) + + if 'SECURE' not in offsets: + raise Exception("Image config does not have secure partition") + + if 'NON_SECURE' not in offsets: + raise Exception("Image config does not have non-secure partition") + + self.offsets = offsets + self.sizes = sizes + + def add_image(self, source, partition): + with open(self.output, 'ab') as ofd: + ofd.seek(0, os.SEEK_END) + pos = ofd.tell() + if pos > self.offsets[partition]: + raise Exception("Partitions not in order, unsupported") + if pos < self.offsets[partition]: + ofd.write(b'\xFF' * (self.offsets[partition] - pos)) + statinfo = os.stat(source) + if statinfo.st_size > self.sizes[partition]: + raise Exception("Image {} is too large for partition".format(source)) + with open(source, 'rb') as rfd: + shutil.copyfileobj(rfd, ofd, 0x10000) + +def main(): + parser = argparse.ArgumentParser() + + parser.add_argument('-l', '--layout', required=True, + help='Location of the memory layout file') + parser.add_argument('-s', '--secure', required=True, + help='Unsigned secure image') + parser.add_argument('-n', '--non_secure', + help='Unsigned non-secure image') + parser.add_argument('-o', '--output', required=True, + help='Filename to write full image to') + + args = parser.parse_args() + output = Assembly(args.layout, args.output) + + + output.add_image(args.secure, "SECURE") + output.add_image(args.non_secure, "NON_SECURE") + +if __name__ == '__main__': + main() diff --git a/tools/psa/tfm/bin_utils/imgtool.py b/tools/psa/tfm/bin_utils/imgtool.py new file mode 100644 index 0000000000..b984ce2170 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# +# Copyright 2017 Linaro Limited +# Copyright (c) 2018, Arm Limited. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import print_function +import os +import re +import argparse +from imgtool_lib import keys +from imgtool_lib import image +from imgtool_lib import version +import sys + +def find_load_address(args): + load_address_re = re.compile(r"^#define\sIMAGE_LOAD_ADDRESS\s+(0x[0-9a-fA-F]+)") + + if os.path.isabs(args.layout): + configFile = args.layout + else: + scriptsDir = os.path.dirname(os.path.abspath(__file__)) + configFile = os.path.join(scriptsDir, args.layout) + + ramLoadAddress = None + with open(configFile, 'r') as flash_layout_file: + for line in flash_layout_file: + m = load_address_re.match(line) + if m is not None: + ramLoadAddress = int(m.group(1), 0) + print("**[INFO]** Writing load address from the macro in " + "flash_layout.h to the image header.. " + + hex(ramLoadAddress) + + " (dec. " + str(ramLoadAddress) + ")") + break + return ramLoadAddress + +# Returns the last version number if present, or None if not +def get_last_version(path): + if (os.path.isfile(path) == False): # Version file not present + return None + else: # Version file is present, check it has a valid number inside it + with open(path, "r") as oldFile: + fileContents = oldFile.read() + if version.version_re.match(fileContents): # number is valid + return version.decode_version(fileContents) + else: + return None + +def next_version_number(args, defaultVersion, path): + newVersion = None + if (version.compare(args.version, defaultVersion) == 0): # Default version + lastVersion = get_last_version(path) + if (lastVersion is not None): + newVersion = version.increment_build_num(lastVersion) + else: + newVersion = version.increment_build_num(defaultVersion) + else: # Version number has been explicitly provided (not using the default) + newVersion = args.version + versionString = "{a}.{b}.{c}+{d}".format( + a=str(newVersion.major), + b=str(newVersion.minor), + c=str(newVersion.revision), + d=str(newVersion.build) + ) + with open(path, "w") as newFile: + newFile.write(versionString) + print("**[INFO]** Image version number set to " + versionString) + return newVersion + +def gen_rsa2048(args): + keys.RSA2048.generate().export_private(args.key) + +keygens = { + 'rsa-2048': gen_rsa2048, } + +def do_keygen(args): + if args.type not in keygens: + msg = "Unexpected key type: {}".format(args.type) + raise argparse.ArgumentTypeError(msg) + keygens[args.type](args) + +def do_getpub(args): + key = keys.load(args.key) + if args.lang == 'c': + key.emit_c() + else: + msg = "Unsupported language, valid are: c" + raise argparse.ArgumentTypeError(msg) + +def do_sign(args): + if args.rsa_pkcs1_15: + keys.sign_rsa_pss = False + img = image.Image.load(args.infile, + version=next_version_number(args, + version.decode_version("0"), + "lastVerNum.txt"), + header_size=args.header_size, + included_header=args.included_header, + pad=args.pad) + key = keys.load(args.key) if args.key else None + img.sign(key, find_load_address(args)) + + if args.pad: + img.pad_to(args.pad, args.align) + + img.save(args.outfile) + +subcmds = { + 'keygen': do_keygen, + 'getpub': do_getpub, + 'sign': do_sign, } + +def alignment_value(text): + value = int(text) + if value not in [1, 2, 4, 8]: + msg = "{} must be one of 1, 2, 4 or 8".format(value) + raise argparse.ArgumentTypeError(msg) + return value + +def intparse(text): + """Parse a command line argument as an integer. + + Accepts 0x and other prefixes to allow other bases to be used.""" + return int(text, 0) + +def args(): + parser = argparse.ArgumentParser() + subs = parser.add_subparsers(help='subcommand help', dest='subcmd') + + keygenp = subs.add_parser('keygen', help='Generate pub/private keypair') + keygenp.add_argument('-k', '--key', metavar='filename', required=True) + keygenp.add_argument('-t', '--type', metavar='type', + choices=keygens.keys(), required=True) + + getpub = subs.add_parser('getpub', help='Get public key from keypair') + getpub.add_argument('-k', '--key', metavar='filename', required=True) + getpub.add_argument('-l', '--lang', metavar='lang', default='c') + + sign = subs.add_parser('sign', help='Sign an image with a private key') + sign.add_argument('--layout', required=True, + help='Location of the memory layout file') + sign.add_argument('-k', '--key', metavar='filename') + sign.add_argument("--align", type=alignment_value, required=True) + sign.add_argument("-v", "--version", type=version.decode_version, + default="0.0.0+0") + sign.add_argument("-H", "--header-size", type=intparse, required=True) + sign.add_argument("--included-header", default=False, action='store_true', + help='Image has gap for header') + sign.add_argument("--pad", type=intparse, + help='Pad image to this many bytes, adding trailer magic') + sign.add_argument("--rsa-pkcs1-15", + help='Use old PKCS#1 v1.5 signature algorithm', + default=False, action='store_true') + sign.add_argument("infile") + sign.add_argument("outfile") + + args = parser.parse_args() + if args.subcmd is None: + print('Must specify a subcommand', file=sys.stderr) + sys.exit(1) + + subcmds[args.subcmd](args) + +if __name__ == '__main__': + args() \ No newline at end of file diff --git a/tools/psa/tfm/bin_utils/imgtool_lib/__init__.py b/tools/psa/tfm/bin_utils/imgtool_lib/__init__.py new file mode 100644 index 0000000000..fd240440dc --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool_lib/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2017 Linaro Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This file is intentionally empty. +# +# The __init__.py files are required to make Python treat the directories as +# containing packages. \ No newline at end of file diff --git a/tools/psa/tfm/bin_utils/imgtool_lib/image.py b/tools/psa/tfm/bin_utils/imgtool_lib/image.py new file mode 100644 index 0000000000..67425d4ba3 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool_lib/image.py @@ -0,0 +1,179 @@ +# Copyright 2017 Linaro Limited +# Copyright (c) 2018, Arm Limited. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Image signing and management. +""" + +from . import version as versmod +import hashlib +import struct + +IMAGE_MAGIC = 0x96f3b83d +IMAGE_HEADER_SIZE = 32 + +# Image header flags. +IMAGE_F = { + 'PIC': 0x0000001, + 'NON_BOOTABLE': 0x0000010, + 'RAM_LOAD': 0x0000020, } +TLV_VALUES = { + 'KEYHASH': 0x01, + 'SHA256' : 0x10, + 'RSA2048': 0x20, } + +TLV_INFO_SIZE = 4 +TLV_INFO_MAGIC = 0x6907 + +# Sizes of the image trailer, depending on flash write size. +trailer_sizes = { + write_size: 128 * 3 * write_size + 8 * 2 + 16 + for write_size in [1, 2, 4, 8] +} + +boot_magic = bytearray([ + 0x77, 0xc2, 0x95, 0xf3, + 0x60, 0xd2, 0xef, 0x7f, + 0x35, 0x52, 0x50, 0x0f, + 0x2c, 0xb6, 0x79, 0x80, ]) + +class TLV(): + def __init__(self): + self.buf = bytearray() + + def add(self, kind, payload): + """Add a TLV record. Kind should be a string found in TLV_VALUES above.""" + buf = struct.pack(' 0: + obj.payload = (b'\000' * obj.header_size) + obj.payload + + obj.check() + return obj + + def __init__(self, version, header_size=IMAGE_HEADER_SIZE, pad=0): + self.version = version + self.header_size = header_size or IMAGE_HEADER_SIZE + self.pad = pad + + def __repr__(self): + return "".format( + self.version, + self.header_size, + self.pad, + len(self.payload)) + + def save(self, path): + with open(path, 'wb') as f: + f.write(self.payload) + + def check(self): + """Perform some sanity checking of the image.""" + # If there is a header requested, make sure that the image + # starts with all zeros. + if self.header_size > 0: + if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]): + raise Exception("Padding requested, but image does not start with zeros") + + def sign(self, key, ramLoadAddress): + self.add_header(key, ramLoadAddress) + + tlv = TLV() + + sha = hashlib.sha256() + sha.update(self.payload) + digest = sha.digest() + + tlv.add('SHA256', digest) + + if key is not None: + pub = key.get_public_bytes() + sha = hashlib.sha256() + sha.update(pub) + pubbytes = sha.digest() + tlv.add('KEYHASH', pubbytes) + + sig = key.sign(self.payload) + tlv.add(key.sig_tlv(), sig) + + self.payload += tlv.get() + + def add_header(self, key, ramLoadAddress): + """Install the image header. + + The key is needed to know the type of signature, and + approximate the size of the signature.""" + + flags = 0 + if ramLoadAddress is not None: + # add the load address flag to the header to indicate that an SRAM + # load address macro has been defined + flags |= IMAGE_F["RAM_LOAD"] + + fmt = ('<' + + # type ImageHdr struct { + 'I' + # Magic uint32 + 'I' + # LoadAddr uint32 + 'H' + # HdrSz uint16 + 'H' + # Pad1 uint16 + 'I' + # ImgSz uint32 + 'I' + # Flags uint32 + 'BBHI' + # Vers ImageVersion + 'I' # Pad2 uint32 + ) # } + assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE + header = struct.pack(fmt, + IMAGE_MAGIC, + 0 if (ramLoadAddress is None) else ramLoadAddress, # LoadAddr + self.header_size, + 0, # Pad1 + len(self.payload) - self.header_size, # ImageSz + flags, # Flags + self.version.major, + self.version.minor or 0, + self.version.revision or 0, + self.version.build or 0, + 0) # Pad2 + self.payload = bytearray(self.payload) + self.payload[:len(header)] = header + + def pad_to(self, size, align): + """Pad the image to the given size, with the given flash alignment.""" + tsize = trailer_sizes[align] + padding = size - (len(self.payload) + tsize) + if padding < 0: + msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format( + len(self.payload), tsize, size) + raise Exception(msg) + pbytes = b'\xff' * padding + pbytes += b'\xff' * (tsize - len(boot_magic)) + pbytes += boot_magic + self.payload += pbytes \ No newline at end of file diff --git a/tools/psa/tfm/bin_utils/imgtool_lib/keys.py b/tools/psa/tfm/bin_utils/imgtool_lib/keys.py new file mode 100644 index 0000000000..fda3ed6710 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool_lib/keys.py @@ -0,0 +1,104 @@ +# Copyright 2017 Linaro Limited +# Copyright (c) 2017-2018, Arm Limited. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Cryptographic key management for imgtool. +""" + +from __future__ import print_function +from Crypto.Hash import SHA256 +from Crypto.PublicKey import RSA +from Crypto.Signature import PKCS1_v1_5, PKCS1_PSS +import hashlib +from pyasn1.type import namedtype, univ +from pyasn1.codec.der.encoder import encode + +# By default, we use RSA-PSS (PKCS 2.1). That can be overridden on +# the command line to support the older (less secure) PKCS1.5 +sign_rsa_pss = True + +AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */" + +class RSAPublicKey(univ.Sequence): + componentType = namedtype.NamedTypes( + namedtype.NamedType('modulus', univ.Integer()), + namedtype.NamedType('publicExponent', univ.Integer())) + +class RSA2048(): + def __init__(self, key): + """Construct an RSA2048 key with the given key data""" + self.key = key + + @staticmethod + def generate(): + return RSA2048(RSA.generate(2048)) + + def export_private(self, path): + with open(path, 'wb') as f: + f.write(self.key.exportKey('PEM')) + + def get_public_bytes(self): + node = RSAPublicKey() + node['modulus'] = self.key.n + node['publicExponent'] = self.key.e + return bytearray(encode(node)) + + def emit_c(self): + print(AUTOGEN_MESSAGE) + print("const unsigned char rsa_pub_key[] = {", end='') + encoded = self.get_public_bytes() + for count, b in enumerate(encoded): + if count % 8 == 0: + print("\n\t", end='') + else: + print(" ", end='') + print("0x{:02x},".format(b), end='') + print("\n};") + print("const unsigned int rsa_pub_key_len = {};".format(len(encoded))) + + def sig_type(self): + """Return the type of this signature (as a string)""" + if sign_rsa_pss: + return "PKCS1_PSS_RSA2048_SHA256" + else: + return "PKCS15_RSA2048_SHA256" + + def sig_len(self): + return 256 + + def sig_tlv(self): + return "RSA2048" + + def sign(self, payload): + converted_payload = bytes(payload) + sha = SHA256.new(converted_payload) + if sign_rsa_pss: + signer = PKCS1_PSS.new(self.key) + else: + signer = PKCS1_v1_5.new(self.key) + signature = signer.sign(sha) + assert len(signature) == self.sig_len() + return signature + +def load(path): + with open(path, 'rb') as f: + pem = f.read() + try: + key = RSA.importKey(pem) + if key.n.bit_length() != 2048: + raise Exception("Unsupported RSA bit length, only 2048 supported") + return RSA2048(key) + except ValueError: + raise Exception("Unsupported RSA key file") diff --git a/tools/psa/tfm/bin_utils/imgtool_lib/version.py b/tools/psa/tfm/bin_utils/imgtool_lib/version.py new file mode 100644 index 0000000000..d1d45f0385 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool_lib/version.py @@ -0,0 +1,66 @@ +# Copyright 2017 Linaro Limited +# Copyright (c) 2018, Arm Limited. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Semi Semantic Versioning + +Implements a subset of semantic versioning that is supportable by the image header. +""" + +import argparse +from collections import namedtuple +import re + +SemiSemVersion = namedtuple('SemiSemVersion', ['major', 'minor', 'revision', 'build']) + +def increment_build_num(lastVer): + newVer = SemiSemVersion(lastVer.major, lastVer.minor, lastVer.revision, lastVer.build + 1) + return newVer + +# -1 if a is older than b; 0 if they're the same version; 1 if a is newer than b +def compare(a, b): + if (a.major > b.major): return 1 + elif (a.major < b.major): return -1 + else: + if (a.minor > b.minor): return 1 + elif (a.minor < b.minor): return -1 + else: + if (a.revision > b.revision): return 1 + elif (a.revision < b.revision): return -1 + else: + if (a.build > b.build): return 1 + elif (a.build < b.build): return -1 + else: return 0 + +version_re = re.compile(r"""^([1-9]\d*|0)(\.([1-9]\d*|0)(\.([1-9]\d*|0)(\+([1-9]\d*|0))?)?)?$""") +def decode_version(text): + """Decode the version string, which should be of the form maj.min.rev+build""" + m = version_re.match(text) + if m: + result = SemiSemVersion( + int(m.group(1)) if m.group(1) else 0, + int(m.group(3)) if m.group(3) else 0, + int(m.group(5)) if m.group(5) else 0, + int(m.group(7)) if m.group(7) else 0) + return result + else: + msg = "Invalid version number, should be maj.min.rev+build with later parts optional" + raise argparse.ArgumentTypeError(msg) + +if __name__ == '__main__': + print(decode_version("1.2")) + print(decode_version("1.0")) + print(decode_version("0.0.2+75")) + print(decode_version("0.0.0+00"))