Boot: add original files from MCUBoot and Zephyr project

Aligned with MCUBoot version 1.0.0
MCUBoot files:
 -- bl2/ext/mcuboot

Aligned with Zephyr version 1.10.0
Zephyr files:
 -- bl2/ext/mcuboot/include/util.h
 -- platform/ext/target/common/flash.h

Change-Id: I314c3efa2bd2c13a4a2eaefeb5da43e53e988638
Signed-off-by: Tamas Ban <tamas.ban@arm.com>
diff --git a/bl2/ext/mcuboot/scripts/imgtool/__init__.py b/bl2/ext/mcuboot/scripts/imgtool/__init__.py
new file mode 100644
index 0000000..107921f
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/imgtool/__init__.py
@@ -0,0 +1,13 @@
+# 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.
diff --git a/bl2/ext/mcuboot/scripts/imgtool/image.py b/bl2/ext/mcuboot/scripts/imgtool/image.py
new file mode 100644
index 0000000..79a342d
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/imgtool/image.py
@@ -0,0 +1,189 @@
+# 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.
+
+"""
+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, }
+
+TLV_VALUES = {
+        'KEYHASH': 0x01,
+        'SHA256': 0x10,
+        'RSA2048': 0x20,
+        'ECDSA224': 0x21,
+        'ECDSA256': 0x22, }
+
+TLV_INFO_SIZE = 4
+TLV_INFO_MAGIC = 0x6907
+TLV_HEADER_SIZE = 4
+
+# 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 = bytes([
+    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('<BBH', TLV_VALUES[kind], 0, len(payload))
+        self.buf += buf
+        self.buf += payload
+
+    def get(self):
+        header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
+        return header + bytes(self.buf)
+
+class Image():
+    @classmethod
+    def load(cls, path, included_header=False, **kwargs):
+        """Load an image from a given file"""
+        with open(path, 'rb') as f:
+            payload = f.read()
+        obj = cls(**kwargs)
+        obj.payload = payload
+
+        # Add the image header if needed.
+        if not included_header and obj.header_size > 0:
+            obj.payload = (b'\000' * obj.header_size) + obj.payload
+
+        obj.check()
+        return obj
+
+    def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0):
+        self.version = version or versmod.decode_version("0")
+        self.header_size = header_size or IMAGE_HEADER_SIZE
+        self.pad = pad
+
+    def __repr__(self):
+        return "<Image version={}, header_size={}, pad={}, payloadlen=0x{:x}>".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 for v in self.payload[0:self.header_size]):
+                raise Exception("Padding requested, but image does not start with zeros")
+
+    def sign(self, key):
+        self.add_header(key)
+
+        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()
+
+        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):
+        """Install the image header.
+
+        The key is needed to know the type of signature, and
+        approximate the size of the signature."""
+
+        flags = 0
+        tlvsz = 0
+        if key is not None:
+            tlvsz += TLV_HEADER_SIZE + key.sig_len()
+
+        tlvsz += 4 + hashlib.sha256().digest_size
+        tlvsz += 4 + hashlib.sha256().digest_size
+
+        fmt = ('<' +
+            # type ImageHdr struct {
+            'I' +   # Magic uint32
+            'H' +   # TlvSz uint16
+            'B' +   # KeyId uint8
+            'B' +   # Pad1  uint8
+            'H' +   # HdrSz uint16
+            'H' +   # Pad2  uint16
+            'I' +   # ImgSz uint32
+            'I' +   # Flags uint32
+            'BBHI' + # Vers  ImageVersion
+            'I'     # Pad3  uint32
+            ) # }
+        assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
+        header = struct.pack(fmt,
+                IMAGE_MAGIC,
+                tlvsz, # TlvSz
+                0, # KeyId (TODO: allow other ids)
+                0,  # Pad1
+                self.header_size,
+                0, # Pad2
+                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) # Pad3
+        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
diff --git a/bl2/ext/mcuboot/scripts/imgtool/keys.py b/bl2/ext/mcuboot/scripts/imgtool/keys.py
new file mode 100644
index 0000000..ee54a0f
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/imgtool/keys.py
@@ -0,0 +1,183 @@
+# 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.
+
+"""
+Cryptographic key management for imgtool.
+"""
+
+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
+
+# 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 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:
+            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):
+        sha = SHA256.new(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
+
+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()
+    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:
+        key = SigningKey.from_pem(pem)
+        if key.curve.name != 'NIST256p':
+            raise Exception("Unsupported ECDSA curve")
+        return ECDSA256P1(key)
diff --git a/bl2/ext/mcuboot/scripts/imgtool/version.py b/bl2/ext/mcuboot/scripts/imgtool/version.py
new file mode 100644
index 0000000..64962e9
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/imgtool/version.py
@@ -0,0 +1,47 @@
+# 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.
+
+"""
+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'])
+
+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)
+    # print("decode:", text, m.groups())
+    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"))