diff --git a/.gitignore b/.gitignore index 5a94f4598..e92715691 100644 --- a/.gitignore +++ b/.gitignore @@ -84,3 +84,8 @@ share/python-wheels/ *.egg *.pyc MANIFEST + +# Deployment credentials +signing/credentials +# Signer target directory +signing/fido-signer/target \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 7ecf0034c..d0d28fddb 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -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/**" diff --git a/Cargo.lock b/Cargo.lock index 4ce3a8490..dafb3bd6a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index a4ed9d307..c91b3bd8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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] diff --git a/README-baochip.md b/README-baochip.md index 1da01a648..0f1688647 100644 --- a/README-baochip.md +++ b/README-baochip.md @@ -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 diff --git a/README-precursor.md b/README-precursor.md new file mode 100644 index 000000000..e69de29bb diff --git a/README.md b/README.md index fc534e510..f6aa5e4a4 100644 --- a/README.md +++ b/README.md @@ -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-.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-.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 diff --git a/bao1x-boot/boot1/src/repl.rs b/bao1x-boot/boot1/src/repl.rs index 4e06f9864..de6f0ed86 100644 --- a/bao1x-boot/boot1/src/repl.rs +++ b/bao1x-boot/boot1/src/repl.rs @@ -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 = 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::() + ); + crate::println!( + "Boot partition is: {:?}", + owc.get_decoded::() + ); + 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!(""); } } diff --git a/bao1x-boot/boot1/src/secboot.rs b/bao1x-boot/boot1/src/secboot.rs index b3cc66239..f41fc7246 100644 --- a/bao1x-boot/boot1/src/secboot.rs +++ b/bao1x-boot/boot1/src/secboot.rs @@ -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!"); diff --git a/baosign.ps1 b/baosign.ps1 new file mode 100644 index 000000000..ec0e19d3f --- /dev/null +++ b/baosign.ps1 @@ -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 +} \ No newline at end of file diff --git a/libs/bao1x-api/Cargo.toml b/libs/bao1x-api/Cargo.toml index 5bf3bc498..39c5dc95f 100644 --- a/libs/bao1x-api/Cargo.toml +++ b/libs/bao1x-api/Cargo.toml @@ -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] diff --git a/libs/bao1x-api/src/lib.rs b/libs/bao1x-api/src/lib.rs index 66cc5eb4e..462bed6b7 100644 --- a/libs/bao1x-api/src/lib.rs +++ b/libs/bao1x-api/src/lib.rs @@ -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 diff --git a/libs/bao1x-api/src/offsets/common.rs b/libs/bao1x-api/src/offsets/common.rs index 78111976d..5e692a325 100644 --- a/libs/bao1x-api/src/offsets/common.rs +++ b/libs/bao1x-api/src/offsets/common.rs @@ -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 diff --git a/libs/bao1x-api/src/pubkeys/bao1.rs b/libs/bao1x-api/src/pubkeys/bao1.rs new file mode 100644 index 000000000..5ebb91863 --- /dev/null +++ b/libs/bao1x-api/src/pubkeys/bao1.rs @@ -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], +}; diff --git a/libs/bao1x-api/src/pubkeys/bao2.rs b/libs/bao1x-api/src/pubkeys/bao2.rs new file mode 100644 index 000000000..06e4ad09b --- /dev/null +++ b/libs/bao1x-api/src/pubkeys/bao2.rs @@ -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], +}; diff --git a/libs/bao1x-api/src/pubkeys/beta.rs b/libs/bao1x-api/src/pubkeys/beta.rs new file mode 100644 index 000000000..128f9f7a0 --- /dev/null +++ b/libs/bao1x-api/src/pubkeys/beta.rs @@ -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] }; diff --git a/libs/bao1x-api/src/pubkeys/developer.rs b/libs/bao1x-api/src/pubkeys/developer.rs new file mode 100644 index 000000000..32be77267 --- /dev/null +++ b/libs/bao1x-api/src/pubkeys/developer.rs @@ -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] }; diff --git a/libs/bao1x-api/src/pubkeys/mod.rs b/libs/bao1x-api/src/pubkeys/mod.rs new file mode 100644 index 000000000..7eb9f9540 --- /dev/null +++ b/libs/bao1x-api/src/pubkeys/mod.rs @@ -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(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]; diff --git a/libs/bao1x-api/src/signatures.rs b/libs/bao1x-api/src/signatures.rs index 07ebe052d..adcf9869c 100644 --- a/libs/bao1x-api/src/signatures.rs +++ b/libs/bao1x-api/src/signatures.rs @@ -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::() + 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::() - SIGNATURE_LENGTH - size_of::(); +pub const PADDING_LEN: usize = SIGBLOCK_LEN - size_of::(); +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::() + SIGNATURE_LENGTH + size_of::() + 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], } } } diff --git a/libs/bao1x-hal/src/acram.rs b/libs/bao1x-hal/src/acram.rs index 8d88c5313..bff38691f 100644 --- a/libs/bao1x-hal/src/acram.rs +++ b/libs/bao1x-hal/src/acram.rs @@ -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::(); +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::(), + 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) } diff --git a/libs/bao1x-hal/src/sigcheck.rs b/libs/bao1x-hal/src/sigcheck.rs index 0bf3fc9ba..5dd3e8cdf 100644 --- a/libs/bao1x-hal/src/sigcheck.rs +++ b/libs/bao1x-hal/src/sigcheck.rs @@ -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 { +) -> 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 = 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 = 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")) } diff --git a/loader/src/main.rs b/loader/src/main.rs index f193db757..93cece1c0 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -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) => { diff --git a/signing/README.md b/signing/README.md new file mode 100644 index 000000000..8c88ec9f0 --- /dev/null +++ b/signing/README.md @@ -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. + diff --git a/signing/beta_ed25519_sk.pub b/signing/beta_ed25519_sk.pub new file mode 100644 index 000000000..36481d77e --- /dev/null +++ b/signing/beta_ed25519_sk.pub @@ -0,0 +1 @@ +sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIICXmSnt0E5AEktSyumuVLJL3/cqe4oATEEGW9FAIHinAAAABHNzaDo= bunnie@bunnie-desktop diff --git a/signing/beta_id_ed25519_sk b/signing/beta_id_ed25519_sk new file mode 100644 index 000000000..42a97b405 --- /dev/null +++ b/signing/beta_id_ed25519_sk @@ -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----- diff --git a/signing/extract_sk_credential.py b/signing/extract_sk_credential.py new file mode 100644 index 000000000..5b1d88b78 --- /dev/null +++ b/signing/extract_sk_credential.py @@ -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() diff --git a/signing/fido-signer/Cargo.lock b/signing/fido-signer/Cargo.lock new file mode 100644 index 000000000..42620a8c8 --- /dev/null +++ b/signing/fido-signer/Cargo.lock @@ -0,0 +1,1261 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "anstream" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2" +dependencies = [ + "windows-sys 0.60.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.60.2", +] + +[[package]] +name = "anyhow" +version = "1.0.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" + +[[package]] +name = "arbitrary-int" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "825297538d77367557b912770ca3083f778a196054b3ee63b22673c4a3cae0a5" + +[[package]] +name = "asn1-rs" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56624a96882bb8c26d61312ae18cb45868e5a9992ea73c58e45c3101e56a1e60" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "auth-sign-test" +version = "0.1.0" +dependencies = [ + "bao1x-api", + "base64", + "byteorder", + "clap", + "ctap-hid-fido2", + "digest", + "hex", + "serde", + "serde_json", + "sha2", + "windows", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "bao1x-api" +version = "0.1.0" +dependencies = [ + "bitbybit", + "bytemuck", + "num-derive", + "num-traits", + "xous", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitbybit" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec187a89ab07e209270175faf9e07ceb2755d984954e58a2296e325ddece2762" +dependencies = [ + "arbitrary-int", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bytemuck" +version = "1.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + +[[package]] +name = "cc" +version = "1.2.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d05d92f4b1fd76aad469d46cdd858ca761576082cd37df81416691e50199fb" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" + +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clap" +version = "4.5.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2ba64afa3c0a6df7fa517765e31314e983f51dda798ffba27b988194fb65dc9" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfd7eae0b0f1a6e63d4b13c9c478de77c2eb546fba158ad50b4203dc24b9f9c" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" + +[[package]] +name = "colorchoice" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "ctap-hid-fido2" +version = "3.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b1d1ba802b7e50be2c6e007fe01d25f4a00060fee1920ce714f93a5285890f4" +dependencies = [ + "aes", + "anyhow", + "base64", + "byteorder", + "cbc", + "ciborium", + "hex", + "hidapi", + "num", + "pad", + "rand", + "ring", + "strum", + "strum_macros", + "x509-parser", +] + +[[package]] +name = "data-encoding" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a41953f86f8a05768a6cda24def994fd2f424b04ec5c719cf89989779f199071" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0399f9d26e5191ce32c498bebd31e7a3ceabc2745f0ac54af3f335126c3f24b3" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasi 0.14.7+wasi-0.2.4", +] + +[[package]] +name = "half" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9" +dependencies = [ + "cfg-if", + "crunchy", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hidapi" +version = "2.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03b876ecf37e86b359573c16c8366bc3eba52b689884a0fc42ba3f67203d2a8b" +dependencies = [ + "cc", + "cfg-if", + "libc", + "pkg-config", + "windows-sys 0.48.0", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.176" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174" + +[[package]] +name = "memchr" +version = "2.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "once_cell_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad" + +[[package]] +name = "pad" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2ad9b889f1b12e0b9ee24db044b5129150d5eada288edc800f789928dc8c0e3" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +dependencies = [ + "getrandom 0.3.3", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.16", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", + "serde_core", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "syn" +version = "2.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "time" +version = "0.3.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" + +[[package]] +name = "time-macros" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "unicode-ident" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasi" +version = "0.14.7+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" +dependencies = [ + "wasip2", +] + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "windows" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-link" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65" + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.4", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d42b7b7f66d2a06854650af09cfdf8713e427a439c97ad65a6375318033ac4b" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "x509-parser" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4569f339c0c402346d4a75a9e39cf8dad310e287eef1ff56d4c68e5067f53460" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "xous" +version = "0.9.67" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb2954670da82bb4be335f2f576d48d33475145d9d0c83c725f395cf3284a12" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "zerocopy" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/signing/fido-signer/Cargo.toml b/signing/fido-signer/Cargo.toml new file mode 100644 index 000000000..556cf2073 --- /dev/null +++ b/signing/fido-signer/Cargo.toml @@ -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", +] } diff --git a/signing/fido-signer/src/main.rs b/signing/fido-signer/src/main.rs new file mode 100644 index 000000000..686755a9f --- /dev/null +++ b/signing/fido-signer/src/main.rs @@ -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, + + /// File to sign + #[arg(short = 'f', long, value_name = "FILE", conflicts_with = "message")] + file: Option, + + /// Function code e.g. partition - if provided, creates a uf2 file + #[arg(short = 'p', long = "function-code", value_name = "CODE")] + function_code: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +struct Credentials { + credential_id: String, // Base64 encoded, will be decoded to Vec + pin: String, // UTF-8 string +} + +fn main() -> Result<(), Box> { + 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 = 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 = 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::()]); + 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> { + 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, + auth_data: &Vec, + offset: usize, +) -> Result<(), Box> { + // 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> { + // 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::(); + 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> { + // 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( + input: &S, + output: &T, + function_code: Option<&str>, + offset: Option, +) -> Result<(), Box> +where + S: AsRef, + T: AsRef, +{ + 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, family_id: u32, app_start_addr: u32) -> Result, std::io::Error> { + let datapadding = [0u8; 512 - 256 - 32 - 4]; + let nblocks: u32 = ((bytes.len() + 255) / 256) as u32; + let mut outp: Vec = 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::(UF2_MAGIC_START0)?; + outp.write_u32::(UF2_MAGIC_START1)?; + outp.write_u32::(flags)?; + outp.write_u32::(ptr + app_start_addr)?; + outp.write_u32::(256)?; + outp.write_u32::(blockno)?; + outp.write_u32::(nblocks)?; + outp.write_u32::(family_id)?; + + // data + outp.write(&chunk)?; + outp.write(&datapadding)?; + + // footer + outp.write_u32::(UF2_MAGIC_END)?; + } + Ok(outp) +} diff --git a/signing/fido-signer/test.bin b/signing/fido-signer/test.bin new file mode 100644 index 000000000..9017fd98b Binary files /dev/null and b/signing/fido-signer/test.bin differ diff --git a/signing/test-verify.py b/signing/test-verify.py new file mode 100644 index 000000000..fd3d37de3 --- /dev/null +++ b/signing/test-verify.py @@ -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== \ No newline at end of file diff --git a/tools/src/sign_image.rs b/tools/src/sign_image.rs index 098ea1ab5..5a4b53bd3 100644 --- a/tools/src/sign_image.rs +++ b/tools/src/sign_image.rs @@ -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, diff --git a/xtask/src/versioning.rs b/xtask/src/versioning.rs index ed0831d98..043e96a74 100644 --- a/xtask/src/versioning.rs +++ b/xtask/src/versioning.rs @@ -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);