Browse Source
This commit adds support to stm32's mboot for signe, encrypted and compressed DFU updates. It is based on inital work done by Andrew Leech. The feature is enabled by setting MBOOT_ENABLE_PACKING to 1 in the board's mpconfigboard.mk file, and by providing a header file in the board folder (usually called mboot_keys.h) with a set of signing and encryption keys (which can be generated by mboot_pack_dfu.py). The signing and encryption is provided by libhydrogen. Compression is provided by uzlib. Enabling packing costs about 3k of flash. The included mboot_pack_dfu.py script converts a .dfu file to a .pack.dfu file which can be subsequently deployed to a board with mboot in packing mode. This .pack.dfu file is created as follows: - the firmware from the original .dfu is split into chunks (so the decryption can fit in RAM) - each chunk is compressed, encrypted, a header added, then signed - a special final chunk is added with a signature of the entire firmware - all chunks are concatenated to make the final .pack.dfu file The .pack.dfu file can be deployed over USB or from the internal filesystem on the device (if MBOOT_FSLOAD is enabled). See #5267 and #5309 for additional discussion. Signed-off-by: Damien George <damien@micropython.org>pull/6771/head
Damien George
4 years ago
18 changed files with 844 additions and 31 deletions
@ -0,0 +1,10 @@ |
|||
// Header for libhydrogen use only. Act like a Particle board for the random
|
|||
// implementation. This code is not actually called when just decrypting and
|
|||
// verifying a signature, but a correct implementation is provided anyway.
|
|||
|
|||
#include "py/mphal.h" |
|||
#include "rng.h" |
|||
|
|||
static inline uint32_t HAL_RNG_GetRandomNumber(void) { |
|||
return rng_get(); |
|||
} |
@ -0,0 +1,260 @@ |
|||
# This file is part of the MicroPython project, http://micropython.org/ |
|||
# |
|||
# The MIT License (MIT) |
|||
# |
|||
# Copyright (c) 2020-2021 Damien P. George |
|||
# |
|||
# Permission is hereby granted, free of charge, to any person obtaining a copy |
|||
# of this software and associated documentation files (the "Software"), to deal |
|||
# in the Software without restriction, including without limitation the rights |
|||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
|||
# copies of the Software, and to permit persons to whom the Software is |
|||
# furnished to do so, subject to the following conditions: |
|||
# |
|||
# The above copyright notice and this permission notice shall be included in |
|||
# all copies or substantial portions of the Software. |
|||
# |
|||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
|||
# THE SOFTWARE. |
|||
""" |
|||
Utility to create compressed, encrypted and signed DFU files. |
|||
""" |
|||
|
|||
import argparse |
|||
import os |
|||
import re |
|||
import struct |
|||
import sys |
|||
import zlib |
|||
|
|||
sys.path.append(os.path.dirname(__file__) + "/../../../tools") |
|||
import dfu |
|||
|
|||
try: |
|||
import pyhy |
|||
except ImportError: |
|||
raise SystemExit( |
|||
"ERROR: pyhy not found. Please install python pyhy for encrypted mboot support: pip3 install pyhy" |
|||
) |
|||
|
|||
|
|||
# Currenty supported version of a packed DFU file. |
|||
MBOOT_PACK_HEADER_VERSION = 1 |
|||
|
|||
# Must match MBOOT_PACK_HYDRO_CONTEXT in mboot/pack.h |
|||
MBOOT_PACK_HYDRO_CONTEXT = "mbootenc" |
|||
|
|||
# Must match enum in mboot/pack.h. |
|||
MBOOT_PACK_CHUNK_META = 0 |
|||
MBOOT_PACK_CHUNK_FULL_SIG = 1 |
|||
MBOOT_PACK_CHUNK_FW_RAW = 2 |
|||
MBOOT_PACK_CHUNK_FW_GZIP = 3 |
|||
|
|||
|
|||
class Keys: |
|||
def __init__(self, filename): |
|||
self.filename = filename |
|||
|
|||
def generate(self): |
|||
kp = pyhy.hydro_sign_keygen() |
|||
self.sign_sk = kp.sk |
|||
self.sign_pk = kp.pk |
|||
self.secretbox = pyhy.hydro_secretbox_keygen() |
|||
|
|||
def _save_data(self, name, data, file_, hide=False): |
|||
prefix = "//" if hide else "" |
|||
data = ",".join("0x{:02x}".format(b) for b in data) |
|||
file_.write("{}const uint8_t {}[] = {{{}}};\n".format(prefix, name, data)) |
|||
|
|||
def _load_data(self, name, line): |
|||
line = line.split(name + "[] = ") |
|||
if len(line) != 2: |
|||
raise Exception("malformed input keys: {}".format(line)) |
|||
data = line[1].strip() |
|||
return bytes(int(value, 16) for value in data[1:-2].split(",")) |
|||
|
|||
def save(self): |
|||
with open(self.filename, "w") as f: |
|||
self._save_data("mboot_pack_sign_secret_key", self.sign_sk, f, hide=True) |
|||
self._save_data("mboot_pack_sign_public_key", self.sign_pk, f) |
|||
self._save_data("mboot_pack_secretbox_key", self.secretbox, f) |
|||
|
|||
def load(self): |
|||
with open(self.filename) as f: |
|||
self.sign_sk = self._load_data("mboot_pack_sign_secret_key", f.readline()) |
|||
self.sign_pk = self._load_data("mboot_pack_sign_public_key", f.readline()) |
|||
self.secretbox = self._load_data("mboot_pack_secretbox_key", f.readline()) |
|||
|
|||
|
|||
def dfu_read(filename): |
|||
elems = [] |
|||
|
|||
with open(filename, "rb") as f: |
|||
hdr = f.read(11) |
|||
sig, ver, size, num_targ = struct.unpack("<5sBIB", hdr) |
|||
file_offset = 11 |
|||
|
|||
for i in range(num_targ): |
|||
hdr = f.read(274) |
|||
sig, alt, has_name, name, t_size, num_elem = struct.unpack("<6sBi255sII", hdr) |
|||
|
|||
file_offset += 274 |
|||
file_offset_t = file_offset |
|||
for j in range(num_elem): |
|||
hdr = f.read(8) |
|||
addr, e_size = struct.unpack("<II", hdr) |
|||
data = f.read(e_size) |
|||
elems.append((addr, data)) |
|||
file_offset += 8 + e_size |
|||
|
|||
if t_size != file_offset - file_offset_t: |
|||
raise Exception("corrupt DFU {} {}".format(t_size, file_offset - file_offset_t)) |
|||
|
|||
if size != file_offset: |
|||
raise Exception("corrupt DFU {} {}".format(size, file_offset)) |
|||
|
|||
hdr = f.read(16) |
|||
hdr = struct.unpack("<HHHH3sBI", hdr) |
|||
vid_pid = "0x{:04x}:0x{:04x}".format(hdr[2], hdr[1]) |
|||
|
|||
return vid_pid, elems |
|||
|
|||
|
|||
def compress(data): |
|||
c = zlib.compressobj(level=9, memLevel=9, wbits=-15) # wsize=15, no header |
|||
return c.compress(data) + c.flush() |
|||
|
|||
|
|||
def encrypt(keys, data): |
|||
return pyhy.hydro_secretbox_encrypt(data, 0, MBOOT_PACK_HYDRO_CONTEXT, keys.secretbox) |
|||
|
|||
|
|||
def sign(keys, data): |
|||
return pyhy.hydro_sign_create(data, MBOOT_PACK_HYDRO_CONTEXT, keys.sign_sk) |
|||
|
|||
|
|||
def pack_chunk(keys, format_, chunk_addr, chunk_payload): |
|||
header = struct.pack( |
|||
"<BBBBII", MBOOT_PACK_HEADER_VERSION, format_, 0, 0, chunk_addr, len(chunk_payload) |
|||
) |
|||
chunk = header + chunk_payload |
|||
sig = sign(keys, chunk) |
|||
chunk = chunk + sig |
|||
return chunk |
|||
|
|||
|
|||
def data_chunks(data, n): |
|||
for i in range(0, len(data), n): |
|||
yield data[i : i + n] |
|||
|
|||
|
|||
def generate_keys(keys, args): |
|||
keys.generate() |
|||
keys.save() |
|||
|
|||
|
|||
def pack_dfu(keys, args): |
|||
chunk_size = int(args.chunk_size[0]) |
|||
|
|||
# Load previously generated keys. |
|||
keys.load() |
|||
|
|||
# Read the input DFU file. |
|||
vid_pid, elems = dfu_read(args.infile[0]) |
|||
|
|||
# Ensure firmware sections are processed in order of destination memory address. |
|||
elems = sorted(elems, key=lambda e: e[0]) |
|||
|
|||
# Build list of packed chunks. |
|||
target = [] |
|||
full_fw = b"" |
|||
full_signature_payload = b"" |
|||
for address, fw in elems: |
|||
# Update full firmware and full signature chunk. |
|||
full_fw += fw |
|||
full_signature_payload += struct.pack("<II", address, len(fw)) |
|||
|
|||
# Split the firmware into chunks, encrypt and sign the chunks |
|||
# then register them as individual DFU targets. |
|||
for i, chunk in enumerate(data_chunks(fw, chunk_size)): |
|||
chunk_addr = address + i * chunk_size |
|||
if args.gzip: |
|||
chunk = compress(chunk) |
|||
chunk = encrypt(keys, chunk) |
|||
chunk = pack_chunk( |
|||
keys, |
|||
MBOOT_PACK_CHUNK_FW_GZIP if args.gzip else MBOOT_PACK_CHUNK_FW_RAW, |
|||
chunk_addr, |
|||
chunk, |
|||
) |
|||
target.append({"address": chunk_addr, "data": chunk}) |
|||
|
|||
# Add full signature to targets, at location following the last chunk. |
|||
chunk_addr += chunk_size |
|||
sig = sign(keys, full_fw) |
|||
full_signature_payload += sig |
|||
full_signature_chunk = pack_chunk( |
|||
keys, MBOOT_PACK_CHUNK_FULL_SIG, chunk_addr, full_signature_payload |
|||
) |
|||
target.append({"address": chunk_addr, "data": full_signature_chunk}) |
|||
|
|||
# Build the packed DFU file of all the encrypted and signed chunks. |
|||
dfu.build(args.outfile[0], [target], vid_pid) |
|||
|
|||
# Verify the packed DFU file. |
|||
verify_pack_dfu(keys, args.outfile[0]) |
|||
|
|||
|
|||
def verify_pack_dfu(keys, filename): |
|||
full_sig = pyhy.hydro_sign(MBOOT_PACK_HYDRO_CONTEXT) |
|||
_, elems = dfu_read(filename) |
|||
for addr, data in elems: |
|||
header = struct.unpack("<BBBBII", data[:12]) |
|||
chunk = data[12 : 12 + header[5]] |
|||
sig = data[12 + header[5] :] |
|||
sig_pass = pyhy.hydro_sign_verify( |
|||
sig, data[:12] + chunk, MBOOT_PACK_HYDRO_CONTEXT, keys.sign_pk |
|||
) |
|||
assert sig_pass |
|||
if header[1] == MBOOT_PACK_CHUNK_FULL_SIG: |
|||
actual_sig = chunk[-64:] |
|||
else: |
|||
chunk = pyhy.hydro_secretbox_decrypt( |
|||
chunk, 0, MBOOT_PACK_HYDRO_CONTEXT, keys.secretbox |
|||
) |
|||
assert chunk is not None |
|||
if header[1] == MBOOT_PACK_CHUNK_FW_GZIP: |
|||
chunk = zlib.decompress(chunk, wbits=-15) |
|||
full_sig.update(chunk) |
|||
full_sig_pass = full_sig.final_verify(actual_sig, keys.sign_pk) |
|||
assert full_sig_pass |
|||
|
|||
|
|||
def main(): |
|||
cmd_parser = argparse.ArgumentParser(description="Build signed/encrypted DFU files") |
|||
cmd_parser.add_argument("-k", "--keys", default="mboot_keys.h", help="filename for keys") |
|||
subparsers = cmd_parser.add_subparsers() |
|||
|
|||
parser_gk = subparsers.add_parser("generate-keys", help="generate keys") |
|||
parser_gk.set_defaults(func=generate_keys) |
|||
|
|||
parser_ed = subparsers.add_parser("pack-dfu", help="encrypt and sign a DFU file") |
|||
parser_ed.add_argument("-z", "--gzip", action="store_true", help="compress chunks") |
|||
parser_ed.add_argument("chunk_size", nargs=1, help="maximum size in bytes of each chunk") |
|||
parser_ed.add_argument("infile", nargs=1, help="input DFU file") |
|||
parser_ed.add_argument("outfile", nargs=1, help="output DFU file") |
|||
parser_ed.set_defaults(func=pack_dfu) |
|||
|
|||
args = cmd_parser.parse_args() |
|||
|
|||
keys = Keys(args.keys) |
|||
args.func(keys, args) |
|||
|
|||
|
|||
if __name__ == "__main__": |
|||
main() |
@ -0,0 +1,282 @@ |
|||
/*
|
|||
* This file is part of the MicroPython project, http://micropython.org/
|
|||
* |
|||
* The MIT License (MIT) |
|||
* |
|||
* Copyright (c) 2020-2021 Damien P. George |
|||
* |
|||
* Permission is hereby granted, free of charge, to any person obtaining a copy |
|||
* of this software and associated documentation files (the "Software"), to deal |
|||
* in the Software without restriction, including without limitation the rights |
|||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
|||
* copies of the Software, and to permit persons to whom the Software is |
|||
* furnished to do so, subject to the following conditions: |
|||
* |
|||
* The above copyright notice and this permission notice shall be included in |
|||
* all copies or substantial portions of the Software. |
|||
* |
|||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
|||
* THE SOFTWARE. |
|||
*/ |
|||
|
|||
#include <string.h> |
|||
|
|||
#include "dfu.h" |
|||
#include "gzstream.h" |
|||
#include "mboot.h" |
|||
#include "pack.h" |
|||
|
|||
#if MBOOT_ENABLE_PACKING |
|||
|
|||
// Keys provided externally by the board, will be built into mboot flash.
|
|||
#include MBOOT_PACK_KEYS_FILE |
|||
|
|||
// Encrypted dfu files using gzip require a decompress buffer. Larger can be faster.
|
|||
// This setting is independent to the incoming encrypted/signed/compressed DFU file.
|
|||
#ifndef MBOOT_PACK_GZIP_BUFFER_SIZE |
|||
#define MBOOT_PACK_GZIP_BUFFER_SIZE (2048) |
|||
#endif |
|||
|
|||
// State to manage automatic flash erasure.
|
|||
static uint32_t erased_base_addr; |
|||
static uint32_t erased_top_addr; |
|||
|
|||
// DFU chunk buffer, used to cache incoming blocks of data from USB.
|
|||
static uint32_t firmware_chunk_base_addr; |
|||
static mboot_pack_chunk_buf_t firmware_chunk_buf; |
|||
|
|||
// Temporary buffer for decrypted data.
|
|||
static uint8_t decrypted_buf[MBOOT_PACK_DFU_CHUNK_BUF_SIZE] __attribute__((aligned(8))); |
|||
|
|||
// Temporary buffer for uncompressing.
|
|||
static uint8_t uncompressed_buf[MBOOT_PACK_GZIP_BUFFER_SIZE] __attribute__((aligned(8))); |
|||
|
|||
// Buffer to hold the start of the firmware, which is only written once the
|
|||
// entire firmware is validated. This is 8 bytes due to STM32WB MCUs requiring
|
|||
// that a double-word write to flash can only be done once (due to ECC).
|
|||
static uint8_t firmware_head[8]; |
|||
|
|||
void mboot_pack_init(void) { |
|||
erased_base_addr = 0; |
|||
erased_top_addr = 0; |
|||
firmware_chunk_base_addr = 0; |
|||
} |
|||
|
|||
// In encrypted mode the erase is automatically managed.
|
|||
// Note: this scheme requires blocks be written in sequence, which is the case.
|
|||
static int mboot_pack_erase(uint32_t addr, size_t len) { |
|||
while (!(erased_base_addr <= addr && addr + len <= erased_top_addr)) { |
|||
uint32_t erase; |
|||
if (erased_base_addr <= addr && addr < erased_top_addr) { |
|||
erase = erased_top_addr; |
|||
} else { |
|||
erase = addr; |
|||
erased_base_addr = addr; |
|||
} |
|||
uint32_t next_addr; |
|||
int ret = hw_page_erase(erase, &next_addr); |
|||
if (ret != 0) { |
|||
return ret; |
|||
} |
|||
erased_top_addr = next_addr; |
|||
} |
|||
return 0; |
|||
} |
|||
|
|||
// Commit an unencrypted and uncompressed chunk of firmware to the flash.
|
|||
static int mboot_pack_commit_chunk(uint32_t addr, uint8_t *data, size_t len) { |
|||
// Erase any required sectors before writing.
|
|||
int ret = mboot_pack_erase(addr, len); |
|||
if (ret != 0) { |
|||
return ret; |
|||
} |
|||
|
|||
if (addr == APPLICATION_ADDR) { |
|||
// Don't write the very start of the firmware, just copy it into a temporary buffer.
|
|||
// It will be written only if the full firmware passes the checksum/signature.
|
|||
memcpy(firmware_head, data, sizeof(firmware_head)); |
|||
addr += sizeof(firmware_head); |
|||
data += sizeof(firmware_head); |
|||
len -= sizeof(firmware_head); |
|||
} |
|||
|
|||
// Commit this piece of the firmware.
|
|||
return hw_write(addr, data, len); |
|||
} |
|||
|
|||
// Handle a chunk with the full firmware signature.
|
|||
static int mboot_pack_handle_full_sig(void) { |
|||
if (firmware_chunk_buf.header.length < hydro_sign_BYTES) { |
|||
return -1; |
|||
} |
|||
|
|||
uint8_t *full_sig = &firmware_chunk_buf.data[firmware_chunk_buf.header.length - hydro_sign_BYTES]; |
|||
uint32_t *region_data = (uint32_t *)&firmware_chunk_buf.data[0]; |
|||
size_t num_regions = (full_sig - (uint8_t *)region_data) / sizeof(uint32_t) / 2; |
|||
|
|||
uint8_t *buf = decrypted_buf; |
|||
const size_t buf_alloc = sizeof(decrypted_buf); |
|||
|
|||
// Compute the signature of the full firmware.
|
|||
hydro_sign_state sign_state; |
|||
hydro_sign_init(&sign_state, MBOOT_PACK_HYDRO_CONTEXT); |
|||
for (size_t region = 0; region < num_regions; ++region) { |
|||
uint32_t addr = region_data[2 * region]; |
|||
uint32_t len = region_data[2 * region + 1]; |
|||
while (len) { |
|||
uint32_t l = len <= buf_alloc ? len : buf_alloc; |
|||
hw_read(addr, l, buf); |
|||
if (addr == APPLICATION_ADDR) { |
|||
// The start of the firmware was not yet written to flash so copy
|
|||
// it out of the temporary buffer to compute the full signature.
|
|||
memcpy(buf, firmware_head, sizeof(firmware_head)); |
|||
} |
|||
int ret = hydro_sign_update(&sign_state, buf, l); |
|||
if (ret != 0) { |
|||
return -1; |
|||
} |
|||
addr += l; |
|||
len -= l; |
|||
} |
|||
} |
|||
|
|||
// Verify the signature of the full firmware.
|
|||
int ret = hydro_sign_final_verify(&sign_state, full_sig, mboot_pack_sign_public_key); |
|||
if (ret != 0) { |
|||
dfu_context.status = DFU_STATUS_ERROR_VERIFY; |
|||
dfu_context.error = MBOOT_ERROR_STR_INVALID_SIG_IDX; |
|||
return -1; |
|||
} |
|||
|
|||
// Full firmware passed the signature check.
|
|||
// Write the start of the firmware so it boots.
|
|||
return hw_write(APPLICATION_ADDR, firmware_head, sizeof(firmware_head)); |
|||
} |
|||
|
|||
// Handle a chunk with firmware data.
|
|||
static int mboot_pack_handle_firmware(void) { |
|||
const uint8_t *fw_data = &firmware_chunk_buf.data[0]; |
|||
const size_t fw_len = firmware_chunk_buf.header.length; |
|||
|
|||
// Decrypt the chunk.
|
|||
if (hydro_secretbox_decrypt(decrypted_buf, fw_data, fw_len, 0, MBOOT_PACK_HYDRO_CONTEXT, mboot_pack_secretbox_key) != 0) { |
|||
dfu_context.status = DFU_STATUS_ERROR_VERIFY; |
|||
dfu_context.error = MBOOT_ERROR_STR_INVALID_SIG_IDX; |
|||
return -1; |
|||
} |
|||
|
|||
// Use the decrypted message contents going formward.
|
|||
size_t len = fw_len - hydro_secretbox_HEADERBYTES; |
|||
uint32_t addr = firmware_chunk_buf.header.address; |
|||
|
|||
if (firmware_chunk_buf.header.format == MBOOT_PACK_CHUNK_FW_GZIP) { |
|||
// Decompress chunk data.
|
|||
gz_stream_init_from_raw_data(decrypted_buf, len); |
|||
for (;;) { |
|||
int read = gz_stream_read(sizeof(uncompressed_buf), uncompressed_buf); |
|||
if (read == 0) { |
|||
return 0; // finished decompressing
|
|||
} else if (read < 0) { |
|||
return -1; // error reading
|
|||
} |
|||
int ret = mboot_pack_commit_chunk(addr, uncompressed_buf, read); |
|||
if (ret != 0) { |
|||
return ret; |
|||
} |
|||
addr += read; |
|||
} |
|||
} else { |
|||
// Commit chunk data directly.
|
|||
return mboot_pack_commit_chunk(addr, decrypted_buf, len); |
|||
} |
|||
} |
|||
|
|||
int mboot_pack_write(uint32_t addr, const uint8_t *src8, size_t len) { |
|||
if (addr == APPLICATION_ADDR) { |
|||
// Base address of main firmware, reset any previous state
|
|||
firmware_chunk_base_addr = 0; |
|||
} |
|||
|
|||
if (firmware_chunk_base_addr == 0) { |
|||
// First piece of data starting a new chunk, so set the base address.
|
|||
firmware_chunk_base_addr = addr; |
|||
} |
|||
|
|||
if (addr < firmware_chunk_base_addr) { |
|||
// Address out of range.
|
|||
firmware_chunk_base_addr = 0; |
|||
return -1; |
|||
} |
|||
|
|||
size_t offset = addr - firmware_chunk_base_addr; |
|||
if (offset + len > sizeof(firmware_chunk_buf)) { |
|||
// Address/length out of range.
|
|||
firmware_chunk_base_addr = 0; |
|||
return -1; |
|||
} |
|||
|
|||
// Copy in the new data piece into the chunk buffer.
|
|||
memcpy((uint8_t *)&firmware_chunk_buf + offset, src8, len); |
|||
|
|||
if (offset + len < sizeof(firmware_chunk_buf.header)) { |
|||
// Don't have the header yet.
|
|||
return 0; |
|||
} |
|||
|
|||
if (firmware_chunk_buf.header.header_vers != MBOOT_PACK_HEADER_VERSION) { |
|||
// Chunk header has the wrong version.
|
|||
dfu_context.status = DFU_STATUS_ERROR_FILE; |
|||
dfu_context.error = MBOOT_ERROR_STR_INVALID_SIG_IDX; |
|||
return -1; |
|||
} |
|||
|
|||
if (firmware_chunk_buf.header.address != firmware_chunk_base_addr) { |
|||
// Chunk address doesn't agree with dfu address, abort.
|
|||
dfu_context.status = DFU_STATUS_ERROR_ADDRESS; |
|||
dfu_context.error = MBOOT_ERROR_STR_INVALID_SIG_IDX; |
|||
return -1; |
|||
} |
|||
|
|||
if (offset + len < sizeof(firmware_chunk_buf.header) + firmware_chunk_buf.header.length + sizeof(firmware_chunk_buf.signature)) { |
|||
// Don't have the full chunk yet.
|
|||
return 0; |
|||
} |
|||
|
|||
// Have the full chunk in firmware_chunk_buf, process it now.
|
|||
|
|||
// Reset the chunk base address for the next chunk that comes in.
|
|||
firmware_chunk_base_addr = 0; |
|||
|
|||
// Verify the signature of the chunk.
|
|||
const size_t fw_len = firmware_chunk_buf.header.length; |
|||
const uint8_t *sig = &firmware_chunk_buf.data[0] + fw_len; |
|||
if (hydro_sign_verify(sig, &firmware_chunk_buf, sizeof(firmware_chunk_buf.header) + fw_len, |
|||
MBOOT_PACK_HYDRO_CONTEXT, mboot_pack_sign_public_key) != 0) { |
|||
// Signature failed
|
|||
dfu_context.status = DFU_STATUS_ERROR_VERIFY; |
|||
dfu_context.error = MBOOT_ERROR_STR_INVALID_SIG_IDX; |
|||
return -1; |
|||
} |
|||
|
|||
// Signature passed, we have valid chunk.
|
|||
|
|||
if (firmware_chunk_buf.header.format == MBOOT_PACK_CHUNK_META) { |
|||
// Ignore META chunks.
|
|||
return 0; |
|||
} else if (firmware_chunk_buf.header.format == MBOOT_PACK_CHUNK_FULL_SIG) { |
|||
return mboot_pack_handle_full_sig(); |
|||
} else if (firmware_chunk_buf.header.format == MBOOT_PACK_CHUNK_FW_RAW |
|||
|| firmware_chunk_buf.header.format == MBOOT_PACK_CHUNK_FW_GZIP) { |
|||
return mboot_pack_handle_firmware(); |
|||
} else { |
|||
// Unsupported contents.
|
|||
return -1; |
|||
} |
|||
} |
|||
|
|||
#endif // MBOOT_ENABLE_PACKING
|
@ -0,0 +1,82 @@ |
|||
/*
|
|||
* This file is part of the MicroPython project, http://micropython.org/
|
|||
* |
|||
* The MIT License (MIT) |
|||
* |
|||
* Copyright (c) 2017-2019 Damien P. George |
|||
* |
|||
* Permission is hereby granted, free of charge, to any person obtaining a copy |
|||
* of this software and associated documentation files (the "Software"), to deal |
|||
* in the Software without restriction, including without limitation the rights |
|||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
|||
* copies of the Software, and to permit persons to whom the Software is |
|||
* furnished to do so, subject to the following conditions: |
|||
* |
|||
* The above copyright notice and this permission notice shall be included in |
|||
* all copies or substantial portions of the Software. |
|||
* |
|||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
|||
* THE SOFTWARE. |
|||
*/ |
|||
#ifndef MICROPY_INCLUDED_STM32_MBOOT_PACK_H |
|||
#define MICROPY_INCLUDED_STM32_MBOOT_PACK_H |
|||
|
|||
#include <stdint.h> |
|||
#include "py/mphal.h" |
|||
|
|||
#if MBOOT_ENABLE_PACKING |
|||
|
|||
#include "lib/libhydrogen/hydrogen.h" |
|||
|
|||
// Encrypted & signed bootloader support
|
|||
|
|||
/******************************************************************************/ |
|||
// Interface
|
|||
|
|||
#define MBOOT_PACK_HEADER_VERSION (1) |
|||
|
|||
// Used by libhydrogen for signing and secretbox context.
|
|||
#define MBOOT_PACK_HYDRO_CONTEXT "mbootenc" |
|||
|
|||
// Maximum size of the firmware payload.
|
|||
#define MBOOT_PACK_DFU_CHUNK_BUF_SIZE (MBOOT_PACK_CHUNKSIZE + hydro_secretbox_HEADERBYTES) |
|||
|
|||
enum mboot_pack_chunk_format { |
|||
MBOOT_PACK_CHUNK_META = 0, |
|||
MBOOT_PACK_CHUNK_FULL_SIG = 1, |
|||
MBOOT_PACK_CHUNK_FW_RAW = 2, |
|||
MBOOT_PACK_CHUNK_FW_GZIP = 3, |
|||
}; |
|||
|
|||
// Each DFU chunk transfered has this header to validate it.
|
|||
|
|||
typedef struct _mboot_pack_chunk_buf_t { |
|||
struct { |
|||
uint8_t header_vers; |
|||
uint8_t format; // enum mboot_pack_chunk_format
|
|||
uint8_t _pad[2]; |
|||
uint32_t address; |
|||
uint32_t length; // number of bytes in following "data" payload, excluding "signature"
|
|||
} header; |
|||
uint8_t data[MBOOT_PACK_DFU_CHUNK_BUF_SIZE]; |
|||
uint8_t signature[hydro_sign_BYTES]; |
|||
} mboot_pack_chunk_buf_t; |
|||
|
|||
// Signing and encryption keys, stored in mboot flash, provided externally.
|
|||
extern const uint8_t mboot_pack_sign_public_key[hydro_sign_PUBLICKEYBYTES]; |
|||
extern const uint8_t mboot_pack_secretbox_key[hydro_secretbox_KEYBYTES]; |
|||
|
|||
/******************************************************************************/ |
|||
// Implementation
|
|||
|
|||
void mboot_pack_init(void); |
|||
int mboot_pack_write(uint32_t addr, const uint8_t *src8, size_t len); |
|||
|
|||
#endif // MBOOT_ENABLE_PACKING
|
|||
|
|||
#endif // MICROPY_INCLUDED_STM32_MBOOT_PACK_H
|
Loading…
Reference in new issue