mirror of
https://github.com/mytechnotalent/Embedded-Hacking.git
synced 2026-10-19 05:57:34 +02:00
Add 0x0026a custom AES-128-CMAC secure bootloader, Week 11a notebook, and README links
This commit is contained in:
1 parent
b85aaf72d6
commit
bec685d573
33 files changed
+3451
No files matched your search
@@ -0,0 +1,2 @@
|
||||
build
|
||||
!.vscode/*
|
||||
Executable
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,89 @@
|
||||
# 0x0026a custom bootloader: builds a secure bootloader plus the signed
|
||||
# application it launches. Run from this directory:
|
||||
#
|
||||
# cmake -B build -G Ninja -DPICO_BOARD=pico2 \
|
||||
# -DPICO_SDK_PATH="$HOME/.pico-sdk/sdk/2.2.0" \
|
||||
# -DPICO_TOOLCHAIN_PATH="$HOME/.pico-sdk/toolchain/14_2_Rel1"
|
||||
# cmake --build build
|
||||
|
||||
cmake_minimum_required(VERSION 3.13)
|
||||
|
||||
set(CMAKE_C_STANDARD 11)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
# == DO NOT EDIT THE FOLLOWING LINES for the Raspberry Pi Pico VS Code Extension to work ==
|
||||
if(WIN32)
|
||||
set(USERHOME $ENV{USERPROFILE})
|
||||
else()
|
||||
set(USERHOME $ENV{HOME})
|
||||
endif()
|
||||
set(sdkVersion 2.2.0)
|
||||
set(toolchainVersion 14_2_Rel1)
|
||||
set(picotoolVersion 2.2.0-a4)
|
||||
set(picoVscode ${USERHOME}/.pico-sdk/cmake/pico-vscode.cmake)
|
||||
if (EXISTS ${picoVscode})
|
||||
include(${picoVscode})
|
||||
endif()
|
||||
# ====================================================================================
|
||||
set(PICO_BOARD pico2 CACHE STRING "Board type")
|
||||
|
||||
# Pull in Raspberry Pi Pico SDK (must be before project)
|
||||
include(pico_sdk_import.cmake)
|
||||
|
||||
project(0x0026a_custom_bootloader C CXX ASM)
|
||||
|
||||
# Initialise the Raspberry Pi Pico SDK
|
||||
pico_sdk_init()
|
||||
|
||||
# --- Bootloader: verifies an AES-128-CMAC tag before launching the app --------
|
||||
add_executable(0x0026a_bootloader
|
||||
bootloader/src/main.c
|
||||
bootloader/src/boot.c
|
||||
bootloader/src/manifest.c
|
||||
bootloader/src/aes_cmac.c
|
||||
bootloader/src/image.c
|
||||
bootloader/src/verify.c)
|
||||
|
||||
target_include_directories(0x0026a_bootloader PRIVATE
|
||||
${CMAKE_CURRENT_LIST_DIR}/bootloader/include
|
||||
${CMAKE_CURRENT_LIST_DIR}/common/include)
|
||||
|
||||
# pico_mbedtls provides the AES-128-CMAC implementation used for verification.
|
||||
target_link_libraries(0x0026a_bootloader PRIVATE
|
||||
pico_stdlib
|
||||
pico_mbedtls)
|
||||
|
||||
pico_enable_stdio_uart(0x0026a_bootloader 1)
|
||||
pico_enable_stdio_usb(0x0026a_bootloader 0)
|
||||
pico_add_extra_outputs(0x0026a_bootloader)
|
||||
|
||||
# --- Application: the 0x0026_functions firmware linked at 0x10020000 ----------
|
||||
add_executable(0x0026a_app
|
||||
app/src/app_main.c
|
||||
app/src/ir.c
|
||||
app/src/led.c
|
||||
app/src/secret.c)
|
||||
|
||||
target_include_directories(0x0026a_app PRIVATE
|
||||
${CMAKE_CURRENT_LIST_DIR}/app/include
|
||||
${CMAKE_CURRENT_LIST_DIR}/common/include)
|
||||
|
||||
# pico_mbedtls provides the AES-128-CBC API used by secret.c.
|
||||
target_link_libraries(0x0026a_app PRIVATE
|
||||
pico_stdlib
|
||||
pico_mbedtls)
|
||||
|
||||
pico_enable_stdio_uart(0x0026a_app 1)
|
||||
pico_enable_stdio_usb(0x0026a_app 0)
|
||||
|
||||
# Relocate the application into flash above the bootloader and manifest.
|
||||
pico_set_linker_script(0x0026a_app
|
||||
${CMAKE_CURRENT_LIST_DIR}/app/memmap_app.ld)
|
||||
|
||||
# The application starts at 0x10020000, so a UF2 (which BOOTSEL always writes to
|
||||
# 0x10000000) would be wrong. Emit the raw artifacts we flash with OpenOCD.
|
||||
pico_add_dis_output(0x0026a_app)
|
||||
pico_add_hex_output(0x0026a_app)
|
||||
pico_add_bin_output(0x0026a_app)
|
||||
pico_add_map_output(0x0026a_app)
|
||||
@@ -0,0 +1,60 @@
|
||||
# 0x0026a Custom AES-128-CMAC Secure Bootloader
|
||||
|
||||
This project builds a custom secure-boot chain for the Pico 2 (RP2350) that sits entirely above the ROM bootloader. A first-stage bootloader in XIP flash authenticates a signed application with AES-128-CMAC (RFC 4493) before jumping to it, and the signed application decrypts and prints a secret banner using the SDK Mbed TLS AES API.
|
||||
|
||||
## What You'll Learn
|
||||
|
||||
- Why a bootloader-only CRC/manifest is insufficient and what a MAC adds
|
||||
- How AES-128-CMAC works (K1/K2 subkeys) and the RFC 4493 test vectors
|
||||
- Custom linker-script editing (`pico_flash_region.ld`, `memmap_app.ld`) to relocate the app
|
||||
- Flashing three images (bootloader, manifest, app) with OpenOCD
|
||||
- Reverse engineering both images with GDB and Ghidra (find the key, IV, ciphertext, banner)
|
||||
|
||||
See the full tutorial: [WEEK11a.md](WEEK11a.md) / [WEEK11a.pdf](WEEK11a.pdf)
|
||||
|
||||
## Flash Map
|
||||
|
||||
| Region | Address | Content |
|
||||
| ---------- | ----------- | ------------------------------ |
|
||||
| Bootloader | `0x10000000` | 0x0026a bootloader (27772 B) |
|
||||
| Manifest | `0x1001F000` | header + AES-128-CMAC tag |
|
||||
| App | `0x10020000` | 0x0026a signed app (21656 B) |
|
||||
|
||||
The CMSIS-RM9 flash-safe range starts at `0x10000000` on the RP2350, so adding 2 MB relocates the app to `0x10020000`.
|
||||
|
||||
## Artifacts
|
||||
|
||||
| File | Description |
|
||||
| ---------------------------- | ---------------------------------------- |
|
||||
| `0x0026a_bootloader.bin` | Bootloader image (flash at `0x10000000`) |
|
||||
| `0x0026a_bootloader.uf2` | Bootloader for the BOOTSEL drag-and-drop |
|
||||
| `0x0026a_app.bin` | Signed app image (flash at `0x10020000`) |
|
||||
| `manifest.bin` | Manifest (flash at `0x1001F000`) |
|
||||
| `WEEK11a.md` / `WEEK11a.pdf` | Full lab notebook |
|
||||
|
||||
## Build
|
||||
|
||||
```sh
|
||||
cmake -B build -DPICO_SDK_PATH=~/.pico-sdk/sdk/2.2.0
|
||||
cmake --build build
|
||||
python3 tools/sign_firmware.py build/0x0026a_app.bin --out manifest.bin --key "IronNetBootKey!!" --app-base 0x10020000
|
||||
```
|
||||
|
||||
This produces `0x0026a_bootloader.bin/.uf2` and `0x0026a_app.bin`; the signer writes `manifest.bin`.
|
||||
|
||||
## Flash
|
||||
|
||||
```sh
|
||||
openocd -f interface/picoprobe.cfg -f target/rp2350.cfg -c \
|
||||
"program 0x0026a_bootloader.bin 0x10000000 verify; \
|
||||
program manifest.bin 0x1001F000 verify; \
|
||||
program 0x0026a_app.bin 0x10020000 verify; reset run; shutdown"
|
||||
```
|
||||
|
||||
## Verify at Runtime
|
||||
|
||||
Halt the core after boot and read the program counter. A valid signed image leaves PC inside the app (`0x100201xx`); a tampered or unsigned image leaves PC in the bootloader `boot_halt` idle loop near `0x10000eb2`.
|
||||
|
||||
## Disclaimers
|
||||
|
||||
This is an educational project for the Embedded-Hacking course. The key `IronNetBootKey!!` ships in the repo and is intentionally embedded in both images so it can be recovered with GDB/Ghidra. Do not use this scheme to protect real products.
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @file ir.h
|
||||
* @brief Header for NEC IR receiver (decoder) API
|
||||
* @author Kevin Thomas
|
||||
* @date 2025
|
||||
*
|
||||
* MIT License
|
||||
*
|
||||
* Copyright (c) 2025 Kevin Thomas
|
||||
*
|
||||
* 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 IR_H
|
||||
#define IR_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Initialize the IR receiver GPIO
|
||||
*
|
||||
* Configures the given `pin` as an input with pull-up for the NEC IR receiver.
|
||||
* Call this once during board initialization before calling `ir_getkey()`.
|
||||
*
|
||||
* @param pin GPIO pin number connected to IR receiver output
|
||||
*/
|
||||
void ir_init(uint8_t pin);
|
||||
|
||||
/**
|
||||
* @brief Blocking NEC IR decoder
|
||||
*
|
||||
* Blocks while waiting for a complete NEC frame. On success returns the
|
||||
* decoded command byte (0..255). On timeout or protocol error returns -1.
|
||||
*
|
||||
* @return decoded command byte (0..255) or -1 on failure
|
||||
*/
|
||||
int ir_getkey(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // IR_H
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @file led.h
|
||||
* @brief LED controller driven by decoded NEC IR commands.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#ifndef LED_H
|
||||
#define LED_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief LED controller state for the three IR-controlled LEDs.
|
||||
*
|
||||
* Maps each logical LED (1-3) to its GPIO pin and remembers whether the
|
||||
* LED is currently on. Build a default instance with led_default() and
|
||||
* drive it with led_init() and led_handle_ir().
|
||||
*/
|
||||
typedef struct {
|
||||
uint8_t led1_pin;
|
||||
uint8_t led2_pin;
|
||||
uint8_t led3_pin;
|
||||
bool led1_state;
|
||||
bool led2_state;
|
||||
bool led3_state;
|
||||
} simple_led_ctrl_t;
|
||||
|
||||
/**
|
||||
* @brief Build the default three-LED configuration (pins 16-18, all off).
|
||||
* @param void No parameters.
|
||||
* @return simple_led_ctrl_t Default LED controller state.
|
||||
*/
|
||||
simple_led_ctrl_t led_default(void);
|
||||
|
||||
/**
|
||||
* @brief Configure the three LED GPIO pins as outputs.
|
||||
* @param leds Pointer to the LED controller to initialize.
|
||||
* @return void No return value.
|
||||
*/
|
||||
void led_init(simple_led_ctrl_t *leds);
|
||||
|
||||
/**
|
||||
* @brief Dispatch a decoded NEC command to the matching LED.
|
||||
* @param leds Pointer to the LED controller to drive.
|
||||
* @param key Decoded NEC command byte, or a negative value to ignore.
|
||||
* @return void No return value.
|
||||
*/
|
||||
void led_handle_ir(simple_led_ctrl_t *leds, int key);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // LED_H
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* @file secret.h
|
||||
* @brief AES-128-CBC protected runtime banner for the application.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#ifndef SECRET_H
|
||||
#define SECRET_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/** @brief AES block size in bytes used by the runtime banner. */
|
||||
#define APP_AES_BLOCK 16U
|
||||
|
||||
/** @brief Length in bytes of the encrypted runtime banner. */
|
||||
#define APP_BANNER_LEN 32U
|
||||
|
||||
/**
|
||||
* @brief Decrypt the embedded AES-128-CBC banner and print it.
|
||||
* @param void No parameters.
|
||||
* @return int Zero on success, non-zero when decryption fails.
|
||||
*/
|
||||
int secret_print_banner(void);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,305 @@
|
||||
/* Based on GCC ARM embedded samples.
|
||||
Defines the following symbols for use by code:
|
||||
__exidx_start
|
||||
__exidx_end
|
||||
__etext
|
||||
__data_start__
|
||||
__preinit_array_start
|
||||
__preinit_array_end
|
||||
__init_array_start
|
||||
__init_array_end
|
||||
__fini_array_start
|
||||
__fini_array_end
|
||||
__data_end__
|
||||
__bss_start__
|
||||
__bss_end__
|
||||
__end__
|
||||
end
|
||||
__HeapLimit
|
||||
__StackLimit
|
||||
__StackTop
|
||||
__stack (== StackTop)
|
||||
*/
|
||||
|
||||
MEMORY
|
||||
{
|
||||
/* Relocated for the custom bootloader: the application is linked to run
|
||||
from 0x10020000, leaving the first 128k of flash for the bootloader and
|
||||
its manifest. */
|
||||
FLASH(rx) : ORIGIN = 0x10020000, LENGTH = 1920k
|
||||
RAM(rwx) : ORIGIN = 0x20000000, LENGTH = 512k
|
||||
SCRATCH_X(rwx) : ORIGIN = 0x20080000, LENGTH = 4k
|
||||
SCRATCH_Y(rwx) : ORIGIN = 0x20081000, LENGTH = 4k
|
||||
}
|
||||
|
||||
ENTRY(_entry_point)
|
||||
|
||||
SECTIONS
|
||||
{
|
||||
.flash_begin : {
|
||||
__flash_binary_start = .;
|
||||
} > FLASH
|
||||
|
||||
/* The bootrom will enter the image at the point indicated in your
|
||||
IMAGE_DEF, which is usually the reset handler of your vector table.
|
||||
|
||||
The debugger will use the ELF entry point, which is the _entry_point
|
||||
symbol, and in our case is *different from the bootrom's entry point.*
|
||||
This is used to go back through the bootrom on debugger launches only,
|
||||
to perform the same initial flash setup that would be performed on a
|
||||
cold boot.
|
||||
*/
|
||||
|
||||
.text : {
|
||||
__logical_binary_start = .;
|
||||
KEEP (*(.vectors))
|
||||
KEEP (*(.binary_info_header))
|
||||
__binary_info_header_end = .;
|
||||
KEEP (*(.embedded_block))
|
||||
__embedded_block_end = .;
|
||||
KEEP (*(.reset))
|
||||
/* TODO revisit this now memset/memcpy/float in ROM */
|
||||
/* bit of a hack right now to exclude all floating point and time critical (e.g. memset, memcpy) code from
|
||||
* FLASH ... we will include any thing excluded here in .data below by default */
|
||||
*(.init)
|
||||
*libgcc.a:cmse_nonsecure_call.o
|
||||
*(EXCLUDE_FILE(*libgcc.a: *libc.a:*lib_a-mem*.o *libm.a:) .text*)
|
||||
*(.fini)
|
||||
/* Pull all c'tors into .text */
|
||||
*crtbegin.o(.ctors)
|
||||
*crtbegin?.o(.ctors)
|
||||
*(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors)
|
||||
*(SORT(.ctors.*))
|
||||
*(.ctors)
|
||||
/* Followed by destructors */
|
||||
*crtbegin.o(.dtors)
|
||||
*crtbegin?.o(.dtors)
|
||||
*(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors)
|
||||
*(SORT(.dtors.*))
|
||||
*(.dtors)
|
||||
|
||||
. = ALIGN(4);
|
||||
/* preinit data */
|
||||
PROVIDE_HIDDEN (__preinit_array_start = .);
|
||||
KEEP(*(SORT(.preinit_array.*)))
|
||||
KEEP(*(.preinit_array))
|
||||
PROVIDE_HIDDEN (__preinit_array_end = .);
|
||||
|
||||
. = ALIGN(4);
|
||||
/* init data */
|
||||
PROVIDE_HIDDEN (__init_array_start = .);
|
||||
KEEP(*(SORT(.init_array.*)))
|
||||
KEEP(*(.init_array))
|
||||
PROVIDE_HIDDEN (__init_array_end = .);
|
||||
|
||||
. = ALIGN(4);
|
||||
/* finit data */
|
||||
PROVIDE_HIDDEN (__fini_array_start = .);
|
||||
*(SORT(.fini_array.*))
|
||||
*(.fini_array)
|
||||
PROVIDE_HIDDEN (__fini_array_end = .);
|
||||
|
||||
*(.eh_frame*)
|
||||
. = ALIGN(4);
|
||||
} > FLASH
|
||||
|
||||
/* Note the boot2 section is optional, and should be discarded if there is
|
||||
no reference to it *inside* the binary, as it is not called by the
|
||||
bootrom. (The bootrom performs a simple best-effort XIP setup and
|
||||
leaves it to the binary to do anything more sophisticated.) However
|
||||
there is still a size limit of 256 bytes, to ensure the boot2 can be
|
||||
stored in boot RAM.
|
||||
|
||||
Really this is a "XIP setup function" -- the name boot2 is historic and
|
||||
refers to its dual-purpose on RP2040, where it also handled vectoring
|
||||
from the bootrom into the user image.
|
||||
*/
|
||||
|
||||
.boot2 : {
|
||||
__boot2_start__ = .;
|
||||
*(.boot2)
|
||||
__boot2_end__ = .;
|
||||
} > FLASH
|
||||
|
||||
ASSERT(__boot2_end__ - __boot2_start__ <= 256,
|
||||
"ERROR: Pico second stage bootloader must be no more than 256 bytes in size")
|
||||
|
||||
.rodata : {
|
||||
*(EXCLUDE_FILE(*libgcc.a: *libc.a:*lib_a-mem*.o *libm.a:) .rodata*)
|
||||
*(.srodata*)
|
||||
. = ALIGN(4);
|
||||
*(SORT_BY_ALIGNMENT(SORT_BY_NAME(.flashdata*)))
|
||||
. = ALIGN(4);
|
||||
} > FLASH
|
||||
|
||||
.ARM.extab :
|
||||
{
|
||||
*(.ARM.extab* .gnu.linkonce.armextab.*)
|
||||
} > FLASH
|
||||
|
||||
__exidx_start = .;
|
||||
.ARM.exidx :
|
||||
{
|
||||
*(.ARM.exidx* .gnu.linkonce.armexidx.*)
|
||||
} > FLASH
|
||||
__exidx_end = .;
|
||||
|
||||
/* Machine inspectable binary information */
|
||||
. = ALIGN(4);
|
||||
__binary_info_start = .;
|
||||
.binary_info :
|
||||
{
|
||||
KEEP(*(.binary_info.keep.*))
|
||||
*(.binary_info.*)
|
||||
} > FLASH
|
||||
__binary_info_end = .;
|
||||
. = ALIGN(4);
|
||||
|
||||
.ram_vector_table (NOLOAD): {
|
||||
*(.ram_vector_table)
|
||||
} > RAM
|
||||
|
||||
.uninitialized_data (NOLOAD): {
|
||||
. = ALIGN(4);
|
||||
*(.uninitialized_data*)
|
||||
} > RAM
|
||||
|
||||
.data : {
|
||||
__data_start__ = .;
|
||||
*(vtable)
|
||||
|
||||
*(.time_critical*)
|
||||
|
||||
/* remaining .text and .rodata; i.e. stuff we exclude above because we want it in RAM */
|
||||
*(.text*)
|
||||
. = ALIGN(4);
|
||||
*(.rodata*)
|
||||
. = ALIGN(4);
|
||||
|
||||
*(.data*)
|
||||
*(.sdata*)
|
||||
|
||||
. = ALIGN(4);
|
||||
*(.after_data.*)
|
||||
. = ALIGN(4);
|
||||
/* preinit data */
|
||||
PROVIDE_HIDDEN (__mutex_array_start = .);
|
||||
KEEP(*(SORT(.mutex_array.*)))
|
||||
KEEP(*(.mutex_array))
|
||||
PROVIDE_HIDDEN (__mutex_array_end = .);
|
||||
|
||||
*(.jcr)
|
||||
. = ALIGN(4);
|
||||
} > RAM AT> FLASH
|
||||
|
||||
.tdata : {
|
||||
. = ALIGN(4);
|
||||
*(.tdata .tdata.* .gnu.linkonce.td.*)
|
||||
/* All data end */
|
||||
__tdata_end = .;
|
||||
} > RAM AT> FLASH
|
||||
PROVIDE(__data_end__ = .);
|
||||
|
||||
/* __etext is (for backwards compatibility) the name of the .data init source pointer (...) */
|
||||
__etext = LOADADDR(.data);
|
||||
|
||||
.tbss (NOLOAD) : {
|
||||
. = ALIGN(4);
|
||||
__bss_start__ = .;
|
||||
__tls_base = .;
|
||||
*(.tbss .tbss.* .gnu.linkonce.tb.*)
|
||||
*(.tcommon)
|
||||
|
||||
__tls_end = .;
|
||||
} > RAM
|
||||
|
||||
.bss (NOLOAD) : {
|
||||
. = ALIGN(4);
|
||||
__tbss_end = .;
|
||||
|
||||
*(SORT_BY_ALIGNMENT(SORT_BY_NAME(.bss*)))
|
||||
*(COMMON)
|
||||
PROVIDE(__global_pointer$ = . + 2K);
|
||||
*(.sbss*)
|
||||
. = ALIGN(4);
|
||||
__bss_end__ = .;
|
||||
} > RAM
|
||||
|
||||
.heap (NOLOAD):
|
||||
{
|
||||
__end__ = .;
|
||||
end = __end__;
|
||||
KEEP(*(.heap*))
|
||||
} > RAM
|
||||
/* historically on GCC sbrk was growing past __HeapLimit to __StackLimit, however
|
||||
to be more compatible, we now set __HeapLimit explicitly to where the end of the heap is */
|
||||
__HeapLimit = ORIGIN(RAM) + LENGTH(RAM);
|
||||
|
||||
/* Start and end symbols must be word-aligned */
|
||||
.scratch_x : {
|
||||
__scratch_x_start__ = .;
|
||||
*(.scratch_x.*)
|
||||
. = ALIGN(4);
|
||||
__scratch_x_end__ = .;
|
||||
} > SCRATCH_X AT > FLASH
|
||||
__scratch_x_source__ = LOADADDR(.scratch_x);
|
||||
|
||||
.scratch_y : {
|
||||
__scratch_y_start__ = .;
|
||||
*(.scratch_y.*)
|
||||
. = ALIGN(4);
|
||||
__scratch_y_end__ = .;
|
||||
} > SCRATCH_Y AT > FLASH
|
||||
__scratch_y_source__ = LOADADDR(.scratch_y);
|
||||
|
||||
/* .stack*_dummy section doesn't contains any symbols. It is only
|
||||
* used for linker to calculate size of stack sections, and assign
|
||||
* values to stack symbols later
|
||||
*
|
||||
* stack1 section may be empty/missing if platform_launch_core1 is not used */
|
||||
|
||||
/* by default we put core 0 stack at the end of scratch Y, so that if core 1
|
||||
* stack is not used then all of SCRATCH_X is free.
|
||||
*/
|
||||
.stack1_dummy (NOLOAD):
|
||||
{
|
||||
*(.stack1*)
|
||||
} > SCRATCH_X
|
||||
.stack_dummy (NOLOAD):
|
||||
{
|
||||
KEEP(*(.stack*))
|
||||
} > SCRATCH_Y
|
||||
|
||||
.flash_end : {
|
||||
KEEP(*(.embedded_end_block*))
|
||||
PROVIDE(__flash_binary_end = .);
|
||||
} > FLASH =0xaa
|
||||
|
||||
/* stack limit is poorly named, but historically is maximum heap ptr */
|
||||
__StackLimit = ORIGIN(RAM) + LENGTH(RAM);
|
||||
__StackOneTop = ORIGIN(SCRATCH_X) + LENGTH(SCRATCH_X);
|
||||
__StackTop = ORIGIN(SCRATCH_Y) + LENGTH(SCRATCH_Y);
|
||||
__StackOneBottom = __StackOneTop - SIZEOF(.stack1_dummy);
|
||||
__StackBottom = __StackTop - SIZEOF(.stack_dummy);
|
||||
PROVIDE(__stack = __StackTop);
|
||||
|
||||
/* picolibc and LLVM */
|
||||
PROVIDE (__heap_start = __end__);
|
||||
PROVIDE (__heap_end = __HeapLimit);
|
||||
PROVIDE( __tls_align = MAX(ALIGNOF(.tdata), ALIGNOF(.tbss)) );
|
||||
PROVIDE( __tls_size_align = (__tls_size + __tls_align - 1) & ~(__tls_align - 1));
|
||||
PROVIDE( __arm32_tls_tcb_offset = MAX(8, __tls_align) );
|
||||
|
||||
/* llvm-libc */
|
||||
PROVIDE (_end = __end__);
|
||||
PROVIDE (__llvm_libc_heap_limit = __HeapLimit);
|
||||
|
||||
/* Check if data + heap + stack exceeds RAM limit */
|
||||
ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed")
|
||||
|
||||
ASSERT( __binary_info_header_end - __logical_binary_start <= 1024, "Binary info must be in first 1024 bytes of the binary")
|
||||
ASSERT( __embedded_block_end - __logical_binary_start <= 4096, "Embedded block must be in first 4096 bytes of the binary")
|
||||
|
||||
/* todo assert on extra code */
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* @file app_main.c
|
||||
* @brief Application entry point: IR receiver drives the LED controller.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*
|
||||
* -----------------------------------------------------------------------------
|
||||
*
|
||||
* This file is deliberately thin: it only wires the modules together and runs
|
||||
* the poll loop. The NEC IR decoder lives in ir.c, the LED controller lives in
|
||||
* led.c, and the AES-128-CBC protected banner lives in secret.c.
|
||||
*
|
||||
* Wiring:
|
||||
* GPIO5 -> IR receiver OUT
|
||||
* GPIO16 -> LED1 anode (with current-limiting resistor to GND)
|
||||
* GPIO17 -> LED2 anode (with current-limiting resistor to GND)
|
||||
* GPIO18 -> LED3 anode (with current-limiting resistor to GND)
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include "pico/stdlib.h"
|
||||
#include "ir.h"
|
||||
#include "led.h"
|
||||
#include "secret.h"
|
||||
|
||||
/** @brief GPIO pin number for the IR receiver. */
|
||||
#define IR_PIN 5
|
||||
|
||||
/**
|
||||
* @brief Poll the IR receiver and dispatch decoded keys forever.
|
||||
* @param leds Pointer to the LED controller to drive.
|
||||
* @return void Does not return.
|
||||
*/
|
||||
static void ir_poll_loop(simple_led_ctrl_t *leds) {
|
||||
while (true) {
|
||||
int key = ir_getkey();
|
||||
if (key >= 0) led_handle_ir(leds, key);
|
||||
else sleep_ms(1);
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
stdio_init_all();
|
||||
secret_print_banner();
|
||||
simple_led_ctrl_t leds = led_default();
|
||||
led_init(&leds);
|
||||
ir_init(IR_PIN);
|
||||
printf("IR receiver on GPIO %d ready\n", IR_PIN);
|
||||
ir_poll_loop(&leds);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* @file ir.c
|
||||
* @brief Implementation of NEC IR receiver (decoder)
|
||||
* @author Kevin Thomas
|
||||
* @date 2025
|
||||
*
|
||||
* MIT License
|
||||
*
|
||||
* Copyright (c) 2025 Kevin Thomas
|
||||
*
|
||||
* 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 "ir.h"
|
||||
#include "pico/stdlib.h"
|
||||
#include "pico/time.h"
|
||||
#include "hardware/gpio.h"
|
||||
|
||||
/** @brief GPIO pin connected to the IR receiver */
|
||||
static unsigned int ir_pin = 0;
|
||||
|
||||
/**
|
||||
* @brief Wait for a GPIO pin to reach a given logic level
|
||||
*
|
||||
* Spins until the pin matches the requested level or a microsecond timeout
|
||||
* is exceeded. Returns the elapsed time in microseconds, or -1 on timeout.
|
||||
*
|
||||
* @param gpio GPIO pin to monitor
|
||||
* @param level Desired logic level (true = HIGH, false = LOW)
|
||||
* @param timeout_us Maximum wait in microseconds
|
||||
* @return int64_t Elapsed microseconds, or -1 on timeout
|
||||
*/
|
||||
static int64_t wait_for_level(unsigned int gpio, bool level, uint32_t timeout_us) {
|
||||
absolute_time_t start = get_absolute_time();
|
||||
while (gpio_get(gpio) != level) {
|
||||
if (absolute_time_diff_us(start, get_absolute_time()) > (int64_t)timeout_us)
|
||||
return -1;
|
||||
}
|
||||
return absolute_time_diff_us(start, get_absolute_time());
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Wait for the NEC 9 ms leader pulse and 4.5 ms space
|
||||
*
|
||||
* @param void No parameters.
|
||||
* @return bool true if a valid leader was detected, false on timeout
|
||||
*/
|
||||
static bool wait_leader(void) {
|
||||
if (wait_for_level(ir_pin, 0, 150000) < 0) return false;
|
||||
int64_t t = wait_for_level(ir_pin, 1, 12000);
|
||||
if (t < 8000 || t > 10000) return false;
|
||||
t = wait_for_level(ir_pin, 0, 7000);
|
||||
if (t < 3500 || t > 5000) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Read a single NEC-encoded bit from the IR receiver
|
||||
*
|
||||
* Measures the mark/space timing and shifts the result into the
|
||||
* appropriate byte of the data array.
|
||||
*
|
||||
* @param data 4-byte array accumulating received bits
|
||||
* @param i Bit index (0-31)
|
||||
* @return bool true on success, false on timeout or protocol error
|
||||
*/
|
||||
static bool read_nec_bit(uint8_t *data, int i) {
|
||||
if (wait_for_level(ir_pin, 1, 1000) < 0) return false;
|
||||
int64_t t = wait_for_level(ir_pin, 0, 2500);
|
||||
if (t < 200) return false;
|
||||
int byte_idx = i / 8;
|
||||
int bit_idx = i % 8;
|
||||
if (t > 1200) data[byte_idx] |= (1 << bit_idx);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Read all 32 data bits of an NEC frame
|
||||
*
|
||||
* @param data 4-byte array filled with the received address and command
|
||||
* @return bool true if all 32 bits were read, false on timeout
|
||||
*/
|
||||
static bool read_32_bits(uint8_t *data) {
|
||||
for (int i = 0; i < 32; ++i)
|
||||
if (!read_nec_bit(data, i)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Validate an NEC frame and extract the command byte
|
||||
*
|
||||
* Checks that the address and command pairs are bitwise-inverted.
|
||||
*
|
||||
* @param data 4-byte NEC frame (addr, ~addr, cmd, ~cmd)
|
||||
* @return int Command byte (0-255) on success, -1 on validation failure
|
||||
*/
|
||||
static int validate_nec_frame(const uint8_t *data) {
|
||||
if ((uint8_t)(data[0] + data[1]) == 0xFF && (uint8_t)(data[2] + data[3]) == 0xFF)
|
||||
return data[2];
|
||||
return -1;
|
||||
}
|
||||
|
||||
void ir_init(uint8_t pin) {
|
||||
ir_pin = pin;
|
||||
gpio_init(pin);
|
||||
gpio_set_dir(pin, GPIO_IN);
|
||||
gpio_pull_up(pin);
|
||||
}
|
||||
|
||||
int ir_getkey(void) {
|
||||
if (!wait_leader()) return -1;
|
||||
uint8_t data[4] = {0, 0, 0, 0};
|
||||
if (!read_32_bits(data)) return -1;
|
||||
return validate_nec_frame(data);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* @file led.c
|
||||
* @brief LED controller driven by decoded NEC IR commands.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include "pico/stdlib.h"
|
||||
#include "led.h"
|
||||
|
||||
/**
|
||||
* @brief Map an NEC command code to a logical LED number.
|
||||
* @param ir_command Decoded NEC command byte.
|
||||
* @return int Logical LED number 1-3, or 0 when the command is unmapped.
|
||||
*/
|
||||
static int led_number_for_command(int ir_command) {
|
||||
if (ir_command == 0x0C) return 1;
|
||||
if (ir_command == 0x18) return 2;
|
||||
if (ir_command == 0x5E) return 3;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Return the GPIO pin backing a logical LED number.
|
||||
* @param leds Pointer to the LED controller.
|
||||
* @param led_num Logical LED number (1-3).
|
||||
* @return uint8_t GPIO pin number for the requested LED.
|
||||
*/
|
||||
static uint8_t led_pin_for(simple_led_ctrl_t *leds, int led_num) {
|
||||
if (led_num == 1) return leds->led1_pin;
|
||||
if (led_num == 2) return leds->led2_pin;
|
||||
return leds->led3_pin;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Turn every LED output off.
|
||||
* @param leds Pointer to the LED controller.
|
||||
* @return void No return value.
|
||||
*/
|
||||
static void led_all_off(simple_led_ctrl_t *leds) {
|
||||
gpio_put(leds->led1_pin, false);
|
||||
gpio_put(leds->led2_pin, false);
|
||||
gpio_put(leds->led3_pin, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Toggle a GPIO on and off for a number of blink cycles.
|
||||
* @param pin GPIO pin to blink.
|
||||
* @param count Number of on/off cycles.
|
||||
* @param delay_ms Milliseconds to hold each phase.
|
||||
* @return void No return value.
|
||||
*/
|
||||
static void led_blink(uint8_t pin, uint8_t count, uint32_t delay_ms) {
|
||||
for (uint8_t i = 0; i < count; i++) {
|
||||
gpio_put(pin, true);
|
||||
sleep_ms(delay_ms);
|
||||
gpio_put(pin, false);
|
||||
sleep_ms(delay_ms);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Blink an LED, then leave it lit.
|
||||
* @param leds Pointer to the LED controller.
|
||||
* @param led_num Logical LED number to activate.
|
||||
* @return void No return value.
|
||||
*/
|
||||
static void led_activate(simple_led_ctrl_t *leds, int led_num) {
|
||||
uint8_t pin = led_pin_for(leds, led_num);
|
||||
led_blink(pin, 3, 50);
|
||||
gpio_put(pin, true);
|
||||
printf("LED %d activated on GPIO %d\n", led_num, pin);
|
||||
}
|
||||
|
||||
simple_led_ctrl_t led_default(void) {
|
||||
simple_led_ctrl_t leds = {
|
||||
.led1_pin = 16, .led2_pin = 17, .led3_pin = 18,
|
||||
.led1_state = false, .led2_state = false, .led3_state = false
|
||||
};
|
||||
return leds;
|
||||
}
|
||||
|
||||
void led_init(simple_led_ctrl_t *leds) {
|
||||
gpio_init(leds->led1_pin);
|
||||
gpio_set_dir(leds->led1_pin, GPIO_OUT);
|
||||
gpio_init(leds->led2_pin);
|
||||
gpio_set_dir(leds->led2_pin, GPIO_OUT);
|
||||
gpio_init(leds->led3_pin);
|
||||
gpio_set_dir(leds->led3_pin, GPIO_OUT);
|
||||
}
|
||||
|
||||
void led_handle_ir(simple_led_ctrl_t *leds, int key) {
|
||||
if (key < 0) return;
|
||||
printf("NEC command: 0x%02X\n", key);
|
||||
led_all_off(leds);
|
||||
int led_num = led_number_for_command(key);
|
||||
if (led_num == 0) return;
|
||||
led_activate(leds, led_num);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* @file secret.c
|
||||
* @brief Decrypts a runtime banner with the SDK Mbed TLS AES-128-CBC API.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*
|
||||
* -----------------------------------------------------------------------------
|
||||
*
|
||||
* This module shows how to use the AES implementation that ships with the Pico
|
||||
* SDK. A short banner is stored in flash only as AES-128-CBC ciphertext; the
|
||||
* key and IV live in the same image. At startup secret_print_banner() rebuilds
|
||||
* the plaintext with mbedtls_aes_crypt_cbc() and writes it to the console.
|
||||
*
|
||||
* The plaintext is exactly APP_BANNER_LEN bytes (two whole AES blocks), so no
|
||||
* padding routine is required. The ciphertext was produced on the host with the
|
||||
* matching key and IV, for example:
|
||||
*
|
||||
* printf '%s' 'SECRET: IR LINK SECURED ONLINE ' \
|
||||
* | openssl enc -aes-128-cbc -K 49726f6e4e6574426f6f744b65792121 \
|
||||
* -iv 41707053656372657449563132333435 -nopad | xxd -p
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "mbedtls/aes.h"
|
||||
#include "secret.h"
|
||||
|
||||
/** @brief AES-128 key, the same 16 bytes the bootloader uses for CMAC. */
|
||||
static const uint8_t banner_key[APP_AES_BLOCK] = {
|
||||
0x49, 0x72, 0x6F, 0x6E, 0x4E, 0x65, 0x74, 0x42,
|
||||
0x6F, 0x6F, 0x74, 0x4B, 0x65, 0x79, 0x21, 0x21
|
||||
};
|
||||
|
||||
/** @brief Initialization vector used when the banner was encrypted. */
|
||||
static const uint8_t banner_iv[APP_AES_BLOCK] = {
|
||||
0x41, 0x70, 0x70, 0x53, 0x65, 0x63, 0x72, 0x65,
|
||||
0x74, 0x49, 0x56, 0x31, 0x32, 0x33, 0x34, 0x35
|
||||
};
|
||||
|
||||
/** @brief AES-128-CBC ciphertext of the runtime banner. */
|
||||
static const uint8_t banner_ct[APP_BANNER_LEN] = {
|
||||
0xBA, 0xEC, 0x4A, 0x19, 0x25, 0x86, 0x1B, 0xB9,
|
||||
0x2D, 0xFD, 0x9F, 0x13, 0xF7, 0x9B, 0x3E, 0x80,
|
||||
0xCF, 0x12, 0xB6, 0x98, 0xDB, 0x91, 0x65, 0xBE,
|
||||
0x8F, 0xD7, 0xC3, 0x47, 0x7B, 0xB2, 0xE7, 0x6E
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Run the AES-128-CBC decrypt in place over a working buffer.
|
||||
* @param aes Pointer to an AES context holding an already-expanded key.
|
||||
* @param iv Pointer to a mutable copy of the initialization vector.
|
||||
* @param buf Pointer to the buffer holding ciphertext, then plaintext.
|
||||
* @return int Zero on success, non-zero on failure.
|
||||
*/
|
||||
static int secret_cbc(mbedtls_aes_context *aes, uint8_t *iv, uint8_t *buf) {
|
||||
int rc = mbedtls_aes_crypt_cbc(aes, MBEDTLS_AES_DECRYPT, APP_BANNER_LEN,
|
||||
iv, buf, buf);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Decrypt the banner ciphertext into a working buffer.
|
||||
* @param buf Buffer of at least APP_BANNER_LEN bytes.
|
||||
* @return int Zero on success, non-zero on failure.
|
||||
*/
|
||||
static int secret_decrypt(uint8_t *buf) {
|
||||
mbedtls_aes_context aes;
|
||||
uint8_t iv[APP_AES_BLOCK];
|
||||
memcpy(iv, banner_iv, APP_AES_BLOCK);
|
||||
mbedtls_aes_init(&aes);
|
||||
mbedtls_aes_setkey_dec(&aes, banner_key, 128);
|
||||
int rc = secret_cbc(&aes, iv, buf);
|
||||
mbedtls_aes_free(&aes);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int secret_print_banner(void) {
|
||||
uint8_t buf[APP_BANNER_LEN + 1];
|
||||
memcpy(buf, banner_ct, APP_BANNER_LEN);
|
||||
buf[APP_BANNER_LEN] = '\0';
|
||||
int rc = secret_decrypt(buf);
|
||||
if (rc != 0) return rc;
|
||||
printf("app banner: %s\n", (char *)buf);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* @file aes_cmac.h
|
||||
* @brief AES-128-CMAC authentication tag helpers backed by Mbed TLS.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#ifndef AES_CMAC_H
|
||||
#define AES_CMAC_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
/** @brief AES block size in bytes. */
|
||||
#define AES_BLOCK_SIZE 16U
|
||||
|
||||
/**
|
||||
* @brief Compute an AES-128-CMAC tag over a memory region.
|
||||
* @param key Pointer to the 16-byte AES-128 key.
|
||||
* @param data Pointer to the message bytes, which may live in XIP flash.
|
||||
* @param len Message length in bytes.
|
||||
* @param tag Output buffer that receives the 16-byte CMAC tag.
|
||||
* @return int Zero on success, non-zero when the cipher is unavailable.
|
||||
*/
|
||||
int aes128_cmac(const uint8_t *key, const uint8_t *data, size_t len,
|
||||
uint8_t *tag);
|
||||
|
||||
/**
|
||||
* @brief Compare two CMAC tags without short-circuiting on the first byte.
|
||||
* @param a Pointer to the first tag.
|
||||
* @param b Pointer to the second tag.
|
||||
* @return bool True when the tags are byte-for-byte identical.
|
||||
*/
|
||||
bool cmac_tags_equal(const uint8_t *a, const uint8_t *b);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* @file boot.h
|
||||
* @brief Secure boot console and application handoff helpers.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#ifndef BOOT_H
|
||||
#define BOOT_H
|
||||
|
||||
#include "manifest.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Bring up the debug console and print the boot banner.
|
||||
* @param void No parameters.
|
||||
* @return void No return value.
|
||||
*/
|
||||
void boot_init(void);
|
||||
|
||||
/**
|
||||
* @brief Print a boot failure reason and idle forever.
|
||||
* @param reason Null-terminated message describing the failure.
|
||||
* @return void Does not return.
|
||||
*/
|
||||
void boot_halt(const char *reason);
|
||||
|
||||
/**
|
||||
* @brief Announce the verified image and jump to its reset vector.
|
||||
* @param manifest Pointer to the validated manifest.
|
||||
* @return void Does not return.
|
||||
*/
|
||||
void boot_launch(const fw_manifest_t *manifest);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // BOOT_H
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* @file flash_layout.h
|
||||
* @brief Flash partition map shared by the bootloader and the host signer.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#ifndef FLASH_LAYOUT_H
|
||||
#define FLASH_LAYOUT_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/** @brief Absolute base address of the bootloader image in XIP flash. */
|
||||
#define BOOTLOADER_BASE 0x10000000U
|
||||
|
||||
/** @brief Absolute address of the one-sector firmware manifest. */
|
||||
#define FW_MANIFEST_BASE 0x1001F000U
|
||||
|
||||
/** @brief Size in bytes of the flash sector holding the manifest. */
|
||||
#define FW_MANIFEST_SECTOR_SIZE 4096U
|
||||
|
||||
/** @brief Absolute base address where the signed application runs. */
|
||||
#define APP_BASE 0x10020000U
|
||||
|
||||
/** @brief Total XIP flash size in bytes on the RP2350 Pico 2 board. */
|
||||
#define FLASH_TOTAL_SIZE 0x200000U
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* @file image.h
|
||||
* @brief Control transfer into a freshly verified Cortex-M application.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#ifndef IMAGE_H
|
||||
#define IMAGE_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/**
|
||||
* @brief Jump to an application whose vector table starts at a base address.
|
||||
* @param vector_base Base address of the application vector table.
|
||||
* @return void Does not return to the caller.
|
||||
*/
|
||||
void image_start(uint32_t vector_base);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* @file manifest.h
|
||||
* @brief Firmware manifest stored in the flash sector before the application.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#ifndef MANIFEST_H
|
||||
#define MANIFEST_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
/** @brief Little-endian magic at the head of a valid manifest ("WFLB"). */
|
||||
#define FW_MANIFEST_MAGIC 0x424C4657U
|
||||
|
||||
/** @brief Current manifest structure revision. */
|
||||
#define FW_MANIFEST_VERSION 1U
|
||||
|
||||
/** @brief Length in bytes of an AES-128-CMAC authentication tag. */
|
||||
#define FW_TAG_SIZE 16U
|
||||
|
||||
#pragma pack(push, 1)
|
||||
/** @brief Fixed-layout record describing the signed application image. */
|
||||
typedef struct {
|
||||
uint32_t magic;
|
||||
uint32_t version;
|
||||
uint32_t app_base;
|
||||
uint32_t app_size;
|
||||
uint8_t tag[FW_TAG_SIZE];
|
||||
} fw_manifest_t;
|
||||
#pragma pack(pop)
|
||||
|
||||
/**
|
||||
* @brief Copy the manifest out of its fixed flash address.
|
||||
* @param out Pointer to the manifest structure to populate.
|
||||
* @return void No return value.
|
||||
*/
|
||||
void manifest_read(fw_manifest_t *out);
|
||||
|
||||
/**
|
||||
* @brief Report whether a manifest carries the expected magic and version.
|
||||
* @param manifest Pointer to the manifest to inspect.
|
||||
* @return bool True when the magic and version both match.
|
||||
*/
|
||||
bool manifest_is_valid(const fw_manifest_t *manifest);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* @file verify.h
|
||||
* @brief Firmware authenticity verification for the secure bootloader.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#ifndef VERIFY_H
|
||||
#define VERIFY_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include "manifest.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Recompute the CMAC over the application and compare it to the tag.
|
||||
* @param manifest Pointer to the validated manifest.
|
||||
* @return bool True when the tag matches, false otherwise.
|
||||
*/
|
||||
bool verify_manifest(const fw_manifest_t *manifest);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // VERIFY_H
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* @file aes_cmac.c
|
||||
* @brief AES-128-CMAC primitives implemented on top of the SDK Mbed TLS.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#include "mbedtls/cmac.h"
|
||||
#include "mbedtls/cipher.h"
|
||||
#include "aes_cmac.h"
|
||||
|
||||
int aes128_cmac(const uint8_t *key, const uint8_t *data, size_t len,
|
||||
uint8_t *tag) {
|
||||
const mbedtls_cipher_info_t *info;
|
||||
info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_ECB);
|
||||
if (info == NULL) return -1;
|
||||
return mbedtls_cipher_cmac(info, key, 128, data, len, tag);
|
||||
}
|
||||
|
||||
bool cmac_tags_equal(const uint8_t *a, const uint8_t *b) {
|
||||
uint8_t diff = 0;
|
||||
for (size_t i = 0; i < AES_BLOCK_SIZE; i++) {
|
||||
diff |= (uint8_t)(a[i] ^ b[i]);
|
||||
}
|
||||
return diff == 0;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* @file boot.c
|
||||
* @brief Secure boot console and application handoff helpers.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include "pico/stdlib.h"
|
||||
#include "boot.h"
|
||||
#include "image.h"
|
||||
|
||||
void boot_init(void) {
|
||||
stdio_init_all();
|
||||
sleep_ms(2000);
|
||||
printf("\n=== 0x0026a secure bootloader ===\n");
|
||||
}
|
||||
|
||||
void boot_halt(const char *reason) {
|
||||
printf("BOOT FAILED: %s\n", reason);
|
||||
while (true) {
|
||||
sleep_ms(500);
|
||||
}
|
||||
}
|
||||
|
||||
void boot_launch(const fw_manifest_t *manifest) {
|
||||
printf("signature valid, entering app at 0x%08lx\n",
|
||||
(unsigned long)manifest->app_base);
|
||||
image_start(manifest->app_base);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* @file image.c
|
||||
* @brief Loads the application stack pointer and branches to its reset vector.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#include "image.h"
|
||||
|
||||
/** @brief Application reset handler signature. */
|
||||
typedef void (*image_entry_t)(void);
|
||||
|
||||
/**
|
||||
* @brief Mask interrupts and point VTOR at the incoming image.
|
||||
* @param base Vector table base address written to the VTOR register.
|
||||
* @return void No return value.
|
||||
*/
|
||||
static void halt_irq_and_rebase(uint32_t base) {
|
||||
__asm volatile ("cpsid i" ::: "memory");
|
||||
*(volatile uint32_t *)0xE000ED08U = base;
|
||||
}
|
||||
|
||||
void image_start(uint32_t vector_base) {
|
||||
uint32_t *vectors = (uint32_t *)vector_base;
|
||||
image_entry_t entry = (image_entry_t)vectors[1];
|
||||
halt_irq_and_rebase(vector_base);
|
||||
__asm volatile ("msr msp, %0" :: "r" (vectors[0]) : "memory");
|
||||
__asm volatile ("dsb\n\tisb" ::: "memory");
|
||||
entry();
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* @file main.c
|
||||
* @brief Secure bootloader entry point (verify AES-128-CMAC, then boot).
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*
|
||||
* -----------------------------------------------------------------------------
|
||||
*
|
||||
* This file is deliberately thin: it only sequences the secure boot steps.
|
||||
* The console setup, halt reporting, and application handoff live in boot.c;
|
||||
* the CMAC verification (and its key) live in verify.c; the manifest lives in
|
||||
* manifest.c; and the raw reset-vector jump lives in image.c.
|
||||
*
|
||||
* Flash map (2 MiB, RP2350 Pico 2):
|
||||
* 0x10000000 bootloader image (this program)
|
||||
* 0x1001F000 one-sector firmware manifest (magic, size, CMAC tag)
|
||||
* 0x10020000 signed application image
|
||||
*/
|
||||
|
||||
#include "manifest.h"
|
||||
#include "boot.h"
|
||||
#include "verify.h"
|
||||
|
||||
int main(void) {
|
||||
fw_manifest_t manifest;
|
||||
boot_init();
|
||||
manifest_read(&manifest);
|
||||
if (!manifest_is_valid(&manifest)) boot_halt("manifest invalid");
|
||||
if (!verify_manifest(&manifest)) boot_halt("firmware signature invalid");
|
||||
boot_launch(&manifest);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* @file manifest.c
|
||||
* @brief Reads and validates the firmware manifest from XIP flash.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#include "flash_layout.h"
|
||||
#include "manifest.h"
|
||||
|
||||
void manifest_read(fw_manifest_t *out) {
|
||||
const fw_manifest_t *src = (const fw_manifest_t *)FW_MANIFEST_BASE;
|
||||
*out = *src;
|
||||
}
|
||||
|
||||
bool manifest_is_valid(const fw_manifest_t *manifest) {
|
||||
if (manifest->magic != FW_MANIFEST_MAGIC) return false;
|
||||
if (manifest->version != FW_MANIFEST_VERSION) return false;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* @file verify.c
|
||||
* @brief Firmware authenticity verification for the secure bootloader.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*/
|
||||
|
||||
#include <stdint.h>
|
||||
#include "flash_layout.h"
|
||||
#include "verify.h"
|
||||
#include "aes_cmac.h"
|
||||
|
||||
/** @brief AES-128 key that authenticates the application image. */
|
||||
static const uint8_t fw_key[FW_TAG_SIZE] = {
|
||||
0x49, 0x72, 0x6F, 0x6E, 0x4E, 0x65, 0x74, 0x42,
|
||||
0x6F, 0x6F, 0x74, 0x4B, 0x65, 0x79, 0x21, 0x21
|
||||
};
|
||||
|
||||
bool verify_manifest(const fw_manifest_t *manifest) {
|
||||
const uint8_t *base = (const uint8_t *)manifest->app_base;
|
||||
uint8_t computed[FW_TAG_SIZE];
|
||||
int rc = aes128_cmac(fw_key, base, manifest->app_size, computed);
|
||||
if (rc != 0) return false;
|
||||
return cmac_tags_equal(computed, manifest->tag);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* @file mbedtls_config.h
|
||||
* @brief Minimal Mbed TLS configuration for the 0x0026a bootloader and app.
|
||||
* @author Kevin Thomas
|
||||
* @date 2026
|
||||
*
|
||||
* MIT License
|
||||
* Copyright (c) 2026 Kevin Thomas
|
||||
*
|
||||
* The Pico SDK points MBEDTLS_CONFIG_FILE at pico_mbedtls_config.h, which in
|
||||
* turn includes this file. Only the AES-128 building blocks needed for CMAC
|
||||
* authentication and CBC encryption are enabled, keeping the image small.
|
||||
*/
|
||||
|
||||
#ifndef MBEDTLS_CONFIG_H
|
||||
#define MBEDTLS_CONFIG_H
|
||||
|
||||
#include <limits.h>
|
||||
|
||||
#define MBEDTLS_AES_C
|
||||
#define MBEDTLS_CIPHER_C
|
||||
#define MBEDTLS_CIPHER_MODE_CBC
|
||||
#define MBEDTLS_CMAC_C
|
||||
|
||||
#endif
|
||||
Binary file not shown.
@@ -0,0 +1,121 @@
|
||||
# This is a copy of <PICO_SDK_PATH>/external/pico_sdk_import.cmake
|
||||
|
||||
# This can be dropped into an external project to help locate this SDK
|
||||
# It should be include()ed prior to project()
|
||||
|
||||
# Copyright 2020 (c) 2020 Raspberry Pi (Trading) Ltd.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
|
||||
# following conditions are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
|
||||
# disclaimer.
|
||||
#
|
||||
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
|
||||
# disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
#
|
||||
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
|
||||
# derived from this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
|
||||
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
if (DEFINED ENV{PICO_SDK_PATH} AND (NOT PICO_SDK_PATH))
|
||||
set(PICO_SDK_PATH $ENV{PICO_SDK_PATH})
|
||||
message("Using PICO_SDK_PATH from environment ('${PICO_SDK_PATH}')")
|
||||
endif ()
|
||||
|
||||
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT} AND (NOT PICO_SDK_FETCH_FROM_GIT))
|
||||
set(PICO_SDK_FETCH_FROM_GIT $ENV{PICO_SDK_FETCH_FROM_GIT})
|
||||
message("Using PICO_SDK_FETCH_FROM_GIT from environment ('${PICO_SDK_FETCH_FROM_GIT}')")
|
||||
endif ()
|
||||
|
||||
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_PATH))
|
||||
set(PICO_SDK_FETCH_FROM_GIT_PATH $ENV{PICO_SDK_FETCH_FROM_GIT_PATH})
|
||||
message("Using PICO_SDK_FETCH_FROM_GIT_PATH from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')")
|
||||
endif ()
|
||||
|
||||
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_TAG} AND (NOT PICO_SDK_FETCH_FROM_GIT_TAG))
|
||||
set(PICO_SDK_FETCH_FROM_GIT_TAG $ENV{PICO_SDK_FETCH_FROM_GIT_TAG})
|
||||
message("Using PICO_SDK_FETCH_FROM_GIT_TAG from environment ('${PICO_SDK_FETCH_FROM_GIT_TAG}')")
|
||||
endif ()
|
||||
|
||||
if (PICO_SDK_FETCH_FROM_GIT AND NOT PICO_SDK_FETCH_FROM_GIT_TAG)
|
||||
set(PICO_SDK_FETCH_FROM_GIT_TAG "master")
|
||||
message("Using master as default value for PICO_SDK_FETCH_FROM_GIT_TAG")
|
||||
endif()
|
||||
|
||||
set(PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the Raspberry Pi Pico SDK")
|
||||
set(PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of SDK from git if not otherwise locatable")
|
||||
set(PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download SDK")
|
||||
set(PICO_SDK_FETCH_FROM_GIT_TAG "${PICO_SDK_FETCH_FROM_GIT_TAG}" CACHE FILEPATH "release tag for SDK")
|
||||
|
||||
if (NOT PICO_SDK_PATH)
|
||||
if (PICO_SDK_FETCH_FROM_GIT)
|
||||
include(FetchContent)
|
||||
set(FETCHCONTENT_BASE_DIR_SAVE ${FETCHCONTENT_BASE_DIR})
|
||||
if (PICO_SDK_FETCH_FROM_GIT_PATH)
|
||||
get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}")
|
||||
endif ()
|
||||
FetchContent_Declare(
|
||||
pico_sdk
|
||||
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
|
||||
GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}
|
||||
)
|
||||
|
||||
if (NOT pico_sdk)
|
||||
message("Downloading Raspberry Pi Pico SDK")
|
||||
# GIT_SUBMODULES_RECURSE was added in 3.17
|
||||
if (${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.17.0")
|
||||
FetchContent_Populate(
|
||||
pico_sdk
|
||||
QUIET
|
||||
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
|
||||
GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}
|
||||
GIT_SUBMODULES_RECURSE FALSE
|
||||
|
||||
SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-src
|
||||
BINARY_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-build
|
||||
SUBBUILD_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-subbuild
|
||||
)
|
||||
else ()
|
||||
FetchContent_Populate(
|
||||
pico_sdk
|
||||
QUIET
|
||||
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
|
||||
GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}
|
||||
|
||||
SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-src
|
||||
BINARY_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-build
|
||||
SUBBUILD_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-subbuild
|
||||
)
|
||||
endif ()
|
||||
|
||||
set(PICO_SDK_PATH ${pico_sdk_SOURCE_DIR})
|
||||
endif ()
|
||||
set(FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR_SAVE})
|
||||
else ()
|
||||
message(FATAL_ERROR
|
||||
"SDK location was not specified. Please set PICO_SDK_PATH or set PICO_SDK_FETCH_FROM_GIT to on to fetch from git."
|
||||
)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
get_filename_component(PICO_SDK_PATH "${PICO_SDK_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}")
|
||||
if (NOT EXISTS ${PICO_SDK_PATH})
|
||||
message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' not found")
|
||||
endif ()
|
||||
|
||||
set(PICO_SDK_INIT_CMAKE_FILE ${PICO_SDK_PATH}/pico_sdk_init.cmake)
|
||||
if (NOT EXISTS ${PICO_SDK_INIT_CMAKE_FILE})
|
||||
message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' does not appear to contain the Raspberry Pi Pico SDK")
|
||||
endif ()
|
||||
|
||||
set(PICO_SDK_PATH ${PICO_SDK_PATH} CACHE PATH "Path to the Raspberry Pi Pico SDK" FORCE)
|
||||
|
||||
include(${PICO_SDK_INIT_CMAKE_FILE})
|
||||
@@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sign a Raspberry Pi Pico application image for the 0x0026a bootloader.
|
||||
|
||||
The signer reads the raw application binary (the bytes the bootloader will see
|
||||
in XIP flash), computes an AES-128-CMAC tag over it, and writes the fixed-layout
|
||||
manifest the bootloader expects into the sector at 0x1001F000. The AES and CMAC
|
||||
routines are implemented here so the tool runs on a stock Python 3 install with
|
||||
no third-party packages.
|
||||
|
||||
Examples
|
||||
--------
|
||||
Sign an image and write the manifest::
|
||||
|
||||
python3 sign_firmware.py build/0x0026a_app.bin --out build/manifest.bin
|
||||
|
||||
Verify an existing manifest against an image::
|
||||
|
||||
python3 sign_firmware.py build/0x0026a_app.bin --verify build/manifest.bin
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import struct
|
||||
from pathlib import Path
|
||||
|
||||
MANIFEST_MAGIC = 0x424C4657
|
||||
MANIFEST_VERSION = 1
|
||||
MANIFEST_SECTOR_SIZE = 4096
|
||||
DEFAULT_APP_BASE = 0x10020000
|
||||
DEFAULT_KEY = b"IronNetBootKey!!"
|
||||
RB = 0x1B
|
||||
RB_128 = 0x87
|
||||
|
||||
SBOX = (
|
||||
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B,
|
||||
0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,
|
||||
0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26,
|
||||
0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
|
||||
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2,
|
||||
0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0,
|
||||
0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED,
|
||||
0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
|
||||
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F,
|
||||
0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5,
|
||||
0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC,
|
||||
0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
|
||||
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14,
|
||||
0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C,
|
||||
0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D,
|
||||
0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
|
||||
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F,
|
||||
0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E,
|
||||
0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11,
|
||||
0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
|
||||
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F,
|
||||
0xB0, 0x54, 0xBB, 0x16,
|
||||
)
|
||||
|
||||
RCON = (0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36)
|
||||
|
||||
|
||||
def _xtime(value: int) -> int:
|
||||
"""Multiply a byte by x in GF(2^8)."""
|
||||
value <<= 1
|
||||
return (value ^ RB) & 0xFF if value & 0x100 else value
|
||||
|
||||
|
||||
def _expand_key(key: bytes) -> list[int]:
|
||||
"""Expand a 16-byte key into the 176-byte AES-128 round key schedule."""
|
||||
schedule = list(key)
|
||||
for index in range(16, 176, 4):
|
||||
word = schedule[index - 4:index]
|
||||
if index % 16 == 0:
|
||||
word = word[1:] + word[:1]
|
||||
word = [SBOX[byte] for byte in word]
|
||||
word[0] ^= RCON[index // 16 - 1]
|
||||
for offset in range(4):
|
||||
schedule.append(schedule[index - 16 + offset] ^ word[offset])
|
||||
return schedule
|
||||
|
||||
|
||||
def _add_round_key(state: list[int], schedule: list[int]) -> None:
|
||||
"""XOR the round key into the state in place."""
|
||||
for index in range(16):
|
||||
state[index] ^= schedule[index]
|
||||
|
||||
|
||||
def _sub_bytes(state: list[int]) -> None:
|
||||
"""Apply the AES S-box to every byte of the state."""
|
||||
for index in range(16):
|
||||
state[index] = SBOX[state[index]]
|
||||
|
||||
|
||||
def _shift_rows(state: list[int]) -> None:
|
||||
"""Rotate each row of the AES state left by its row index."""
|
||||
for row in range(1, 4):
|
||||
cells = [state[row + 4 * col] for col in range(4)]
|
||||
cells = cells[row:] + cells[:row]
|
||||
for col in range(4):
|
||||
state[row + 4 * col] = cells[col]
|
||||
|
||||
|
||||
def _mix_columns(state: list[int]) -> None:
|
||||
"""Mix each column of the AES state with the fixed AES matrix."""
|
||||
for col in range(4):
|
||||
base = 4 * col
|
||||
a0, a1, a2, a3 = state[base:base + 4]
|
||||
total = a0 ^ a1 ^ a2 ^ a3
|
||||
state[base + 0] = a0 ^ total ^ _xtime(a0 ^ a1)
|
||||
state[base + 1] = a1 ^ total ^ _xtime(a1 ^ a2)
|
||||
state[base + 2] = a2 ^ total ^ _xtime(a2 ^ a3)
|
||||
state[base + 3] = a3 ^ total ^ _xtime(a3 ^ a0)
|
||||
|
||||
|
||||
def aes_encrypt_block(block: bytes, schedule: list[int]) -> bytes:
|
||||
"""Encrypt one 16-byte block with the supplied round key schedule."""
|
||||
state = list(block)
|
||||
_add_round_key(state, schedule)
|
||||
for round_index in range(1, 10):
|
||||
_sub_bytes(state)
|
||||
_shift_rows(state)
|
||||
_mix_columns(state)
|
||||
_add_round_key(state, schedule[16 * round_index:])
|
||||
_sub_bytes(state)
|
||||
_shift_rows(state)
|
||||
_add_round_key(state, schedule[160:])
|
||||
return bytes(state)
|
||||
|
||||
|
||||
def _double(block: bytes) -> bytes:
|
||||
"""Left-shift a 128-bit big-endian value, folding in the CMAC constant."""
|
||||
value = int.from_bytes(block, "big")
|
||||
value <<= 1
|
||||
if block[0] & 0x80:
|
||||
value ^= RB_128
|
||||
return (value & ((1 << 128) - 1)).to_bytes(16, "big")
|
||||
|
||||
|
||||
def _subkeys(schedule: list[int]) -> tuple[bytes, bytes]:
|
||||
"""Derive the RFC 4493 K1 and K2 subkeys."""
|
||||
k1 = _double(aes_encrypt_block(bytes(16), schedule))
|
||||
return k1, _double(k1)
|
||||
|
||||
|
||||
def _xor(left: bytes, right: bytes) -> bytes:
|
||||
"""XOR two equal-length byte strings."""
|
||||
return bytes(a ^ b for a, b in zip(left, right))
|
||||
|
||||
|
||||
def aes128_cmac(key: bytes, message: bytes) -> bytes:
|
||||
"""Return the RFC 4493 AES-128-CMAC tag of a message."""
|
||||
schedule = _expand_key(key)
|
||||
k1, k2 = _subkeys(schedule)
|
||||
blocks = [message[i:i + 16] for i in range(0, len(message), 16)]
|
||||
complete = bool(blocks) and len(blocks[-1]) == 16
|
||||
if not complete:
|
||||
tail = (blocks[-1] + b"\x80") if blocks else b"\x80"
|
||||
blocks = blocks[:-1] + [tail.ljust(16, b"\x00")]
|
||||
last = blocks[-1]
|
||||
last = _xor(last, k1 if complete else k2)
|
||||
state = bytes(16)
|
||||
for block in blocks[:-1]:
|
||||
state = aes_encrypt_block(_xor(state, block), schedule)
|
||||
return aes_encrypt_block(_xor(state, last), schedule)
|
||||
|
||||
|
||||
def build_manifest(app: bytes, app_base: int, key: bytes) -> bytes:
|
||||
"""Assemble the padded manifest sector for an application image."""
|
||||
tag = aes128_cmac(key, app)
|
||||
header = struct.pack("<IIII", MANIFEST_MAGIC, MANIFEST_VERSION, app_base,
|
||||
len(app)) + tag
|
||||
return header.ljust(MANIFEST_SECTOR_SIZE, b"\xFF")
|
||||
|
||||
|
||||
def _parse_key(text: str) -> bytes:
|
||||
"""Decode a hex or UTF-8 key argument into 16 bytes."""
|
||||
raw = bytes.fromhex(text) if len(text) == 32 else text.encode()
|
||||
if len(raw) != 16:
|
||||
raise argparse.ArgumentTypeError("key must be 16 bytes")
|
||||
return raw
|
||||
|
||||
|
||||
def _read_image(path: str) -> bytes:
|
||||
"""Read an application binary from disk."""
|
||||
data = Path(path).read_bytes()
|
||||
if not data:
|
||||
raise SystemExit(f"error: {path} is empty")
|
||||
return data
|
||||
|
||||
|
||||
def _cmd_sign(args: argparse.Namespace) -> int:
|
||||
"""Sign an image and write the manifest sector."""
|
||||
app = _read_image(args.image)
|
||||
manifest = build_manifest(app, args.app_base, args.key)
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_bytes(manifest)
|
||||
tag = manifest[16:32].hex()
|
||||
print(f"image : {args.image} ({len(app)} bytes)")
|
||||
print(f"app_base : 0x{args.app_base:08x}")
|
||||
print(f"cmac tag : {tag}")
|
||||
print(f"manifest : {out} ({len(manifest)} bytes)")
|
||||
return 0
|
||||
|
||||
|
||||
def _cmd_verify(args: argparse.Namespace) -> int:
|
||||
"""Recompute the tag and compare it against a manifest on disk."""
|
||||
app = _read_image(args.image)
|
||||
manifest = Path(args.verify).read_bytes()
|
||||
stored = manifest[16:32]
|
||||
expected = aes128_cmac(args.key, app)
|
||||
print(f"stored : {stored.hex()}")
|
||||
print(f"computed : {expected.hex()}")
|
||||
if stored != expected:
|
||||
print("result : MISMATCH")
|
||||
return 1
|
||||
print("result : MATCH")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Parse arguments and dispatch to sign or verify."""
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("image", help="raw application .bin to sign")
|
||||
parser.add_argument("--out", default="manifest.bin",
|
||||
help="manifest output path (default: manifest.bin)")
|
||||
parser.add_argument("--app-base", type=lambda v: int(v, 0),
|
||||
default=DEFAULT_APP_BASE,
|
||||
help="application base address (default: 0x10020000)")
|
||||
parser.add_argument("--key", type=_parse_key, default=DEFAULT_KEY,
|
||||
help="16-byte AES key as text or 32 hex digits")
|
||||
parser.add_argument("--verify", metavar="MANIFEST",
|
||||
help="verify an existing manifest instead of signing")
|
||||
args = parser.parse_args()
|
||||
if args.verify:
|
||||
return _cmd_verify(args)
|
||||
return _cmd_sign(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -579,6 +579,18 @@ Structures and Functions in Embedded Systems: Debugging and Hacking w/ IR Remote
|
||||
|
||||
## Week 11-IDA Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK11/WEEK11-IDA.md)
|
||||
|
||||
## Week 11a Secure Boot + Custom Bootloader Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/0x0026a_custom-bootloader/WEEK11a.md)
|
||||
|
||||
### 0x0026a Custom Secure Bootloader [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/0x0026a_custom-bootloader/README.md)
|
||||
|
||||
### 0x0026a Bootloader BIN [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/0x0026a_custom-bootloader/0x0026a_bootloader.bin)
|
||||
|
||||
### 0x0026a Bootloader UF2 [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/0x0026a_custom-bootloader/0x0026a_bootloader.uf2)
|
||||
|
||||
### 0x0026a Signed Application BIN [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/0x0026a_custom-bootloader/0x0026a_app.bin)
|
||||
|
||||
### 0x0026a Manifest BIN [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/0x0026a_custom-bootloader/manifest.bin)
|
||||
|
||||
### Chapter 35: Structures
|
||||
This chapter covers structures as well as an intro to infrared basics as we work a infrared receiver and infrared remote controller as it relates to embedded development on the Pico 2.
|
||||
|
||||
|
||||
Reference in new issue
Block a user