Boot: integrate MCUBoot with TF-M to act as a BL2 bootloader

Modifications in MCUBoot to be aligned with BL2 requirements in TF-M:
 -- OS dependency was removed, no need to copy any OS repo to build it
 -- CMSIS serial driver is used
 -- flash driver interface is aligned with original version
 -- S and NS images are handeled as a single binary blob
 -- automatic image concatenation and signing at build time
 -- authentication based on SHA256 and RSA-2048 digital signature
 -- mbedTLS library is used for cryptographic operation
 -- static analyser warnings fixed in some files

Change-Id: I54891762eac8d0df634e954ff19a9505b16f3028
Signed-off-by: Tamas Ban <tamas.ban@arm.com>
diff --git a/bl2/ext/mcuboot/scripts/assemble.py b/bl2/ext/mcuboot/scripts/assemble.py
index 7a38985..1523964 100644
--- a/bl2/ext/mcuboot/scripts/assemble.py
+++ b/bl2/ext/mcuboot/scripts/assemble.py
@@ -1,6 +1,7 @@
 #! /usr/bin/env python3
 #
 # Copyright 2017 Linaro Limited
+# Copyright (c) 2017, Arm Limited.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -22,24 +23,15 @@
 import errno
 import io
 import re
-import os.path
+import os
+import shutil
 
-def same_keys(a, b):
-    """Determine if the dicts a and b have the same keys in them"""
-    for ak in a.keys():
-        if ak not in b:
-            return False
-    for bk in b.keys():
-        if bk not in a:
-            return False
-    return True
-
-offset_re = re.compile(r"^#define FLASH_AREA_([0-9A-Z_]+)_OFFSET_0\s+((0x)?[0-9a-fA-F]+)")
-size_re   = re.compile(r"^#define FLASH_AREA_([0-9A-Z_]+)_SIZE_0\s+((0x)?[0-9a-fA-F]+)")
+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, output, bootdir):
-        self.find_slots(bootdir)
+    def __init__(self, output):
+        self.find_slots()
         try:
             os.unlink(output)
         except OSError as e:
@@ -47,10 +39,15 @@
                 raise
         self.output = output
 
-    def find_slots(self, bootdir):
+    def find_slots(self):
         offsets = {}
         sizes = {}
-        with open(os.path.join(bootdir, 'include', 'generated', 'generated_dts_board.h'), 'r') as fd:
+
+        scriptsDir = os.path.dirname(os.path.abspath(__file__))
+        path = '../../../../platform/ext/target/sse_200_mps2/sse_200/partition/flash_layout.h'
+        configFile = os.path.join(scriptsDir, path)
+
+        with open(configFile, 'r') as fd:
             for line in fd:
                 m = offset_re.match(line)
                 if m is not None:
@@ -59,18 +56,11 @@
                 if m is not None:
                     sizes[m.group(1)] = int(m.group(2), 0)
 
-        if not same_keys(offsets, sizes):
-            raise Exception("Inconsistent data in generated_dts_board.h")
+        if 'SECURE' not in offsets:
+            raise Exception("Image config does not have secure partition")
 
-        # We care about the MCUBOOT, IMAGE_0, and IMAGE_1 partitions.
-        if 'MCUBOOT' not in offsets:
-            raise Exception("Board partition table does not have mcuboot partition")
-
-        if 'IMAGE_0' not in offsets:
-            raise Exception("Board partition table does not have image-0 partition")
-
-        if 'IMAGE_1' not in offsets:
-            raise Exception("Board partition table does not have image-1 partition")
+        if 'NON_SECURE' not in offsets:
+            raise Exception("Image config does not have non-secure partition")
 
         self.offsets = offsets
         self.sizes = sizes
@@ -78,37 +68,32 @@
     def add_image(self, source, partition):
         with open(self.output, 'ab') as ofd:
             pos = ofd.tell()
-            print("partition {}, pos={}, offset={}".format(partition, pos, self.offsets[partition]))
             if pos > self.offsets[partition]:
                 raise Exception("Partitions not in order, unsupported")
             if pos < self.offsets[partition]:
-                buf = b'\xFF' * (self.offsets[partition] - pos)
-                ofd.write(buf)
+                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:
-                ibuf = rfd.read()
-                if len(ibuf) > self.sizes[partition]:
-                    raise Exception("Image {} is too large for partition".format(source))
-            ofd.write(ibuf)
+                shutil.copyfileobj(rfd, ofd, 0x10000)
 
 def main():
     parser = argparse.ArgumentParser()
 
-    parser.add_argument('-b', '--bootdir', required=True,
-            help='Directory of built bootloader')
-    parser.add_argument('-p', '--primary', required=True,
-            help='Signed image file for primary image')
-    parser.add_argument('-s', '--secondary',
-            help='Signed image file for secondary image')
+    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.output, args.bootdir)
+    output = Assembly(args.output)
 
-    output.add_image(os.path.join(args.bootdir, "zephyr.bin"), 'MCUBOOT')
-    output.add_image(args.primary, "IMAGE_0")
-    if args.secondary is not None:
-        output.add_image(args.secondary, "IMAGE_1")
+
+    output.add_image(args.secure, "SECURE")
+    output.add_image(args.non_secure, "NON_SECURE")
 
 if __name__ == '__main__':
     main()
diff --git a/bl2/ext/mcuboot/scripts/imgtool.py b/bl2/ext/mcuboot/scripts/imgtool.py
index bc67252..9420d2b 100644
--- a/bl2/ext/mcuboot/scripts/imgtool.py
+++ b/bl2/ext/mcuboot/scripts/imgtool.py
@@ -22,15 +22,9 @@
 
 def gen_rsa2048(args):
     keys.RSA2048.generate().export_private(args.key)
-def gen_ecdsa_p256(args):
-    keys.ECDSA256P1.generate().export_private(args.key)
-def gen_ecdsa_p224(args):
-    print("TODO: p-224 not yet implemented")
 
 keygens = {
-        'rsa-2048': gen_rsa2048,
-        'ecdsa-p256': gen_ecdsa_p256,
-        'ecdsa-p224': gen_ecdsa_p224, }
+        'rsa-2048': gen_rsa2048, }
 
 def do_keygen(args):
     if args.type not in keygens:
@@ -42,10 +36,8 @@
     key = keys.load(args.key)
     if args.lang == 'c':
         key.emit_c()
-    elif args.lang == 'rust':
-        key.emit_rust()
     else:
-        msg = "Unsupported language, valid are: c, or rust"
+        msg = "Unsupported language, valid are: c"
         raise argparse.ArgumentTypeError(msg)
 
 def do_sign(args):
diff --git a/bl2/ext/mcuboot/scripts/imgtool/__init__.py b/bl2/ext/mcuboot/scripts/imgtool/__init__.py
index 107921f..fd24044 100644
--- a/bl2/ext/mcuboot/scripts/imgtool/__init__.py
+++ b/bl2/ext/mcuboot/scripts/imgtool/__init__.py
@@ -11,3 +11,8 @@
 # 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/bl2/ext/mcuboot/scripts/imgtool/image.py b/bl2/ext/mcuboot/scripts/imgtool/image.py
index 79a342d..f8309b3 100644
--- a/bl2/ext/mcuboot/scripts/imgtool/image.py
+++ b/bl2/ext/mcuboot/scripts/imgtool/image.py
@@ -30,10 +30,8 @@
 
 TLV_VALUES = {
         'KEYHASH': 0x01,
-        'SHA256': 0x10,
-        'RSA2048': 0x20,
-        'ECDSA224': 0x21,
-        'ECDSA256': 0x22, }
+        'SHA256' : 0x10,
+        'RSA2048': 0x20, }
 
 TLV_INFO_SIZE = 4
 TLV_INFO_MAGIC = 0x6907
@@ -110,8 +108,6 @@
 
         tlv = TLV()
 
-        # Note that ecdsa wants to do the hashing itself, which means
-        # we get to hash it twice.
         sha = hashlib.sha256()
         sha.update(self.payload)
         digest = sha.digest()
diff --git a/bl2/ext/mcuboot/scripts/imgtool/keys.py b/bl2/ext/mcuboot/scripts/imgtool/keys.py
index ee54a0f..9728cd0 100644
--- a/bl2/ext/mcuboot/scripts/imgtool/keys.py
+++ b/bl2/ext/mcuboot/scripts/imgtool/keys.py
@@ -1,4 +1,5 @@
 # Copyright 2017 Linaro Limited
+# Copyright (c) 2017, Arm Limited.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -19,7 +20,6 @@
 from Crypto.Hash import SHA256
 from Crypto.PublicKey import RSA
 from Crypto.Signature import PKCS1_v1_5, PKCS1_PSS
-from ecdsa import SigningKey, NIST256p, util
 import hashlib
 from pyasn1.type import namedtype, univ
 from pyasn1.codec.der.encoder import encode
@@ -67,18 +67,6 @@
         print("\n};")
         print("const unsigned int rsa_pub_key_len = {};".format(len(encoded)))
 
-    def emit_rust(self):
-        print(AUTOGEN_MESSAGE)
-        print("static RSA_PUB_KEY: &'static [u8] = &[", end='')
-        encoded = self.get_public_bytes()
-        for count, b in enumerate(encoded):
-            if count % 8 == 0:
-                print("\n    ", end='')
-            else:
-                print(" ", end='')
-            print("0x{:02x},".format(b), end='')
-        print("\n];")
-
     def sig_type(self):
         """Return the type of this signature (as a string)"""
         if sign_rsa_pss:
@@ -93,7 +81,8 @@
         return "RSA2048"
 
     def sign(self, payload):
-        sha = SHA256.new(payload)
+        converted_payload = bytes(payload)
+        sha = SHA256.new(converted_payload)
         if sign_rsa_pss:
             signer = PKCS1_PSS.new(self.key)
         else:
@@ -102,72 +91,6 @@
         assert len(signature) == self.sig_len()
         return signature
 
-class ECDSA256P1():
-    def __init__(self, key):
-        """Construct an ECDSA P-256 private key"""
-        self.key = key
-
-    @staticmethod
-    def generate():
-        return ECDSA256P1(SigningKey.generate(curve=NIST256p))
-
-    def export_private(self, path):
-        with open(path, 'wb') as f:
-            f.write(self.key.to_pem())
-
-    def get_public_bytes(self):
-        vk = self.key.get_verifying_key()
-        return bytes(vk.to_der())
-
-    def emit_c(self):
-        vk = self.key.get_verifying_key()
-        print(AUTOGEN_MESSAGE)
-        print("const unsigned char ecdsa_pub_key[] = {", end='')
-        encoded = bytes(vk.to_der())
-        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 ecdsa_pub_key_len = {};".format(len(encoded)))
-
-    def emit_rust(self):
-        vk = self.key.get_verifying_key()
-        print(AUTOGEN_MESSAGE)
-        print("static ECDSA_PUB_KEY: &'static [u8] = &[", end='')
-        encoded = bytes(vk.to_der())
-        for count, b in enumerate(encoded):
-            if count % 8 == 0:
-                print("\n    ", end='')
-            else:
-                print(" ", end='')
-            print("0x{:02x},".format(b), end='')
-        print("\n];")
-
-    def sign(self, payload):
-        # To make this fixed length, possibly pad with zeros.
-        sig = self.key.sign(payload, hashfunc=hashlib.sha256, sigencode=util.sigencode_der)
-        sig += b'\000' * (self.sig_len() - len(sig))
-        return sig
-
-    def sig_len(self):
-        # The DER encoding depends on the high bit, and can be
-        # anywhere from 70 to 72 bytes.  Because we have to fill in
-        # the length field before computing the signature, however,
-        # we'll give the largest, and the sig checking code will allow
-        # for it to be up to two bytes larger than the actual
-        # signature.
-        return 72
-
-    def sig_type(self):
-        """Return the type of this signature (as a string)"""
-        return "ECDSA256_SHA256"
-
-    def sig_tlv(self):
-        return "ECDSA256"
-
 def load(path):
     with open(path, 'rb') as f:
         pem = f.read()
@@ -177,7 +100,4 @@
             raise Exception("Unsupported RSA bit length, only 2048 supported")
         return RSA2048(key)
     except ValueError:
-        key = SigningKey.from_pem(pem)
-        if key.curve.name != 'NIST256p':
-            raise Exception("Unsupported ECDSA curve")
-        return ECDSA256P1(key)
+        raise Exception("Unsupported RSA key file")