Add some simple scripts for signing/flashing
These are some simple scripts for signing images (with an example with a
hardcoded path), a fixed root key that matches the one checked into the
code, and a few scripts to use the Segger debugger to flash the images.
diff --git a/scripts/flash.sh b/scripts/flash.sh
new file mode 100755
index 0000000..7353dd7
--- /dev/null
+++ b/scripts/flash.sh
@@ -0,0 +1,18 @@
+#! /bin/bash
+
+source $(dirname $0)/../target.sh
+
+lscript=/tmp/flash$$.jlink
+
+cat >$lscript <<EOF
+h
+r
+loadfile outdir/$BOARD/zephyr.bin $BASE_BOOT
+loadfile hello.signed.bin $BASE_SLOT0
+loadfile shell.signed.bin $BASE_SLOT1
+q
+EOF
+
+JLinkExe -device $SOC -si SWD -speed auto \
+ -CommanderScript $lscript
+rm $lscript
diff --git a/scripts/gdb-boot.sh b/scripts/gdb-boot.sh
new file mode 100755
index 0000000..dd8a34d
--- /dev/null
+++ b/scripts/gdb-boot.sh
@@ -0,0 +1,27 @@
+#! /bin/bash
+
+source $(dirname $0)/../target.sh
+
+gscript=/tmp/init$$.gdb
+
+cat > $gscript <<EOF
+target remote localhost:2331
+symbol-file outdir/$BOARD/zephyr.elf
+# symbol-file ../zephyr/samples/shell/outdir/$BOARD/zephyr.elf
+# dir apps/boot/src
+# dir libs/bootutil/src
+# dir hw/mcu/stm/stm32f4xx/src
+b main
+# b __reset
+# b bootutil_img_validate
+# b cmp_rsasig
+# b bootutil_verify_sig
+# b mbedtls_rsa_public
+# b boot_calloc
+mon reset 2
+layout src
+focus cmd
+EOF
+
+$gdbexe -x $gscript
+rm $gscript
diff --git a/scripts/jgdb.sh b/scripts/jgdb.sh
new file mode 100755
index 0000000..a79c87c
--- /dev/null
+++ b/scripts/jgdb.sh
@@ -0,0 +1,6 @@
+#! /bin/bash
+
+source $(dirname $0)/../target.sh
+
+# Start the jlink gdb server
+JLinkGDBServer -if swd -device $SOC -speed auto
diff --git a/scripts/jl.sh b/scripts/jl.sh
new file mode 100755
index 0000000..260206d
--- /dev/null
+++ b/scripts/jl.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+
+source $(dirname $0)/../target.sh
+
+JLinkExe -speed auto -si SWD -device $SOC
diff --git a/scripts/newtimg.py b/scripts/newtimg.py
new file mode 100644
index 0000000..1e968d7
--- /dev/null
+++ b/scripts/newtimg.py
@@ -0,0 +1,67 @@
+# BOOT_IMG_MAGIC = 0x12344321
+BOOT_IMG_MAGIC = [ 0xf395c277, 0x7fefd260, 0x0f505235, 0x8079b62c ]
+IMAGE_MAGIC = 0x96f3b83c
+IMAGE_MAGIC_NONE = 0xffffffff
+
+#
+# Image header flags.
+#
+IMAGE_F_PIC = 0x00000001
+IMAGE_F_SHA256 = 0x00000002 # Image contains hash TLV
+IMAGE_F_PKCS15_RSA2048_SHA256 = 0x00000004 # PKCS15 w/RSA and SHA
+IMAGE_F_ECDSA224_SHA256 = 0x00000008 # ECD
+IMAGE_HEADER_SIZE = 32
+
+# Digest sizes
+SHA256_DIGEST_SIZE = 32
+
+# Signature sizes
+RSA_SIZE = 256
+ECDSA_SIZE = 68
+
+#
+# Image trailer TLV types.
+#
+IMAGE_TLV_SHA256 = 1 # SHA256 of image hdr and body
+IMAGE_TLV_RSA2048 = 2 # RSA2048 of hash output
+IMAGE_TLV_ECDSA224 = 3 # ECDSA of hash output
+
+
+OFFSET_VECTOR_TABLE = 0x20
+OFFSET_IH_MAGIC = 0
+OFFSET_IH_TLV_SIZE = 4
+OFFSET_IH_KEY_ID = 6
+OFFSET_IH_PAD1 = 7
+OFFSET_IH_HDR_SIZE = 8
+OFFSET_IH_PAD2 = 10
+OFFSET_IH_IMG_SIZE = 12
+OFFSET_IH_FLAGS = 16
+OFFSET_IH_VER_MAJOR = 20
+OFFSET_IH_VER_MINOR = 21
+OFFSET_IH_REVISION = 22
+OFFSET_IH_BUILD_NUM = 24
+OFFSET_IH_PAD3 = 28
+#struct image_version { uint8_t iv_major; uint8_t iv_minor; uint16_t iv_revision;
+# uint32_t iv_build_num;
+#};
+#
+#/** Image header. All fields are in little endian byte order. */
+#struct image_header {
+# uint32_t ih_magic;
+# uint16_t ih_tlv_size; /* Trailing TLVs */
+# uint8_t ih_key_id;
+# uint8_t _pad1;
+# uint16_t ih_hdr_size;
+# uint16_t _pad2;
+# uint32_t ih_img_size; /* Does not include header. */
+# uint32_t ih_flags;
+# struct image_version ih_ver;
+# uint32_t _pad3;
+#};
+#
+#/** Image trailer TLV format. All fields in little endian. */
+#struct image_tlv {
+# uint8_t it_type;
+# uint8_t _pad;
+# uint16_t it_len;
+#};
diff --git a/scripts/newtimg.pyc b/scripts/newtimg.pyc
new file mode 100644
index 0000000..9bdc5c1
--- /dev/null
+++ b/scripts/newtimg.pyc
Binary files differ
diff --git a/scripts/zep2newt.py b/scripts/zep2newt.py
new file mode 100755
index 0000000..1b46465
--- /dev/null
+++ b/scripts/zep2newt.py
@@ -0,0 +1,220 @@
+#!/usr/bin/python2
+
+from __future__ import print_function
+
+import mmap
+import os
+import struct
+import sys
+from argparse import ArgumentParser
+import newtimg
+from ctypes import *
+from Crypto.Signature import PKCS1_v1_5
+from Crypto.Hash import SHA256
+from Crypto.PublicKey import RSA
+
+DEBUG = False
+
+def get_args():
+ parser = ArgumentParser(description='Script to create images on a format \
+ that Mynewts bootloader expects')
+
+ parser.add_argument('--bin', required=True, dest='binary_file', \
+ help='Name of *.bin file (input)')
+
+ parser.add_argument('--key', required=False, dest='key_file', \
+ help='Name of private key file (*.pem format)')
+
+ parser.add_argument('--out', required=False, dest='image_file', \
+ default='zephyr.img.bin', \
+ help='Name of *.img file (output)')
+
+ parser.add_argument('--sig', required=False, dest='sig_type', \
+ default='SHA256', \
+ help='Type of signature <SHA256|RSA|EC>')
+
+ parser.add_argument('--off', required=False, dest='flash_offs_addr', \
+ default='0x08020000', \
+ help='Offset for the binary in flash (at what address \
+ should it be flashed?)')
+
+ parser.add_argument('--word-size', required=False, dest='word_size',
+ default=1,
+ help='Writable size of flash device (1, 2, 4, or 8)')
+
+ parser.add_argument('--vtoff', required=False, dest='vtable_offs', \
+ default=str(hex(newtimg.OFFSET_VECTOR_TABLE)), \
+ help='Offset to vector table in HEX (default: 0x80)')
+
+ parser.add_argument('--pad', required=False, \
+ help='Pad file with 0xff up to this size (in hex)')
+
+ parser.add_argument('--bit', required=False, action="store_true", \
+ default=False, \
+ help='Whether to add the Boot Image Trailer to the \
+ padded image or not (default: False)')
+
+ parser.add_argument('--verbose', required=False, action="store_true", \
+ default=False, \
+ help='Enable verbose mode')
+
+ parser.add_argument('--version', action='version', version='%(prog)s 1.0')
+
+ parser.add_argument('-f', required=False, action="store_true", \
+ default=False, \
+ help='Flash using JLinkExe')
+
+ return parser.parse_args()
+
+def trailer_size(word_size):
+ """
+ Compute the size of the image trailer.
+
+ The image trailer size depends on the writable unit size of the
+ flash in question. Given a word size of 1, 2, 4 or 8, return the
+ size, in bytes, of the image trailer. The magic number should be
+ placed at this particular offset from the end of the segment
+ """
+ sizes = { 1: 402, 2: 788, 4: 1560, 8: 3104 }
+ return sizes[word_size]
+
+class Signature(object):
+ """
+ Sign an image appropriately.
+ """
+
+ def compute(self, payload, key_file):
+ # Base computes sha256.
+ ctx = SHA256.new()
+ ctx.update(payload)
+ self.hash = ctx.digest()
+ self.ctx = ctx
+
+ def get_trailer(self):
+ return struct.pack('bxh32s', newtimg.IMAGE_TLV_SHA256,
+ len(self.hash),
+ self.hash)
+
+ def trailer_len(self):
+ return 32 + 4
+
+ def get_flags(self):
+ return newtimg.IMAGE_F_SHA256
+
+class RSASignature(Signature):
+
+ def compute(self, payload, key_file):
+ super(RSASignature, self).compute(payload, key_file)
+ with open(key_file, 'rb') as f:
+ rsa_key = RSA.importKey(f.read())
+ rsa = PKCS1_v1_5.new(rsa_key)
+ self.signature = rsa.sign(self.ctx)
+
+ def trailer_len(self):
+ return super(RSASignature, self).trailer_len() + newtimg.RSA_SIZE
+
+ def get_trailer(self):
+ buf = bytearray(super(RSASignature, self).get_trailer())
+ buf.extend(struct.pack('bxh', newtimg.IMAGE_TLV_RSA2048,
+ newtimg.RSA_SIZE))
+ buf.extend(self.signature)
+ return buf
+
+ def get_flags(self):
+ return newtimg.IMAGE_F_PKCS15_RSA2048_SHA256 | newtimg.IMAGE_F_SHA256
+
+sigs = {
+ 'SHA256': Signature,
+ 'RSA': RSASignature,
+ }
+
+class Convert():
+ def __init__(self, args):
+ self.args = args
+ if args.verbose:
+ for a in vars(args):
+ print("Arg -> {}: {}".format(a, getattr(args, a)))
+ self.debug = True
+ else:
+ self.debug = False
+
+ self.vtable_offs = int(args.vtable_offs, 16)
+ self.word_size = int(args.word_size)
+
+ self.load_image(args.binary_file)
+ self.validate_header()
+
+ sig = sigs[args.sig_type]()
+ header = self.make_header(sig)
+ assert len(header) == 32
+ self.image[:len(header)] = header
+
+ sig.compute(self.image, args.key_file)
+ self.trailer = sig.get_trailer()
+
+ self.image.extend(self.trailer)
+
+ if args.bit:
+ self.add_trailer(args.pad)
+
+ self.save_image(args.image_file)
+
+ def load_image(self, name):
+ with open(name, 'rb') as f:
+ image = f.read()
+ self.image = bytearray(image)
+
+ def save_image(self, name):
+ with open(name, 'wb') as f:
+ f.write(self.image)
+
+ def validate_header(self):
+ """Ensure that the image has space for a header
+
+ If the image is build with CONFIG_BOOT_HEADER off, the vector
+ table will be at the beginning, rather than the zero padding.
+ Verify that the padding is present.
+ """
+ if self.image[:self.vtable_offs] != bytearray(self.vtable_offs):
+ raise Exception("Image does not have space for header")
+
+ def make_header(self, sig):
+ image_size = len(self.image) - self.vtable_offs
+ tlv_size = sig.trailer_len()
+ key_id = 0
+ hd = struct.pack('IHBxHxxIIBBHI4x',
+ newtimg.IMAGE_MAGIC,
+ tlv_size,
+ key_id,
+ self.vtable_offs,
+ image_size,
+ sig.get_flags(),
+ 1, 0, 0, 0)
+ return hd
+
+ def add_trailer(self, pad):
+ """
+ Add the image trailer, to indicate to the bootloader that this
+ image should be flashed
+ """
+ if not pad:
+ raise Exception("Must specify image length with --pad to use --bit")
+ pad = int(pad, 16)
+
+ if len(self.image) > pad:
+ raise Exception("Image is too large for padding")
+
+ self.image.extend(b'\xFF' * (pad - len(self.image)))
+
+ magic = struct.pack('4I', *newtimg.BOOT_IMG_MAGIC)
+ pos = pad - trailer_size(self.word_size)
+ self.image[pos:pos + len(magic)] = magic
+
+def main(argv):
+ args = get_args()
+ erase = False
+
+ conv = Convert(args)
+
+if __name__ == "__main__":
+ main(sys.argv)