Merge branch 'main' into vault2

This commit is contained in:
bunnie 2025-10-08 01:19:08 +08:00 committed by GitHub
commit 3df456532c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
33 changed files with 2627 additions and 234 deletions

5
.gitignore vendored
View file

@ -84,3 +84,8 @@ share/python-wheels/
*.egg
*.pyc
MANIFEST
# Deployment credentials
signing/credentials
# Signer target directory
signing/fido-signer/target

10
.vscode/settings.json vendored
View file

@ -8,11 +8,11 @@
"--target-dir",
"target/analyzer",
"--features",
"precursor",
"bao1x",
"--features",
"utralib/precursor",
"utralib/bao1x",
"--features",
"utralib/precursor-pvt",
"board-baosec",
"--message-format",
"json"
],
@ -20,9 +20,9 @@
"XOUS_SVD_FILE": "../precursors/soc.svd"
},
"rust-analyzer.cargo.features": [
"precursor",
"bao1x",
"board-baosec",
"swap",
"mass-storage"
],
"rust-analyzer.files.excludeDirs": [
"./loader/**"

8
Cargo.lock generated
View file

@ -800,18 +800,18 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]]
name = "bytemuck"
version = "1.19.0"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8334215b81e418a0a7bdb8ef0849474f40bb10c8b71f1c4ed315cff49f32494d"
checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4"
dependencies = [
"bytemuck_derive",
]
[[package]]
name = "bytemuck_derive"
version = "1.10.1"
version = "1.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f154e572231cb6ba2bd1176980827e3d5dc04cc183a75dea38109fbdd672d29"
checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"
dependencies = [
"proc-macro2",
"quote",

View file

@ -144,6 +144,8 @@ exclude = [
"libs/mass-storage/packing",
# This directory is dedicated to out-of-tree tests and examples
"planning/",
# This is for signing images, and requires dependencies that are incompatible with Xous
"signing/fido-signer"
]
[profile.release]

View file

@ -1,12 +1,49 @@
# "Baochip" / "bao1x" Series API Organization & Glossary
# Getting Started with Baochip Targets
Baochip-based boards use the `bao1x` SoC. There are two boards supported out-of-the-box:
- `dabao` is a minimal SoM-style breakout board. Basically just the chip on a board.
- `baosec` is a hardware security token. It features a camera, display, external memory, buttons, and a supplemental hardware TRNG.
Regardless of the board, the `bao1x` chip comes from the factory programmed with `boot0` and `boot1` stages. The code for these can be found in `bao1x-boot/`.
- `boot0` is a permanent root of trust burned onto the chip. Its sole purpose is to validate `boot1`. See [security model](./README-baochip.md#security-model) for details on the trust chain
- `boot1` contains a USB driver, serial-over-USB driver, and serial driver capable of accepting code updates in the form of .u2f files or serial commands. It also contains a small command terminal for managing configurations, keys, and device lifecycle state.
Three application targets are supported by Xous:
- `baremetal` is an unsecured, bare-iron environment. It is `no-std`, but comes with `alloc` pre-initialized and a USB serial console.
- `dabao` is a Xous environment. It boots a full kernel, supports `std`, and features "detached-apps", i.e., users can develop stand-alone applications that run on the OS without having to touch the kernel image.
- `baosec` is a Xous environment. It is like `dabao`, but supports swap memory. As a result it can run much larger, more complicated applications. The on-chip RRAM is reserved for the kernel, while the off-chip swap contains user applications.
Code is delivered via `boot1`. `boot1` is entered by holding down a button while power the device on. The device will show up as a USB mass storage device, at which point a .uf2 file containing the application image is copied to the device, and the update is applied.
## Security Model
The default `bao1x` chips come from the factory with four public keys burned into them:
- Two code deployment signing keys
- One beta signing key
- One developer key (anyone can use the [private key](./devkey/README.md) to sign a developer image)
In addition to these public keys, a collection of initial identifiers and secrets are generated on-device which serve as the security root. Each boot stage has a copy of these public keys; thus the key set can be updated/changed for downstream artifacts. boot0/boot1 should be rarely, if ever, updated; meanwhile detached application images running within the OS environment may have more permissive signing policies since memory protection is enforced by the OS.
By default, the `bao1x` will accept and run developer images; however upon encountering a developer image anywhere in the boot chain, all the initial secrets are erased, and a one-way counter is incremented to indicate the device is a developer device. From this point developers can generate new keys, but any device attestation or on-chip secrets programmed into the device are lost.
The developer key can be revoked by running `lockdown` at the `boot1` stage. `baosec` boards have this done at the factory prior to shipment, to prevent tampering in the supply chain.
## API Organization
The Baochip platform has the following API structure. Note that
`bao1x` is the original code name for the target chip, which after
two years of extensive code development migrated to the `baochip`
brand name. At the moment the misnaming stands, due to the amount
of code that carries the legacy name.
The Baochip platform has the following API structure.
`apps-dabao`: Applications for the dabao platform
`apps-baosec`: Applications for the baosec platform
`bao1x-boot`: Secure bootloader chain for the Baochip platform. The
bootloader code has settings for three targets, `dabao`, `baosec`,
and `oem`. The `oem` setting is intended for developers who want
to do their own custom board.
`libs/bao1x-api`: contains hardware-abstracted API code to the hardware
layers (traits, some constants, enums, etc.). For example, "here is
@ -47,10 +84,12 @@ you may encounter in this project.
`daric`: Internal code name for the SoC while in development.
`crossbar`: The parent company that shouldered the cost of taping out the SoC.
Most of the OSS SoC code has its copyright assigned to this organization;
so, this is probably the most relevant legal entity even though its
name doesn't appear in marketing materials.
`crossbar`: Baochip made it's SoC by "hitchiking" on Crossbar's tape-out. Crossbar
thus shouldered the cost of taping out the SoC, while Baochip made light-fingered
changes that made the chip amenable to running Xous. Most of the OSS SoC code
has its copyright assigned to this organization; so, this is probably the
most relevant third-party legal entity, even though its name doesn't appear
in marketing materials.
`baochip`: The name of a new company formed to market an OSS- and Xous-focused
variant of the `daric` chip. This is the relevant legal organization in terms

0
README-precursor.md Normal file
View file

185
README.md
View file

@ -2,157 +2,74 @@
Core files for the Xous microkernel operating system.
You might find this [wiki](https://github.com/betrusted-io/betrusted-wiki/wiki) handy, as well as the [Xous Book](https://betrusted.io/xous-book/).
The [Xous Book](https://betrusted.io/xous-book/) covers the architecture and structure of the kernel.
Users targeting Baochip platforms should also familiarize with the [Boachip API structure and glossary](./README-baochip.md) as the platform has several targets and gone through numerous name changes.
The [wiki](https://github.com/betrusted-io/betrusted-wiki/wiki) is a community resource that answers many FAQ.
This repository contains everything necessary to build the Xous kernel
from source. It consists of the following projects:
The [Boachip README](./README-baochip.md) is the starting point for Baochip users.
* **kernel**: core memory manager, irq manager, and syscallhandler
* **loader**: initial loader used to start the kernel
* **tools**: programs used to construct a final boot image
* **docs**: documentation on various aspects of Xous
The [Precursor README](./README-precursor.md) is the starting point for Precursor users.
Xous is a mono-repo project. It contains the kernel, libraries, applications, and tools necessary to build full device images. Here is a brief description of the more important directories:
* **api**: "Secular" API libraries - minimal-dependency, common-core APIs used by core Xous services
* **apps**: Precursor applications
* **apps-dabao**: Dabao applications
* **apps-baosec**: Baosec applications
* **bao1x-boot**: Bao1x secure boot chain
* **baremetal**: Baremetal target - runs after the boot chain, for developers that don't want Xous but can still use Xous' `no-std` features
* **emulation**: Renode scripts used to emulate Xous
* **xous-rs**: userspace library
* **imports**: Vendored-in libraries that had to be forked for Xous compatibility
* **kernel**: core memory manager, irq manager, and syscall implementations.
* **libs**: Device driver libraries. The common thread is that none of these code bases contain a `main.rs`, just a `lib.rs`.
* **loader**: Sets up virtual memory space and boots the kernel
* **locales**: Tools for handling internationalization
* **signing**: Scripts for generating signed images
* **services**: Xous programs that support Xous apps. Middleware, if you will.
* **svd2utra**: A program for converting SVD chip descriptions in XML to the UTRA "header file" format
* **tools**: Programs used to construct a final boot image. Also the home of various diagnostic and test utilities.
* **utralib**: The [Unambigous Thin Register Abtraction](./utralib/README.md). The core hardware interface for Xous.
* **xous-ipc**: Inter-process communication convenience APIs for Xous
* **xous-rs**: API files for the kernel. Where the syscall interfaces live.
* **xtask**: The build system manager for Xous.
## Dependencies
- Xous requires its own Rust target, `riscv32imac-unknown-xous-elf`. If you run `cargo xtask` from the command line, you should be prompted to install the target automatically if it does not already exist.
- You may need to remove the `target/` directory before building, if `rustc` continues to behave like it can't find the `xous` target even after it is installed.
- If you plan on doing USB firmware updates, you'll need `progressbar2` (updates) and `pyusb` (updates). Note that `pyusb` has name space conflicts with similarly named packages, so if updates aren't working you may need to create a `venv` or uninstall conflicting packages.
- If you are doing development on the digital signatures with the Python helper scripts, you will need: `pycryptodome` (signing - PEM read), `cryptography` (signing - x509 read), `pynacl` (signing - ed25519 signatures) (most users won't need this).
- Some system packages are needed, which can be installed with `sudo apt install libssl-dev libxkbcommon-dev` or similar
- If you receive an error about `feature resolver is required`, try installing a newer version of `rustc` and `cargo` via [rustup](https://rustup.rs)
Install the latest [Rust](https://rust-lang.org/tools/install/) or run `rustup update` to update your Rust installation prior to building. Xous development assumes a recent version of Rust.
## Build Commands
- Precursor: `cargo xtask app-image`
- Dabao: `cargo xtask dabao`
- Baosec: `cargo xtask baosec`
- Baochip baremetal: `cargo xtask baremetal-bao1x`
Additional apps to be bundled into images can be specified as extra arguments on the command line, e.g. `cargo xtask dabao helloworld` will generate a Dabao image that includes `helloworld` in the detached-app section. Features, app-features, loader-features, and so forth can also be passed as command line arguments; run `cargo xtask` on its own for more help.
## Emulation
- `cargo xtask run` will bring up an emulated Precursor
- `cargo xtask baosec-emu` will bring up an emulated Baosec
- `cargo xtask renode-image` will build an image suitable for [Renode](https://renode.io/#downloads) emulation of a Precursor target. Start renode by running `renode emulation/xous-release.resc`
## Building Documentation
A flag of `--feature doc-deps` must be passed when running `cargo doc`, like this:
`cargo doc --no-deps --feature doc-deps`
This flag is required because Xous requires a target board to be specified in
all build configurations. `doc-deps` specifies a set of dummy dependencies
that satisfy board requirements for the purpose of building documentation.
`doc-deps` is a dummy hardware target that satisfies the requirement of
a "board" when building documentation.
## Local-vs-crates.io Verification
By default the `xtask` resolver runs a check to confirm that your local files
match the ones referenced in `crates.io`. For a handful of core crates, the
build preferentially runs from what is on `crates.io`, so local changes have
no effect until they are pushed as an update to an existing crate. If you see
an error complaining about local source files not being published, make sure
you have the correct patches in place in your top level `Cargo.toml` file,
and bypass the check with `--no-verify`.
## Quickstart using Hosted Mode
`xtask` does a check every build to ensure that any `crates.io` dependencies
are synchronized with the contents of the monorepo. It protects against the
scenario where you edited a crate that exists in the Xous repo, but the
build system ignores the local edits because it's fetching an old version from
`crates.io`.
You can try out Xous in a "hosted mode" wherein programs are compiled
for your native platform and are run locally as processes within your
current operating system. System calls are replaced with network calls
to a kernel that simply shuffles messages around.
Xous uses the [xtask](https://github.com/matklad/cargo-xtask/) convention,
where various complex build commands are stored under `cargo xtask`.
This allows for us to create arbitrarily complex build sequences
without resorting to `make` (which is platform-dependent),
`sh` (which requires a lot of external tooling), or another build
system.
To build a set of sample programs and run them all using the
kernel for communication, clone this repository and run:
```sh
cargo xtask run
```
This will build several servers and a "shell" program to control them
all. Most notably, a `graphics-server` will appear and kernel messages
will begin scrolling in your terminal.
### Hosted Mode UI navigation
| Precursor | Host |
| ------------------- | ----------- |
| D-pad middle button | Home |
| D-pad up | up arrow |
| D-pad down | down arrow |
| D-pad left | left arrow |
| D-pad right | right arrow |
## Quickstart using an emulator
Xous uses [Renode](https://renode.io/) as the preferred emulator, because
it is easy to extend the hardware peripherals without recompiling the
entire emulator.
Due to a breaking change in Renode, this codebase is only compatible with Renode equal to or later than `1.15.2.7965 (e6e79aad-202408180425)`
[Download Renode](https://renode.io/#downloads) and ensure it is in your path.
For now, you need to [download the nightly build](https://dl.antmicro.com/projects/renode/builds/),
until `DecodedOperation` is included in the release.
Then, build Xous:
```sh
cargo xtask renode-image
```
This will compile everything in `release` mode for RISC-V, compile the tools
require to package it all up, then create an image file.
Finally, run Renode and specify the `xous-release.resc` REnode SCript:
```sh
renode emulation/xous-release.resc
```
Renode will start emulation automatically, and will run the same set of programs
as in "Hosted mode".
## Generating a hardware image
To build for real hardware, you must specify an `.svd` file. This
file is generated by the SoC build process and describes a single
Betrusted core. These addresses will change as hardware is modified,
so if you distribute a modified Betrusted core, you should be sure
to distribute the `.svd` file.
The [UTRA](./utralib/README.md) abstracts the details of the register
locations, by wrapping them in logical names that don't change.
For Precursor, the SVD files are tracked inside `utralib/precursor/soc-<gitref>.svd`.
Since each soc.svd can potentially change with a git reference, a gitref
is coded into the filename by convention.
Generally, one can create an image for hardware using the following command:
```sh
cargo xtask app-image-xip
```
And it will pull from the default soc.svd configuration.
The currently selected config is set by the constant `PRECURSOR_SOC_VERSION`
in [xtask/src/main.rs](./xtask/src/main.rs); it is one of the first constants
near the top.
If you have built your own custom soc.svd file, the most convenient way to update
to this is to simply replace the file referenced in the default with yours,
and then run `cargo build` inside the `utralib` directory (not in the Xous
root -- the `build` command must happen inside the directory to force a
regeneration of the generated UTRA bindings). This will likely result
in a complaint when you run `xtask` that your local tree does not match what
is checked into `git`; if you are building from your own configuration,
that is correct, and thus you should add `--no-verify` to your `xtask` command
to suppress the check.
Note that adding a full extra custom gitrev is more involved, it involves
editing the [utralib/Cargo.toml](./utralib/Cargo.toml) and [utralib/build.rs](./utralib/build.rs)
to reference your new artifact as a brand new feature flag.
The resulting images are in your target directory (typically `target/riscv32imac-unknown-xous-elf/release/`)
with the names `xous.img` (for the kernel) and `loader.bin` (for its bootloader). The corresponding
gateware is in `precursors/soc_csr-<gitref>.bin`. These can be written to your
device by following the [update guide](https://github.com/betrusted-io/betrusted-wiki/wiki/Updating-Your-Device).
Developers working on published crates should patch them in the root `Cargo.toml`
file and bypass the check with `--no-verify`.
## Acknowledgement
This project is funded through the NGI0 PET Fund, a fund established by NLnet

View file

@ -3,6 +3,7 @@ use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use bao1x_api::signatures::FunctionCode;
#[allow(unused_imports)]
use bao1x_api::*;
use bao1x_hal::acram::OneWayCounter;
@ -21,10 +22,13 @@ pub struct Repl {
cmdline: String,
do_cmd: bool,
local_echo: bool,
lockdown_armed: bool,
}
impl Repl {
pub fn new() -> Self { Self { cmdline: String::new(), do_cmd: false, local_echo: true } }
pub fn new() -> Self {
Self { cmdline: String::new(), do_cmd: false, local_echo: true, lockdown_armed: false }
}
#[allow(dead_code)]
pub fn init_cmd(&mut self, cmd: &str) {
@ -69,6 +73,32 @@ impl Repl {
let mut parts = self.cmdline.split_whitespace();
let cmd = parts.next().unwrap_or("").to_string();
let args: Vec<String> = parts.map(|s| s.to_string()).collect();
// process two-phase lockdown command
if self.lockdown_armed {
if args.len() == 0 && cmd.as_str() == "YES" {
let owc = OneWayCounter::new();
let devkey_offsets = [
("loader", LOADER_REVOCATION_OFFSET + bao1x_api::pubkeys::DEVELOPER_KEY_SLOT),
("boot0", BOOT0_REVOCATION_OFFSET + bao1x_api::pubkeys::DEVELOPER_KEY_SLOT),
("boot1", BOOT1_REVOCATION_OFFSET + bao1x_api::pubkeys::DEVELOPER_KEY_SLOT),
];
for &(desc, devkey) in devkey_offsets.iter() {
match unsafe { owc.inc(devkey) } {
Ok(_) => crate::println!("{} locked", desc),
Err(e) => crate::println!("Couldn't lock {}: {:?}", desc, e),
}
}
} else {
crate::println!("Lockdown aborted.");
}
self.lockdown_armed = false;
self.abort_cmd();
return Ok(());
}
self.lockdown_armed = false;
// now process any further commands
match cmd.as_str() {
"reset" => {
let mut rcurst = CSR::new(utra::sysctrl::HW_SYSCTRL_BASE as *mut u32);
@ -168,6 +198,120 @@ impl Repl {
}
crate::println!("Board type set to {:?} after {} increments", new_type, count);
}
"audit" => {
let owc = OneWayCounter::new();
crate::println!(
"Board type reads as: {:?}",
owc.get_decoded::<bao1x_api::offsets::BoardTypeCoding>()
);
crate::println!(
"Boot partition is: {:?}",
owc.get_decoded::<bao1x_api::offsets::AltBootCoding>()
);
crate::println!("Revocations:");
crate::println!("Stage key0 key1 key2 key3");
let key_array = [
("boot0 ", BOOT0_REVOCATION_OFFSET),
("boot1 ", BOOT1_REVOCATION_OFFSET),
("next stage ", LOADER_REVOCATION_OFFSET),
];
for (img_type, start) in key_array {
crate::print!("{}", img_type);
for offset in start..(start + PUBKEY_SLOTS) {
if owc.get(offset).unwrap_or(1) == 0 {
crate::print!("enabled ");
} else {
crate::print!("revoked ");
}
}
crate::println!("");
}
match bao1x_hal::sigcheck::validate_image(
bao1x_api::BOOT0_START as *const u32,
bao1x_api::BOOT0_START as *const u32,
bao1x_api::BOOT0_REVOCATION_OFFSET,
&[FunctionCode::Boot0 as u32],
false,
None,
) {
Ok((k, tag)) => crate::println!(
"Boot0: key {} ({})",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
),
Err(e) => crate::println!("Boot0 did not validate: {:?}", e),
}
match bao1x_hal::sigcheck::validate_image(
bao1x_api::BOOT1_START as *const u32,
bao1x_api::BOOT0_START as *const u32,
bao1x_api::BOOT0_REVOCATION_OFFSET,
&[
FunctionCode::Boot1 as u32,
FunctionCode::UpdatedBoot1 as u32,
FunctionCode::Developer as u32,
],
false,
None,
) {
Ok((k, tag)) => crate::println!(
"Boot1: key {} ({})",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
),
Err(e) => crate::println!("Boot1 did not validate: {:?}", e),
}
match bao1x_hal::sigcheck::validate_image(
bao1x_api::LOADER_START as *const u32,
bao1x_api::BOOT1_START as *const u32,
bao1x_api::BOOT1_REVOCATION_OFFSET,
&crate::secboot::ALLOWED_FUNCTIONS,
false,
None,
) {
Ok((k, tag)) => crate::println!(
"Next stage: key {} ({})",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
),
Err(e) => crate::println!("Next stage did not validate: {:?}", e),
}
// TODO:
// - devboot seen
// - oem keys erased
// - uuid
}
"lockdown" => {
match bao1x_hal::sigcheck::validate_image(
bao1x_api::BOOT1_START as *const u32,
bao1x_api::BOOT0_START as *const u32,
bao1x_api::BOOT0_REVOCATION_OFFSET,
&[
FunctionCode::Boot1 as u32,
FunctionCode::UpdatedBoot1 as u32,
FunctionCode::Developer as u32,
],
false,
None,
) {
Ok((k, _tag)) => {
if k != bao1x_api::pubkeys::DEVELOPER_KEY_SLOT {
crate::println!(
"This will permanently disable developer mode. It cannot be undone!"
);
crate::println!("Proceed? (type 'YES' in all caps to proceed)");
self.lockdown_armed = true;
} else {
crate::println!(
"Boot1 is signed with the developer key. Refusing to lockdown, as that would brick the chip."
)
}
}
Err(_e) => {
crate::println!("Boot1 has no valid signature, lockdown would brick the chip.")
}
}
}
#[cfg(feature = "unsafe-debug")]
"peek" => {
const COLUMNS: usize = 4;
@ -206,7 +350,9 @@ impl Repl {
}
_ => {
crate::println!("Command not recognized: {}", cmd);
crate::print!("Commands include: reset, echo, boot, bootwait, localecho, uf2, boardtype");
crate::print!(
"Commands include: reset, echo, boot, bootwait, localecho, uf2, boardtype, audit, lockdown"
);
crate::println!("");
}
}

View file

@ -1,6 +1,6 @@
use bao1x_api::signatures::FunctionCode;
const ALLOWED_FUNCTIONS: [u32; 5] = [
pub const ALLOWED_FUNCTIONS: [u32; 5] = [
FunctionCode::Baremetal as u32,
FunctionCode::UpdatedBaremetal as u32,
FunctionCode::Loader as u32,
@ -32,7 +32,11 @@ pub fn boot_or_die() -> ! {
true,
None,
) {
Ok(k) => crate::println!("**should be unreachable** Booted with key {}", k),
Ok((k, tag)) => crate::println!(
"**should be unreachable** Booted with key {}({})",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
),
Err(e) => crate::println!("Image did not validate: {:?}", e),
}
crate::println!("No valid loader or baremetal image found. Halting!");

247
baosign.ps1 Normal file
View file

@ -0,0 +1,247 @@
# Image Signing and Deployment Automation Script
# Invoke with e.g. .\baosign.ps1 -Config dabao
# From the root of xous-core. Must be run in a powershell session with administrator privileges
# in order to access the signing token.
#
# TODO: port to a Linux environment so signing can be done on CI-generated builds - once we
# have setup the full signing process.
param(
[Parameter(Mandatory = $true)]
[ValidateSet("baremetal", "dabao", "baosec")]
[string]$Config,
[Parameter(Mandatory = $false)]
[string]$CredentialFile = "beta.json",
[Parameter(Mandatory = $false)]
[string]$Target = "bunnie@10.0.245.183:code/jtag-tools/"
)
# Configuration
$TARGET = $Target
$SIGNING_DIR = ".\signing\fido-signer"
# Define configurations and their associated images with function codes
# Modify these mappings according to your actual image names and function codes
$configurations = @{
"baremetal" = @(
@{ Image = "bao1x-boot0.img"; FunctionCode = "boot0" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "baremetal.img"; FunctionCode = "baremetal" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" }
)
"dabao" = @(
@{ Image = "bao1x-boot0.img"; FunctionCode = "boot0" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
@{ Image = "xous.img"; FunctionCode = "kernel" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
@{ Image = "app.img"; FunctionCode = "app" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
)
"baosec" = @(
@{ Image = "bao1x-boot0.img"; FunctionCode = "boot0" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "bao1x-boot1.img"; FunctionCode = "boot1" ; TargetDir = "target\riscv32imac-unknown-none-elf\release" },
@{ Image = "loader.bin"; FunctionCode = "loader" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
@{ Image = "xous.img"; FunctionCode = "kernel" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
@{ Image = "swap.img"; FunctionCode = "swap" ; TargetDir = "target\riscv32imac-unknown-xous-elf\release" }
)
}
# Color output functions for better visibility
function Write-Status {
param([string]$Message)
Write-Host $Message -ForegroundColor Cyan
}
function Write-Success {
param([string]$Message)
Write-Host $Message -ForegroundColor Green
}
function Write-Error {
param([string]$Message)
Write-Host "ERROR: $Message" -ForegroundColor Red
}
function Write-Warning {
param([string]$Message)
Write-Host "WARNING: $Message" -ForegroundColor Yellow
}
# Function to calculate MD5 hash
function Get-MD5Hash {
param([string]$FilePath)
if (Test-Path $FilePath) {
$hash = Get-FileHash -Path $FilePath -Algorithm MD5
return $hash.Hash.ToLower()
}
else {
Write-Warning "File not found for MD5 calculation: $FilePath"
return $null
}
}
# Function to copy files via SSH
function Copy-ToSSH {
param(
[string]$LocalPath,
[string]$RemoteTarget
)
if (Test-Path $LocalPath) {
try {
# Using scp for file transfer
$scpCommand = "scp `"$LocalPath`" `"$RemoteTarget`""
Write-Status " Copying: $LocalPath -> $RemoteTarget"
$result = Invoke-Expression $scpCommand 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Success " Successfully copied: $(Split-Path $LocalPath -Leaf)"
return $true
}
else {
Write-Error "Failed to copy file: $result"
return $false
}
}
catch {
Write-Error "Exception during SCP: $_"
return $false
}
}
else {
Write-Error "Local file not found: $LocalPath"
return $false
}
}
# Main processing loop
Write-Host "`n==========================================" -ForegroundColor Blue
Write-Host " Image Signing and Deployment Script " -ForegroundColor Blue
Write-Host "==========================================" -ForegroundColor Blue
Write-Host ""
Write-Status "Configuration: $Config"
Write-Status "Target SSH: $TARGET"
Write-Status "Credential File: $CredentialFile"
Write-Host ""
$totalImages = 0
$successfulImages = 0
$failedImages = 0
Write-Host "`n------------------------------------------" -ForegroundColor Yellow
Write-Host " Processing Configuration: $Config" -ForegroundColor Yellow
Write-Host "------------------------------------------" -ForegroundColor Yellow
# Process only the selected configuration
$selectedConfig = $configurations[$Config]
foreach ($imageSpec in $selectedConfig) {
$totalImages++
$imageName = $imageSpec.Image
$functionCode = $imageSpec.FunctionCode
$target_dir = $imageSpec.TargetDir
$imagePath = Join-Path $target_dir $imageName
$uf2Name = $imageName -replace '\.(?:bin|img)$', '.uf2'
$uf2Path = Join-Path $target_dir $uf2Name
Write-Host "`nProcessing: $imageName (Function: $functionCode)" -ForegroundColor White
# Check if image exists
if (-not (Test-Path $imagePath)) {
Write-Warning "Image not found: $imagePath (skipping)"
$failedImages++
continue
}
# Change to signing directory
Push-Location $SIGNING_DIR
try {
# Build the cargo run command
$cargoCmd = @(
"cargo", "run", "--",
"--credential-file", "..\credentials\$CredentialFile",
"--file", "..\..\$imagePath",
"--function-code", $functionCode
)
Write-Status "Signing image..."
Write-Status "Command: $($cargoCmd -join ' ')"
# Execute the signing command
& cargo run -- --credential-file "..\credentials\$CredentialFile" --file "..\..\$imagePath" --function-code $functionCode 2>&1 | Tee-Object -Variable result
# $result = cargo run -- --credential-file "..\credentials\$CredentialFile" --file "..\..\$imagePath" --function-code $functionCode | Tee-Object -Variable result
if ($LASTEXITCODE -eq 0) {
Write-Success "Successfully signed: $imageName"
# Return to root directory
Pop-Location
# Calculate and display MD5 checksums
Write-Status "Calculating MD5 checksums..."
$imgMD5 = Get-MD5Hash -FilePath $imagePath
if ($imgMD5) {
Write-Host " MD5 ($imageName): $imgMD5" -ForegroundColor Gray
}
$uf2MD5 = Get-MD5Hash -FilePath $uf2Path
if ($uf2MD5) {
Write-Host " MD5 ($uf2Name): $uf2MD5" -ForegroundColor Gray
}
# Copy files to SSH target
Write-Status "Copying files to remote host..."
$imgCopySuccess = Copy-ToSSH -LocalPath $imagePath -RemoteTarget $TARGET
$uf2CopySuccess = Copy-ToSSH -LocalPath $uf2Path -RemoteTarget $TARGET
if ($imgCopySuccess -and $uf2CopySuccess) {
Write-Success "Completed processing: $imageName"
$successfulImages++
}
else {
Write-Warning "Partial completion for: $imageName (signing OK, copy failed)"
$failedImages++
}
}
else {
Write-Error "Failed to sign image: $imageName"
Write-Error "Error output: $result"
Pop-Location
$failedImages++
}
}
catch {
Write-Error "Exception during signing: $_"
Pop-Location
$failedImages++
}
}
# Summary report
Write-Host "`n==========================================" -ForegroundColor Blue
Write-Host " Summary Report " -ForegroundColor Blue
Write-Host "==========================================" -ForegroundColor Blue
Write-Host "Total images processed: $totalImages" -ForegroundColor White
Write-Success "Successfully processed: $successfulImages"
if ($failedImages -gt 0) {
Write-Error "Failed: $failedImages"
}
else {
Write-Host "Failed: 0" -ForegroundColor White
}
# Exit with appropriate code
if ($failedImages -gt 0) {
exit 1
}
else {
Write-Host "`nAll operations completed successfully!" -ForegroundColor Green
exit 0
}

View file

@ -13,7 +13,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [
"std",
"alloc",
], optional = true }
bytemuck = { version = "1.0", features = ["derive"] }
bytemuck = { version = "1.24", features = ["derive"] }
bitbybit = "1.4.0"
[features]

View file

@ -16,6 +16,7 @@ pub mod offsets;
pub mod sce;
pub mod signatures;
pub use offsets::*;
pub mod pubkeys;
/// UF2 Family ID. Randomly generated, no collisions with the known list, still to be merged
/// into the "official" list

View file

@ -96,3 +96,5 @@ pub const BOOT1_REVOCATION_OFFSET: usize = LOADER_REVOCATION_OFFSET + PUBKEY_SLO
/// Offset in the one-way counter array for boot0 key revocations. Provisions for up to four
/// key slots, from [124..=127].
pub const BOOT0_REVOCATION_OFFSET: usize = BOOT1_REVOCATION_OFFSET + PUBKEY_SLOTS;
// slots from 128..=255 are totally unused by the boot logic

View file

@ -0,0 +1,18 @@
/// ===== PLACEHOLDER - bao2 signing HSM ceremony pending ======
#[allow(unused_imports)]
use super::*;
use crate::signatures::Pubkey;
/// Bao1 public key. Will be extracted from signing/bao1_id_ed25519_sk using extract_sk_credential.py
pub const ID_ED25519_SK_PUB: [u8; 32] = [0u8; 32];
/// Bao1 public key "key handle"
pub const ID_ED25519_SK_CRED_ID: [u8; 241] = [0u8; 241];
/// Bao1 public key "relying party"
pub const ID_ED25519_SK_RP: &'static str = "ssh:";
pub const PUBKEY: Pubkey = Pubkey {
pk: ID_ED25519_SK_PUB,
// Placeholder: tag is 0.
tag: [0u8; 4], // *KEYSLOT_INITIAL_TAGS[BAO1_KEY_SLOT],
};

View file

@ -0,0 +1,18 @@
/// ===== PLACEHOLDER - bao2 signing HSM ceremony pending ======
#[allow(unused_imports)]
use super::*;
use crate::signatures::Pubkey;
/// Bao1 public key. Will be extracted from signing/bao1_id_ed25519_sk using extract_sk_credential.py
pub const ID_ED25519_SK_PUB: [u8; 32] = [0u8; 32];
/// Bao1 public key "key handle"
pub const ID_ED25519_SK_CRED_ID: [u8; 241] = [0u8; 241];
/// Bao1 public key "relying party"
pub const ID_ED25519_SK_RP: &'static str = "ssh:";
pub const PUBKEY: Pubkey = Pubkey {
pk: ID_ED25519_SK_PUB,
// Placeholder: tag is 0.
tag: [0u8; 4], // *KEYSLOT_INITIAL_TAGS[BAO2_KEY_SLOT],
};

View file

@ -0,0 +1,33 @@
use super::*;
use crate::signatures::Pubkey;
/// Beta public key. Extracted from signing/beta_id_ed25519_sk using extract_sk_credential.py
pub const ID_ED25519_SK_PUB: [u8; 32] = [
0x80, 0x97, 0x99, 0x29, 0xed, 0xd0, 0x4e, 0x40, 0x12, 0x4b, 0x52, 0xca, 0xe9, 0xae, 0x54, 0xb2, 0x4b,
0xdf, 0xf7, 0x2a, 0x7b, 0x8a, 0x00, 0x4c, 0x41, 0x06, 0x5b, 0xd1, 0x40, 0x20, 0x78, 0xa7,
];
/// Beta public key "key handle" - used to retrieve the key for signing from the token.
/// Extracted from signing/beta_id_ed25519_sk using extract_sk_credential.py
pub const ID_ED25519_SK_CRED_ID: [u8; 241] = [
0x01, 0x06, 0x60, 0x8b, 0xfa, 0x05, 0x28, 0x24, 0x0d, 0x5b, 0x33, 0x92, 0x1b, 0xb1, 0x38, 0x4e, 0xbe,
0xae, 0xf3, 0xe4, 0x73, 0x7a, 0x5e, 0xb2, 0xd0, 0x7e, 0x77, 0x80, 0x5b, 0x88, 0xcb, 0x1e, 0xd6, 0xea,
0xfc, 0x75, 0xd4, 0x21, 0xc9, 0x41, 0xfa, 0x8d, 0x09, 0xe2, 0x4b, 0x4a, 0x4c, 0xec, 0x98, 0x85, 0xdd,
0x76, 0xc0, 0xfd, 0xa1, 0x66, 0x0c, 0x4d, 0x6e, 0x72, 0xe4, 0xf3, 0xba, 0x6b, 0xba, 0xc0, 0x68, 0xc8,
0x75, 0x32, 0x7b, 0x4f, 0x4d, 0xbd, 0xab, 0x87, 0x36, 0x80, 0xe7, 0x52, 0x58, 0x28, 0x84, 0xf1, 0xb7,
0x80, 0xd1, 0xfc, 0xb0, 0xde, 0xcd, 0x53, 0x00, 0x7e, 0x7a, 0x6b, 0x5b, 0x8c, 0x61, 0x81, 0xea, 0x74,
0xf1, 0xb5, 0x73, 0xde, 0x72, 0x99, 0x2d, 0x2c, 0x07, 0x96, 0x5f, 0x5c, 0x81, 0x08, 0x75, 0xed, 0x11,
0xf3, 0x42, 0x43, 0x66, 0x8b, 0x18, 0xeb, 0x99, 0x42, 0x56, 0x8c, 0x57, 0x8f, 0x7c, 0x03, 0xfa, 0xbf,
0x6e, 0xbd, 0xc8, 0x19, 0xc9, 0x48, 0xd9, 0xc9, 0x69, 0xef, 0x2b, 0xb1, 0x26, 0x6c, 0xd0, 0xd1, 0xa0,
0xd5, 0x2e, 0x1c, 0x37, 0xe3, 0x23, 0x6a, 0x07, 0x56, 0xe5, 0x41, 0x0f, 0x31, 0x7e, 0x62, 0x28, 0xb1,
0x08, 0x85, 0xc8, 0x33, 0xaa, 0xae, 0x94, 0xa8, 0x89, 0x7b, 0xe4, 0x6f, 0xb6, 0x7b, 0xd4, 0xc8, 0xc2,
0x6b, 0x01, 0x21, 0x16, 0x2c, 0xb0, 0x46, 0x15, 0xae, 0xf8, 0x2c, 0x6a, 0x6e, 0x6f, 0xa7, 0x6b, 0x9c,
0x5f, 0x03, 0x4a, 0x3d, 0xda, 0x15, 0x04, 0xcd, 0x2e, 0x09, 0x9d, 0xcc, 0x1d, 0x03, 0xff, 0xb8, 0x2b,
0xe4, 0x97, 0xfe, 0x96, 0x1f, 0x7a, 0x4a, 0xd8, 0x6b, 0x7d, 0x6c, 0xcd, 0x73, 0x3f, 0xaa, 0xfe, 0x94,
0x4a, 0x85, 0x8b,
];
/// Beta public key "relying party"
/// Extracted from signing/beta_id_ed25519_sk using extract_sk_credential.py
pub const ID_ED25519_SK_RP: &'static str = "ssh:";
pub const PUBKEY: Pubkey = Pubkey { pk: ID_ED25519_SK_PUB, tag: *KEYSLOT_INITIAL_TAGS[BETA_KEY_SLOT] };

View file

@ -0,0 +1,11 @@
use super::*;
use crate::signatures::Pubkey;
/// Developer public key. The private key is the devkey/ directory, included here for your
/// convenience: "MC4CAQAwBQYDK2VwBCIEIKindlyNoteThisIsADevKeyDontUseForProduction" (base64)
pub const PUB: [u8; 32] = [
0x1c, 0x9b, 0xea, 0xe3, 0x2a, 0xea, 0xc8, 0x75, 0x07, 0xc1, 0x80, 0x94, 0x38, 0x7e, 0xff, 0x1c, 0x74,
0x61, 0x42, 0x82, 0xaf, 0xfd, 0x81, 0x52, 0xd8, 0x71, 0x35, 0x2e, 0xdf, 0x3f, 0x58, 0xbb,
];
pub const PUBKEY: Pubkey = Pubkey { pk: PUB, tag: *KEYSLOT_INITIAL_TAGS[DEVELOPER_KEY_SLOT] };

View file

@ -0,0 +1,40 @@
use crate::signatures::Pubkey;
pub mod bao1;
pub mod bao2;
pub mod beta;
pub mod developer;
pub const BAO1_KEY_SLOT: usize = 0;
pub const BAO2_KEY_SLOT: usize = 1;
pub const BETA_KEY_SLOT: usize = 2;
pub const DEVELOPER_KEY_SLOT: usize = 3;
/// Nominal purposes of pub key slots:
/// - slot 0 is Baochip secured signing key 1
/// - slot 1 is Baochip secured signing key 2
/// - slot 2 is a Beta signing key. It's kept in a secured token but also available in a development
/// environment.
/// - slot 3 is the Developer signing key. It's a well-known key that anyone can use to sign an image. If
/// revoked, it is not a valid signing key. When not revoked, upon being presented with an image signed by
/// this, the bootloader will automatically erase all device-local secrets.
///
/// The dual signing keys for Baochip allows for a laddered upgrade path in case a signing key
/// needs to be replaced, upgraded, or cycled out for any reason.
pub const KEYSLOT_INITIAL_TAGS: [&'static [u8; 4]; 4] = [b"bao1", b"bao2", b"beta", b"dev "];
// helper function to pad arrays out, if needed. Previously used for auth_data until
// I realized that auth_data changes with every signing.
#[allow(dead_code)]
const fn pad_array<const N: usize, const M: usize>(input: &[u8; N]) -> [u8; M] {
let mut result = [0u8; M];
let mut i = 0;
while i < N && i < M {
result[i] = input[i];
i += 1;
}
result
}
/// This is the exported record that should be copied into the header of all boot images
pub const PUBKEY_HEADER: [Pubkey; 4] = [bao1::PUBKEY, bao2::PUBKEY, beta::PUBKEY, developer::PUBKEY];

View file

@ -1,11 +1,15 @@
use bytemuck::{Pod, Zeroable};
pub const SIGBLOCK_LEN: usize = 768; // this is adjusted inside builder.rs, in the sign-image invocation
// The jump instruction and the signature itself are not protected
pub const UNSIGNED_LEN: usize = size_of::<u32>() + SIGNATURE_LENGTH;
/// Total reserved space for the signature block
pub const SIGBLOCK_LEN: usize = 768;
/// The jump instruction and the signature itself are not protected
pub const UNSIGNED_LEN: usize = SignatureInFlash::sealed_data_offset();
// These are vendored in so we don't have a circular dependency on ed25519 crate
pub const SIGNATURE_LENGTH: usize = 64; // length of an ed25519 signature.
pub const PUBLIC_KEY_LENGTH: usize = 32; // length of an ed25519 public key.
pub const AAD_LENGTH: usize = 60; // at least 37 bytes, rounded up to the nearest 32-byte boundary
/// These are notional and subject to change
#[repr(u32)]
#[derive(PartialEq, Eq, Clone, Copy)]
@ -40,7 +44,8 @@ pub enum FunctionCode {
}
pub const BAOCHIP_SIG_VERSION: u32 = 0x1_00;
pub const PADDING_LEN: usize = SIGBLOCK_LEN - size_of::<SealedFields>() - SIGNATURE_LENGTH - size_of::<u32>();
pub const PADDING_LEN: usize = SIGBLOCK_LEN - size_of::<SignatureInFlash>();
pub const MAGIC_NUMBER: [u32; 2] = [u32::from_be_bytes(*b"yumy"), u32::from_be_bytes(*b"Bao3")];
/// Representation of the signature block in memory.
#[repr(C)]
#[derive(Copy, Clone)]
@ -50,10 +55,17 @@ pub struct SignatureInFlash {
pub _jal_instruction: u32,
/// The actual signature.
pub signature: [u8; SIGNATURE_LENGTH],
/// `aad_len` also specifies the signing protocol. If it is `0`, then a pure `ed25519ph`
/// signature is assumed. If it is greater than `0`, then it's assumed to be a
/// FIDO2/WebAuthn signature format using ed25519, where the signature is computed as:
/// `signature = Ed25519.sign(authenticatorData || SHA-256(clientData))`
/// `authenticatorData` is a field that is at least 37 bytes in size. The size is influenced
/// by the type of signing and operation, but for our implementation I think it stays
/// fixed at 37 bytes.
pub aad_len: u32,
pub aad: [u8; AAD_LENGTH],
/// All data from this point onward are included in the signature computation.
pub sealed_data: SealedFields,
/// Padding to target length
pub padding: [u8; PADDING_LEN],
}
unsafe impl Zeroable for SignatureInFlash {}
unsafe impl Pod for SignatureInFlash {}
@ -68,17 +80,44 @@ impl Default for SignatureInFlash {
Self {
_jal_instruction: 0,
signature: [0u8; SIGNATURE_LENGTH],
aad_len: 0,
aad: [0u8; AAD_LENGTH],
sealed_data: SealedFields::default(),
padding: [0u8; PADDING_LEN],
}
}
}
impl SignatureInFlash {
// The offset is after the jal instruction + signature.
pub const fn sealed_data_offset() -> usize {
size_of::<u32>() + SIGNATURE_LENGTH + size_of::<u32>() + AAD_LENGTH
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Pubkey {
pub pk: [u8; PUBLIC_KEY_LENGTH],
pub tag: [u8; 4],
}
unsafe impl Zeroable for Pubkey {}
unsafe impl Pod for Pubkey {}
impl Default for Pubkey {
fn default() -> Self { Self { pk: [0u8; PUBLIC_KEY_LENGTH], tag: [0u8; 4] } }
}
impl Pubkey {
pub fn populate_from(&mut self, record: &Pubkey) {
self.pk.copy_from_slice(&record.pk);
self.tag.copy_from_slice(&record.tag);
}
}
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
pub struct SealedFields {
/// Version number of this signature record
pub version: u32,
/// Magic number, to quickly differentiate uninitialized memory from a valid signature record
pub magic: [u32; 2],
/// Length of the signed code.
pub signed_len: u32,
/// Function code of the signed block. Used to provide metadata about what is inside the signed
@ -106,7 +145,7 @@ pub struct SealedFields {
/// is erased and boot is allowed to proceed.
///
/// If no valid keys are found, the device is effectively bricked and goes into a "die" state.
pub pubkeys: [[u8; PUBLIC_KEY_LENGTH]; 4],
pub pubkeys: [Pubkey; 4],
}
impl AsRef<[u8]> for SealedFields {
@ -115,13 +154,14 @@ impl AsRef<[u8]> for SealedFields {
impl Default for SealedFields {
fn default() -> Self {
Self {
version: 0,
version: BAOCHIP_SIG_VERSION,
magic: MAGIC_NUMBER,
signed_len: 0,
function_code: 0,
reserved: 0,
min_semver: [0u8; 16],
semver: [0u8; 16],
pubkeys: [[0u8; PUBLIC_KEY_LENGTH]; 4],
pubkeys: [Pubkey::default(); 4],
}
}
}

View file

@ -9,9 +9,11 @@ pub const ACRAM_DATASLOT_START: usize = 0x603D_C000;
pub const ACRAM_KEYSLOT_START: usize = 0x603D_E000;
// pub const ACRAM_GKEYSLOT_START: usize = 0x603D_E400; // This is mentioned in the docs but I don't see it in
// the code?
pub const ONEWAY_START: usize = 0x603D_A000;
pub const ONEWAY2_START: usize = 0x603D_B000;
pub const ONEWAY_LEN: usize = 2048; // in u32-sized elements
pub const ONEWAY_START: usize = 0x603D_A000; // page with 128 counters
pub const ONEWAY2_START: usize = 0x603D_B000; // page with another 128 counters
const ONEWAY_LEN: usize = 256 / 8; // in bytes
const COUNTER_STRIDE_U32: usize = ONEWAY_LEN / size_of::<u32>();
pub const MAX_ONEWAY_COUNTERS: usize = 8192 / ONEWAY_LEN;
pub const CODESEL_END: usize = 0x603D_A000;
#[bitfield(u32)]
@ -94,7 +96,6 @@ pub struct OneWayCounter {
#[cfg(feature = "std")]
mapping: MemoryRange,
}
const COUNTER_STRIDE_U32: usize = 8;
impl OneWayCounter {
pub fn new() -> Self {
#[cfg(not(feature = "std"))]
@ -103,9 +104,9 @@ impl OneWayCounter {
#[cfg(feature = "std")]
let ret = OneWayCounter {
mapping: xous::syscall::map_memory(
xous::MemoryAddress::new(ONEWAY2_START),
xous::MemoryAddress::new(ONEWAY_START),
None,
ONEWAY_LEN * size_of::<u32>(),
ONEWAY_LEN * MAX_ONEWAY_COUNTERS,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map oneway range"),
@ -119,7 +120,7 @@ impl OneWayCounter {
let base = ONEWAY_START as *const u32;
#[cfg(feature = "std")]
let base = self.mapping.as_ptr() as *const u32;
if offset < ONEWAY_LEN {
if offset < MAX_ONEWAY_COUNTERS {
// safety: only safe because the pointer is length-checked
// we use this form to access the array because we need to read_volatile()
Ok(unsafe { base.add(offset * COUNTER_STRIDE_U32).read_volatile() })
@ -139,7 +140,7 @@ impl OneWayCounter {
#[cfg(feature = "std")]
let base = self.mapping.as_mut_ptr() as *mut u32;
if offset < ONEWAY_LEN {
if offset < MAX_ONEWAY_COUNTERS {
let starting_value = self.get(offset).unwrap(); // offset is already checked
// this will cause the increment in hardware
unsafe { base.add(offset * COUNTER_STRIDE_U32).write_volatile(0) }
@ -165,7 +166,7 @@ impl OneWayCounter {
let base = self.mapping.as_mut_ptr() as *mut u32;
let offset = T::OFFSET;
if offset < ONEWAY_LEN {
if offset < MAX_ONEWAY_COUNTERS {
let starting_value = self.get(offset).unwrap(); // offset is already checked
// this will cause the increment in hardware
unsafe { base.add(offset * COUNTER_STRIDE_U32).write_volatile(0) }

View file

@ -1,9 +1,10 @@
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use bao1x_api::signatures::*;
use digest::Digest;
use sha2_bao1x::Sha512;
use sha2_bao1x::{Sha256, Sha512};
use xous::arch::PAGE_SIZE;
use crate::acram::OneWayCounter;
@ -33,7 +34,7 @@ use crate::udma::Spim;
/// the wrong phase of the boot sequence. Passed as a list of u32-values that are allowed.
///
/// `auto_jump` is a flag which, when `true`, causes the code to diverge into the signed block.
/// If `false` the function returns the key index of the first passing public key, or an error
/// If `false` the function returns the `(key_index, tag)` of the first passing public key, or an error
/// if none were found.
pub fn validate_image(
img_offset: *const u32,
@ -42,7 +43,7 @@ pub fn validate_image(
function_codes: &[u32],
auto_jump: bool,
mut spim: Option<&mut Spim>,
) -> Result<usize, String> {
) -> Result<(usize, [u8; 4]), String> {
// Copy the signature into a structure so we can unpack it.
let mut sig = SignatureInFlash::default();
if let Some(ref mut spim) = spim {
@ -56,9 +57,15 @@ pub fn validate_image(
let pubkey_ptr = pubkeys_offset as *const SignatureInFlash;
let pk_src: &SignatureInFlash = unsafe { pubkey_ptr.as_ref().unwrap() };
if pk_src.sealed_data.magic != MAGIC_NUMBER {
return Err(String::from("Invalid magic number in verifying key record"));
}
let signed_len = sig.sealed_data.signed_len;
if sig.sealed_data.magic != MAGIC_NUMBER {
return Err(String::from("Invalid magic number on incoming record to be verified"));
}
if sig.sealed_data.version != BAOCHIP_SIG_VERSION {
crate::println!(
"Version {:x} sig found, should be {:x}",
@ -77,11 +84,12 @@ pub fn validate_image(
let developer = sig.sealed_data.function_code == FunctionCode::Developer as u32;
// crate::println!("Signature: {:x?}", sig.signature);
let one_way_counters = OneWayCounter::new();
let mut secure = false;
let mut passing_key: Option<usize> = None;
for (i, key) in pk_src.sealed_data.pubkeys.iter().enumerate() {
if key.iter().all(|&x| x == 0) {
if key.tag == [0u8; 4] {
continue;
}
let revocation_value = one_way_counters.get(revocation_offset + i).expect("internal error");
@ -90,9 +98,10 @@ pub fn validate_image(
continue;
}
let verifying_key =
ed25519_dalek::VerifyingKey::from_bytes(key).or(Err(String::from("invalid public key")))?;
ed25519_dalek::VerifyingKey::from_bytes(&key.pk).or(Err(String::from("invalid public key")))?;
let ed25519_signature = ed25519_dalek::Signature::from(sig.signature);
let mut h: Sha512 = Sha512::new();
if let Some(ref mut spim) = spim {
// need to read the data out page by page and hash it.
@ -113,24 +122,61 @@ pub fn validate_image(
signed_len as usize,
)
};
// crate::println!("Verifying image {:x?} with {:x?}", &image[..16], &key);
h.update(&image);
}
// debugging note: h.clone() does *not* work. You have to print the hash by modifying
// the function inside the ed25519 crate.
match verifying_key.verify_prehashed(h, None, &ed25519_signature) {
Ok(_) => {
passing_key = Some(i);
if i != sig.sealed_data.pubkeys.len() - 1 {
secure = true;
break;
} else if i == sig.sealed_data.pubkeys.len() - 1 {
// this is the developer key slot
secure = false;
break;
if sig.aad_len == 0 {
// crate::println!("ed25519ph verifying with {:x?}", &key.pk);
// debugging note: h.clone() does *not* work. You have to print the hash by modifying
// the function inside the ed25519 crate.
match verifying_key.verify_prehashed(h, None, &ed25519_signature) {
Ok(_) => {
crate::println!("ed25519ph verification passed");
passing_key = Some(i);
if i != sig.sealed_data.pubkeys.len() - 1 {
secure = true;
break;
} else if i == sig.sealed_data.pubkeys.len() - 1 {
// this is the developer key slot
secure = false;
break;
}
}
_ => {
crate::println!("ed25519ph verification failed");
}
}
} else {
let sha512_hashed_image = h.finalize();
// create a *new* hasher because a token can only sign a hash, not the full image.
let mut h: Sha256 = Sha256::new();
// hash dat hash!
// crate::println!("verifying base hash {:x?}", &sha512_hashed_image.as_slice());
h.update(&sha512_hashed_image.as_slice());
let hashed_hash = h.finalize();
// crate::println!("hashed hash: {:x?}", hashed_hash.as_slice());
let mut msg: Vec<u8> = Vec::new();
msg.extend_from_slice(&sig.aad[..sig.aad_len as usize]);
msg.extend_from_slice(hashed_hash.as_slice());
// crate::println!("assembled msg({}): {:x?}", msg.len(), msg);
match verifying_key.verify_strict(&msg, &ed25519_signature) {
Ok(_) => {
crate::println!("FIDO2 ed25519 verification passed");
passing_key = Some(i);
if i != sig.sealed_data.pubkeys.len() - 1 {
secure = true;
break;
} else if i == sig.sealed_data.pubkeys.len() - 1 {
// this is the developer key slot
secure = false;
break;
}
}
_ => {
crate::println!("FIDO2 verification failed");
}
}
_ => {}
}
}
@ -141,7 +187,7 @@ pub fn validate_image(
if auto_jump {
jump_to(img_offset as usize);
}
Ok(valid_key)
Ok((valid_key, pk_src.sealed_data.pubkeys[valid_key].tag))
} else {
Err(String::from("No valid pubkeys found or signature invalid"))
}

View file

@ -266,7 +266,11 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32)
false,
None,
) {
Ok(k) => println!("*** Kernel signature check by key @ {} OK ***", k),
Ok((k, tag)) => println!(
"*** Kernel signature check by key @ {}({}) OK ***",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
),
Err(e) => {
println!("Kernel failed signature check. Dying: {:?}", e);
bao1x_hal::sigcheck::die_no_std();
@ -285,8 +289,12 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32)
false,
None,
) {
Ok(k) => {
println!("*** Detached app signature check by key @ {} OK ***", k);
Ok((k, tag)) => {
println!(
"*** Detached app signature check by key @ {}({}) OK ***",
k,
core::str::from_utf8(&tag).unwrap_or("invalid tag")
);
true
}
Err(_e) => {

28
signing/README.md Normal file
View file

@ -0,0 +1,28 @@
# Image Signing and Deployment
The scripts in this directory are used for image signing and deployment.
The primary method for securing images is by signing them with a Precursor or Baochip device. There is a `beta` key, which is kept within such a device, but the device is regularly accessible for testing purposes. There is also at least one `deployment` key, which is kept in a similar device, but the device is kept in a physically secured location and deploying it requires some ceremony and effort.
Here is the flow for generating and deploying signatures:
## Preparation
1. The "HSM" (as it may be -- really just a signing token) is a Precursor/Baochip device. The signature type is `ed25519`. The device is primed with a PIN like a normal FIDO device.
1. A residential SSH key is created on the device using `ssh-keygen -t ed25519-sk`
1. The "private key" resulting from this contains the credential ID, public key, relying party,
## Signing
2. The image to be signed is fed into `fido-signer`:
1. The signing token must be connected to the computer
2. The PIN must be provided by the signer
3. Depending on the host, this may need to run at an elevated privilege level (Windows in particular enforces that)
3. Assuming the prequisites are met, `fido-signer` patches a unified signed Baochip image to inject the `signature` and `auth_data` into the designated key slot. It also generates a `.uf2` file for convenience.
In the case that a `deployment` key is used, additional physical security measures are invoked, a list of which are not publicly documented because in physical security, obscurity and the element of surprise are valid and useful countermeasures.
## Other notes
The `credentials` directory is in the `.gitignore` and should not be checked in. If you see a `credentials` directory in the tree, there was an operational security problem.
That being said, `credentials` does *not* store the actual private key used for signing. The main thing the directory contains is the PIN to unlock the signing token, which is a secondary security precaution.

View file

@ -0,0 +1 @@
sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIICXmSnt0E5AEktSyumuVLJL3/cqe4oATEEGW9FAIHinAAAABHNzaDo= bunnie@bunnie-desktop

View file

@ -0,0 +1,12 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAASgAAABpzay1zc2
gtZWQyNTUxOUBvcGVuc3NoLmNvbQAAACCAl5kp7dBOQBJLUsrprlSyS9/3KnuKAExBBlvR
QCB4pwAAAARzc2g6AAABaBoLZaIaC2WiAAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY2
9tAAAAIICXmSnt0E5AEktSyumuVLJL3/cqe4oATEEGW9FAIHinAAAABHNzaDoBAAAA8QEG
YIv6BSgkDVszkhuxOE6+rvPkc3pestB+d4BbiMse1ur8ddQhyUH6jQniS0pM7JiF3XbA/a
FmDE1ucuTzumu6wGjIdTJ7T029q4c2gOdSWCiE8beA0fyw3s1TAH56a1uMYYHqdPG1c95y
mS0sB5ZfXIEIde0R80JDZosY65lCVoxXj3wD+r9uvcgZyUjZyWnvK7EmbNDRoNUuHDfjI2
oHVuVBDzF+YiixCIXIM6qulKiJe+RvtnvUyMJrASEWLLBGFa74LGpub6drnF8DSj3aFQTN
LgmdzB0D/7gr5Jf+lh96SthrfWzNcz+q/pRKhYsAAAAAAAAAFWJ1bm5pZUBidW5uaWUtZG
Vza3RvcAECAw==
-----END OPENSSH PRIVATE KEY-----

View file

@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""
Extract FIDO/U2F credential id (key_handle) from an OpenSSH sk private key.
Usage:
python3 extract_sk_credential.py /path/to/id_ed25519_sk
cat /path/to/id_ed25519_sk | python3 extract_sk_credential.py -
"""
import sys, argparse, base64, struct
from pathlib import Path
def read_u32(buf, off):
if off+4 > len(buf):
raise ValueError("unexpected end while reading u32")
return struct.unpack(">I", buf[off:off+4])[0], off+4
def read_string(buf, off):
l, off = read_u32(buf, off)
if off + l > len(buf):
raise ValueError("unexpected end while reading string")
return buf[off:off+l], off + l
def read_byte(buf, off):
if off >= len(buf):
raise ValueError("unexpected end while reading byte")
return buf[off], off+1
def extract_key_info(priv_blob):
# priv_blob layout: two checkints, then for each key:
# string keytype
# string pubkey_blob
# string privkey_blob
off = 0
_, off = read_u32(priv_blob, off)
_, off = read_u32(priv_blob, off)
key_type, off = read_string(priv_blob, off)
print(f"Key type: {key_type.decode('utf-8')}")
pubkey_blob, off = read_string(priv_blob, off)
relying_party, off = read_string(priv_blob, off)
print(f"Relying party: {relying_party.decode('utf-8')}")
flags, off = read_byte(priv_blob, off)
key_handle, off = read_string(priv_blob, off)
return (pubkey_blob, key_handle)
def load_openssh_private(data_bytes):
b = data_bytes.strip()
if b.startswith(b"-----BEGIN OPENSSH PRIVATE KEY-----"):
body = b.split(b"-----BEGIN OPENSSH PRIVATE KEY-----",1)[1]
body = body.split(b"-----END OPENSSH PRIVATE KEY-----",1)[0]
body = b"".join(body.splitlines())
raw = base64.b64decode(body)
else:
# try base64 decode; if invalid, assume already binary openssh blob
try:
raw = base64.b64decode(b, validate=True)
except Exception:
raw = data_bytes
return raw
def extract_from_file(path):
data = sys.stdin.buffer.read() if path == "-" else open(path, "rb").read()
raw = load_openssh_private(data)
magic = b"openssh-key-v1\0"
if not raw.startswith(magic):
raise ValueError("not an openssh-key-v1 private key (magic mismatch)")
off = len(magic)
# string ciphername, string kdfname, string kdfoptions, uint32 nkeys
_, off = read_string(raw, off)
_, off = read_string(raw, off)
_, off = read_string(raw, off)
nkeys, off = read_u32(raw, off)
for _ in range(nkeys):
_, off = read_string(raw, off) # public key blob(s)
priv_block, off = read_string(raw, off)
return extract_key_info(priv_block)
def main():
p = argparse.ArgumentParser(description="Extract FIDO/U2F key_handle (credential id) from an OpenSSH sk private key")
p.add_argument("infile", nargs="?", default="./testing_id_ed25519_sk", help="private key file (PEM or base64). Use '-' for stdin")
args, _ = p.parse_known_args()
infile = Path(args.infile)
try:
(pubkey_blob, key_handle) = extract_from_file(infile)
except Exception as e:
sys.stderr.write("ERROR: " + str(e) + "\n")
sys.exit(2)
name = infile.stem.upper()
pubkey_formatted = ', '.join(f"0x{byte:02x}" for byte in pubkey_blob)
print(f"pub const {name}_PUB: [u8; 32] = [{pubkey_formatted}];")
print(f"pubkey base64: {base64.b64encode(pubkey_blob)}")
key_handle_formatted = ', '.join(f"0x{byte:02x}" for byte in key_handle)
print(f"pub const {name}_CRED_ID: [u8; {len(key_handle)}] = [{key_handle_formatted}];")
print(f"cred id base64: {base64.b64encode(key_handle)}")
if __name__ == "__main__":
main()

1261
signing/fido-signer/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,24 @@
[package]
name = "auth-sign-test"
version = "0.1.0"
edition = "2021"
[dependencies]
hex = "0.4"
ctap-hid-fido2 = "3.5.5"
clap = { version = "4.5", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
base64 = "0.22.1"
bao1x-api = { path = "../../libs/bao1x-api" }
sha2 = "0.10.9"
digest = "0.10"
byteorder = "1.2"
# For Windows USB support
[target.'cfg(windows)'.dependencies]
windows = { version = "0.48", features = [
"Win32_Devices_HumanInterfaceDevice",
] }

View file

@ -0,0 +1,343 @@
use std::fs;
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
use std::mem;
use std::path::Path;
use std::path::PathBuf;
use bao1x_api::signatures::SignatureInFlash;
use base64::{Engine as _, engine::general_purpose};
use clap::{ArgGroup, Parser};
use ctap_hid_fido2::fidokey::get_assertion::get_assertion_params::Assertion;
use ctap_hid_fido2::{Cfg, FidoKeyHidFactory, fidokey::GetAssertionArgsBuilder};
use digest::Digest;
use serde::{Deserialize, Serialize};
use sha2::Sha512;
/// FIDO Signer - Sign messages or files using FIDO credentials
#[derive(Parser, Debug)]
#[command(
name = "fido-signer",
author = "bunnie",
about = "Sign messages and bao1x image files with a FIDO token"
)]
#[command(version, long_about = None)]
#[command(group(
ArgGroup::new("input")
.required(true)
.args(["message", "file"])
))]
struct Args {
/// Path to the credential file (JSON format)
#[arg(short = 'c', long, value_name = "FILE")]
credential_file: PathBuf,
/// Message to sign (base64 encoded)
#[arg(short = 'm', long, value_name = "BASE64_MESSAGE", conflicts_with = "file")]
message: Option<String>,
/// File to sign
#[arg(short = 'f', long, value_name = "FILE", conflicts_with = "message")]
file: Option<PathBuf>,
/// Function code e.g. partition - if provided, creates a uf2 file
#[arg(short = 'p', long = "function-code", value_name = "CODE")]
function_code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
struct Credentials {
credential_id: String, // Base64 encoded, will be decoded to Vec<u8>
pin: String, // UTF-8 string
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Ed25519 Signing with FIDO2 Token");
println!("================================\n");
// Parse command line arguments
let args = Args::parse();
// Load and parse the credential file
let credential_data = fs::read_to_string(&args.credential_file)
.map_err(|e| format!("Failed to read credential file: {}", e))?;
let credentials: Credentials = serde_json::from_str(&credential_data)
.map_err(|e| format!("Failed to parse credential JSON: {}", e))?;
// Decode the credential_id from base64
let credential_id: Vec<u8> = general_purpose::STANDARD
.decode(&credentials.credential_id)
.map_err(|e| format!("Failed to decode credential_id: {}", e))?;
// Get the PIN as a string (already UTF-8)
let pin: String = credentials.pin;
// Determine what to sign
let mut is_bao1x = false;
let mut offset = 0;
let data_to_sign: Vec<u8> = if let Some(message_b64) = args.message {
// Decode message from base64 - used for testing signing operations with small pieces of temporary
// data
general_purpose::STANDARD
.decode(&message_b64)
.map_err(|e| format!("Failed to decode message: {}", e))?
} else if let Some(ref file_path) = args.file {
// Read file contents.
let file = fs::read(&file_path)
.map_err(|e| format!("Failed to read file '{}': {}", file_path.display(), e))?;
if let Some(ref code) = args.function_code {
// swap is a special case, its signature header is shifted in the image due to the presence
// of the swap metadata header
if code == "swap" {
offset = bao1x_api::offsets::baosec::SWAP_HEADER_LEN - bao1x_api::signatures::SIGBLOCK_LEN;
}
}
// Check to see if this is a signed bao1x binary, by looking at the magic number.
let mut sig = SignatureInFlash::default();
sig.as_mut().copy_from_slice(&file[offset..offset + size_of::<SignatureInFlash>()]);
if sig.sealed_data.magic == bao1x_api::signatures::MAGIC_NUMBER {
is_bao1x = true;
let mut h: Sha512 = Sha512::new();
// hash the sealed region
h.update(&file[offset + SignatureInFlash::sealed_data_offset()..]);
// finalize it and send it on for signing
h.finalize().as_slice().to_vec()
} else {
file
}
} else {
// This shouldn't happen due to clap's ArgGroup, but handle it just in case
return Err("Either --message or --file must be provided".into());
};
println!("Credential file: {:?}", args.credential_file);
println!("Credential ID (decoded): {} bytes", credential_id.len());
println!("PIN: [REDACTED]"); // Don't print the actual PIN
println!("Data to sign: {} bytes", data_to_sign.len());
// Sign the hash
// println!("Signing {:x?}", data_to_sign);
// let mut h_debug = sha2::Sha256::new();
// h_debug.update(&data_to_sign);
// let h_debug_final = h_debug.finalize();
// println!("hashed hash: {:x?}", h_debug_final.as_slice());
let assertion = sign_ed25519_hash(&credential_id, &data_to_sign, &pin)?;
println!("\n* Signing successful!");
println!("Signature length: {} bytes", assertion.signature.len());
if assertion.signature.len() == 64 {
println!("* Valid Ed25519 signature");
// Ed25519 signature components
let (r, s) = assertion.signature.split_at(32);
println!(" R (hex): {}", hex::encode(r));
println!(" S (hex): {}", hex::encode(s));
println!(" auth_data (hex): {}", hex::encode(&assertion.auth_data));
println!(" signature (b64): {}", general_purpose::STANDARD.encode(&assertion.signature));
println!(" auth_data (b64): {}", general_purpose::STANDARD.encode(&assertion.auth_data));
}
if is_bao1x {
if let Some(ref file_path) = args.file {
println!("Patching image file with signature...");
patch_signature_in_file(&file_path, &assertion.signature, &assertion.auth_data, offset)?;
}
if let Some(function_code) = args.function_code {
if let Some(input) = args.file {
let output = input.with_extension("uf2");
println!("Building image file for partition {}, writing to {:?}...", function_code, output);
convert_to_uf2(&input, &output, Some(&function_code), None)?
}
}
}
Ok(())
}
// Using the ctap-hid crate (Pure Rust, no C dependencies)
// #[cfg(feature = "pure-rust")]
fn sign_ed25519_hash(
credential_id: &[u8],
hash: &[u8],
pin: &str,
) -> Result<Assertion, Box<dyn std::error::Error>> {
let cfg = Cfg::init();
let mut devices = ctap_hid_fido2::get_fidokey_devices();
if devices.is_empty() {
return Err("No FIDO2 devices found".into());
}
let device = devices.pop().unwrap();
let fidokey = FidoKeyHidFactory::create_by_params(&[device.param], &cfg).unwrap();
// println!("Using key {:?}", fidokey.get_info().unwrap());
let assertion = GetAssertionArgsBuilder::new("ssh:", hash).pin(pin).credential_id(credential_id).build();
match fidokey.get_assertion_with_args(&assertion) {
Ok(mut a) => {
println!("Key used {} times", a[0].sign_count);
Ok(a.pop().unwrap())
}
Err(e) => Err(e.try_into().unwrap()),
}
}
fn patch_signature_in_file(
file_path: &PathBuf,
signature: &Vec<u8>,
auth_data: &Vec<u8>,
offset: usize,
) -> Result<(), Box<dyn std::error::Error>> {
// Open file with read and write permissions
let mut file = OpenOptions::new().read(true).write(true).open(file_path)?;
let mut signature_struct = read_header_from_file(&mut file, offset)?;
signature_struct.signature.copy_from_slice(&signature);
if auth_data.len() > signature_struct.aad.len() {
println!(
"Auth data returned by key is {} bytes and exceeds the capacity {} of the signature record",
auth_data.len(),
signature_struct.aad.len()
);
return Err(String::from("Auth data exceeds capacity of the signature field").into());
}
signature_struct.aad[..auth_data.len()].copy_from_slice(&auth_data);
signature_struct.aad_len = auth_data.len() as u32;
write_header_to_file(&mut file, &signature_struct, offset)?;
Ok(())
}
fn read_header_from_file(file: &mut std::fs::File, offset: usize) -> Result<SignatureInFlash, Box<dyn std::error::Error>> {
// Ensure we're at the beginning of the file
file.seek(SeekFrom::Start(offset as u64))?;
// Create a buffer for the struct
let struct_size = mem::size_of::<SignatureInFlash>();
let mut buffer = vec![0u8; struct_size];
// Read exactly the size of the struct
file.read_exact(&mut buffer)?;
let mut signature_struct = SignatureInFlash::default();
assert!(
signature_struct.sealed_data.magic == bao1x_api::signatures::MAGIC_NUMBER,
"Magic number does not match in bao header file!"
);
signature_struct.as_mut().copy_from_slice(&buffer);
Ok(signature_struct)
}
fn write_header_to_file(
file: &mut std::fs::File,
signature: &SignatureInFlash,
offset: usize,
) -> Result<(), Box<dyn std::error::Error>> {
// Seek back to the beginning where the struct starts
file.seek(SeekFrom::Start(offset as u64))?;
// Write the bytes back to the file
file.write_all(signature.as_ref())?;
// Ensure the data is flushed to disk
file.flush()?;
Ok(())
}
// ----- code below is vendored in from tools/src/sign_image.rs. Maybe this should be a library,
// but let's see what the e2e integration looks like before we puzzle on how to librarify-this.
pub fn convert_to_uf2<S, T>(
input: &S,
output: &T,
function_code: Option<&str>,
offset: Option<usize>,
) -> Result<(), Box<dyn std::error::Error>>
where
S: AsRef<Path>,
T: AsRef<Path>,
{
let mut source = vec![];
let mut source_file = std::fs::File::open(input)?;
let mut dest_file = std::fs::File::create(output)?;
source_file.read_to_end(&mut source)?;
let app_start_addr = match function_code {
Some("boot0") => bao1x_api::BOOT0_START,
Some("boot1") => bao1x_api::BOOT1_START,
Some("loader") => bao1x_api::LOADER_START,
Some("baremetal") => bao1x_api::BAREMETAL_START,
Some("kernel") => bao1x_api::KERNEL_START,
Some("swap") => bao1x_api::SWAP_START_UF2,
Some("app") => bao1x_api::dabao::APP_RRAM_START,
_ => return Err(String::from("UF2 Image Requires a function code").into()),
};
match bin_to_uf2(
&source,
bao1x_api::BAOCHIP_1X_UF2_FAMILY,
app_start_addr as u32 + offset.unwrap_or(0) as u32,
) {
Ok(u2f_blob) => {
dest_file.write_all(&u2f_blob)?;
Ok(())
}
Err(e) => Err(e.into()),
}
}
use byteorder::{LittleEndian, WriteBytesExt};
const UF2_MAGIC_START0: u32 = 0x0A324655; // "UF2\n"
const UF2_MAGIC_START1: u32 = 0x9E5D5157; // Randomly selected
const UF2_MAGIC_END: u32 = 0x0AB16F30; // Ditto
// Vendored in from https://github.com/sajattack/uf2conv-rs/blob/master/lib/src/lib.rs
// The code is MIT-licensed, and authored by Paul Sajna
pub fn bin_to_uf2(bytes: &Vec<u8>, family_id: u32, app_start_addr: u32) -> Result<Vec<u8>, std::io::Error> {
let datapadding = [0u8; 512 - 256 - 32 - 4];
let nblocks: u32 = ((bytes.len() + 255) / 256) as u32;
let mut outp: Vec<u8> = Vec::new();
for blockno in 0..nblocks {
let ptr = 256 * blockno;
let chunk = match bytes.get(ptr as usize..ptr as usize + 256) {
Some(bytes) => bytes.to_vec(),
None => {
let mut chunk = bytes[ptr as usize..bytes.len()].to_vec();
while chunk.len() < 256 {
chunk.push(0);
}
chunk
}
};
let mut flags: u32 = 0;
if family_id != 0 {
flags |= 0x2000
}
// header
outp.write_u32::<LittleEndian>(UF2_MAGIC_START0)?;
outp.write_u32::<LittleEndian>(UF2_MAGIC_START1)?;
outp.write_u32::<LittleEndian>(flags)?;
outp.write_u32::<LittleEndian>(ptr + app_start_addr)?;
outp.write_u32::<LittleEndian>(256)?;
outp.write_u32::<LittleEndian>(blockno)?;
outp.write_u32::<LittleEndian>(nblocks)?;
outp.write_u32::<LittleEndian>(family_id)?;
// data
outp.write(&chunk)?;
outp.write(&datapadding)?;
// footer
outp.write_u32::<LittleEndian>(UF2_MAGIC_END)?;
}
Ok(outp)
}

Binary file not shown.

44
signing/test-verify.py Normal file
View file

@ -0,0 +1,44 @@
#!/usr/bin/env python3
import base64
import hashlib
import argparse
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.exceptions import InvalidSignature
def verify_signature(file_path: Path, pubkey_b64: str, sig_b64: str, authdata_b64: str):
pubkey = base64.b64decode(pubkey_b64)
signature = base64.b64decode(sig_b64)
authdata = base64.b64decode(authdata_b64)
client_data = file_path.read_bytes()
client_data_hash = hashlib.sha256(client_data).digest()
message = authdata + client_data_hash
public_key = ed25519.Ed25519PublicKey.from_public_bytes(pubkey)
try:
public_key.verify(signature, message)
print("Signature is valid.")
except InvalidSignature:
print("Signature is INVALID.")
def main():
parser = argparse.ArgumentParser(
description="Verify FIDO2 Ed25519-SK signature for a given clientDataJSON file."
)
parser.add_argument("file", type=Path, help="Path to clientDataJSON file")
parser.add_argument("pubkey_b64", help="Base64-encoded 32-byte Ed25519 public key")
parser.add_argument("sig_b64", help="Base64-encoded 64-byte signature")
parser.add_argument("authdata_b64", help="Base64-encoded 37-byte authenticator data")
args = parser.parse_args()
verify_signature(args.file, args.pubkey_b64, args.sig_b64, args.authdata_b64)
if __name__ == "__main__":
main()
# test data is 64 bytes of 0, signed with beta-key
#
# pubkey gJeZKe3QTkASS1LK6a5Uskvf9yp7igBMQQZb0UAgeKc=
# authdata 4wYQ6KFiEVlg/h7CI+ZSnJ9LboAgDcteXDIcivHisb8FAAACDw==
# signature uYiL6JV0h4LcZ95F3i4o09Lf29zI7PAM11LGfIolkOiJooeOUDm2tOIk2u/OuaiZgN62UZ4a6coNSwZkV9UxCg==

View file

@ -2,7 +2,7 @@ use std::io::{Read, Write};
use std::path::Path;
use bao1x_api::signatures::{
FunctionCode, PADDING_LEN, PUBLIC_KEY_LENGTH, SIGBLOCK_LEN, SealedFields, UNSIGNED_LEN,
FunctionCode, PADDING_LEN, SIGBLOCK_LEN, SealedFields, SignatureInFlash, UNSIGNED_LEN,
};
use ed25519_dalek::{DigestSigner, SigningKey};
use pkcs8::PrivateKeyInfo;
@ -196,9 +196,13 @@ pub fn sign_image(
// Now we can use the private key data.
let signing_key = SigningKey::from_bytes(&secbytes);
// derive a private key
let sk = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&private_key.contents)
.map_err(|e| format!("{}", e))?;
// This is handy code to remember - a quick way to get the public key from the private key. Just
// in case I need this in the future to sanity check some values.
/*
let sk = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&private_key.contents)
.map_err(|e| format!("{}", e))?;
let pubkey = sk.public_key();
*/
let function_code = match function_code {
Some("boot0") => FunctionCode::Boot0,
@ -209,24 +213,23 @@ pub fn sign_image(
Some("swap") => FunctionCode::Swap,
_ => FunctionCode::Developer,
};
let mut sealed_fields = SealedFields {
version: version as u32,
signed_len: (source.len() + SIGBLOCK_LEN - UNSIGNED_LEN) as u32,
function_code: function_code as u32,
reserved: 0,
min_semver: minver_bytes,
semver,
pubkeys: [
[0u8; PUBLIC_KEY_LENGTH],
[0u8; PUBLIC_KEY_LENGTH],
[0u8; PUBLIC_KEY_LENGTH],
[0u8; PUBLIC_KEY_LENGTH],
],
};
sealed_fields.pubkeys[3].copy_from_slice(sk.public_key().as_ref());
let mut header = SignatureInFlash::default();
header.sealed_data.version = version as u32;
header.sealed_data.signed_len = (source.len() + SIGBLOCK_LEN - UNSIGNED_LEN) as u32;
header.sealed_data.function_code = function_code as u32;
header.sealed_data.reserved = 0;
header.sealed_data.min_semver = minver_bytes;
header.sealed_data.semver = semver;
// whack in all the public keys, defined in the bao1x-api crate
for (dst, src) in
header.sealed_data.pubkeys.iter_mut().zip(bao1x_api::pubkeys::PUBKEY_HEADER.iter())
{
dst.populate_from(src);
}
let mut protected = Vec::new();
protected.extend_from_slice(sealed_fields.as_ref());
protected.extend_from_slice(header.sealed_data.as_ref());
protected.resize(protected.len() + PADDING_LEN, 0);
protected.extend_from_slice(&source);
@ -235,12 +238,14 @@ pub fn sign_image(
h.update(&protected);
let sig = signing_key.sign_digest(h.clone()).to_bytes();
header._jal_instruction = generate_jal_x0(SIGBLOCK_LEN as isize)?;
header.signature.copy_from_slice(&sig);
// no AAD on this type of signature
header.aad_len = 0;
let jal = generate_jal_x0(length as isize)?;
dest_file.write_all(&jal.to_le_bytes())?;
// Write the signature data
dest_file.write_all(&sig)?;
// Write the header
dest_file.write_all(&header.as_ref()[..UNSIGNED_LEN])?;
println!("dest_file wrote {}, {}", dest_file.len(), UNSIGNED_LEN);
if defile {
println!(
@ -305,6 +310,12 @@ where
let mut dest_file = std::fs::File::create(output)?;
source_file.read_to_end(&mut source)?;
// maintenance note: there is a mirror of this code in signing/fido-signer/src/main.rs
// if you're editing this, maybe consider also trying to librarify these routines?
// the key challenge is that fido-signer has to be out of workspace because it relies
// on cryptographic primitives that are pinned to versions that are not compatible
// with the baochip hardware, e.g. the FIDO2 libraries pin to an incompatible version
// with xous-core, so it's a little awkward spanning/sharing crates this way.
let app_start_addr = match function_code {
Some("boot0") => bao1x_api::BOOT0_START,
Some("boot1") => bao1x_api::BOOT1_START,

View file

@ -10,16 +10,9 @@ use chrono::Local;
pub(crate) fn generate_version(add_timestamp: bool) {
let output = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(["/C", "git describe --tags --long"])
.output()
.expect("failed to execute process")
Command::new("cmd").args(["/C", "git describe --long"]).output().expect("failed to execute process")
} else {
Command::new("sh")
.arg("-c")
.arg("git describe --tags --long")
.output()
.expect("failed to execute process")
Command::new("sh").arg("-c").arg("git describe --long").output().expect("failed to execute process")
};
let gitver = output.stdout;
let semver = String::from_utf8_lossy(&gitver);