From e41195e3495cb27b447f0aec897c8928f29ced9d Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 30 Jan 2026 19:30:28 +0800 Subject: [PATCH 1/6] attempt to resolve version from URL automatically this might be a bit too heavy-weight for a lightweight tool but let's give it a try --- tools/Cargo.toml | 5 ++ tools/src/bin/xous-app-uf2.rs | 7 +- tools/src/git_remote_version.rs | 146 ++++++++++++++++++++++++++++++++ tools/src/lib.rs | 1 + 4 files changed, 158 insertions(+), 1 deletion(-) create mode 100644 tools/src/git_remote_version.rs diff --git a/tools/Cargo.toml b/tools/Cargo.toml index 802631404..1a5ec3412 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -39,6 +39,11 @@ serde_json = "1.0" # bao1x-api = { path = "../libs/bao1x-api" } bao1x-api = "0.1.0" # use crates.io to refer to this +# for remote resolution of github version in out-of-tree builds +reqwest = { version = "0.11", features = ["blocking", "json"] } +anyhow = "1.0" +toml = "0.8" + [[bin]] name = "xous-copy-object" diff --git a/tools/src/bin/xous-app-uf2.rs b/tools/src/bin/xous-app-uf2.rs index 59e8ca40c..ab3605eac 100644 --- a/tools/src/bin/xous-app-uf2.rs +++ b/tools/src/bin/xous-app-uf2.rs @@ -5,8 +5,10 @@ extern crate crc; use std::fs::File; use std::io::{Cursor, Write}; +use std::str::FromStr; use clap::{App, Arg}; +use xous_semver::SemVer; use xous_tools::elf::read_minielf; use xous_tools::sign_image::bin_to_uf2; use xous_tools::swap_writer::SwapWriter; @@ -107,12 +109,15 @@ fn main() -> Result<(), Box> { let mut source = Cursor::new(Vec::new()); args.write(&mut source).expect("Couldn't write out ELF files"); + let version = xous_tools::git_remote_version::get_xous_version().unwrap_or("v0.0.0".to_string()); + let semver: [u8; 16] = SemVer::from_str(&version)?.into(); + let result = xous_tools::sign_image::sign_image( &source.get_ref(), &private_key, false, &None, - None, + Some(semver), true, bao1x_api::signatures::SIGBLOCK_LEN, xous_tools::sign_image::Version::Bao1xV1, diff --git a/tools/src/git_remote_version.rs b/tools/src/git_remote_version.rs new file mode 100644 index 000000000..d85a566e8 --- /dev/null +++ b/tools/src/git_remote_version.rs @@ -0,0 +1,146 @@ +use std::collections::HashMap; +use std::fs; + +use anyhow::{Context, Result}; +use serde::Deserialize; + +#[derive(Debug, Deserialize)] +struct CargoToml { + dependencies: Option>, +} + +#[derive(Debug, Deserialize, Clone)] +#[serde(untagged)] +enum Dependency { + Simple(String), + Detailed(DetailedDependency), +} + +#[derive(Debug, Deserialize, Clone)] +struct DetailedDependency { + git: Option, + rev: Option, +} + +#[derive(Debug, Deserialize)] +struct GitHubTag { + name: String, +} + +fn find_xous_core_revision(cargo_toml_path: &str) -> Result> { + // Read and parse Cargo.toml + let contents = fs::read_to_string(cargo_toml_path).context("Failed to read Cargo.toml")?; + + let cargo: CargoToml = toml::from_str(&contents).context("Failed to parse Cargo.toml")?; + + let Some(deps) = cargo.dependencies else { + return Ok(None); + }; + + let xous_core_url = "https://github.com/betrusted-io/xous-core"; + let mut found_revisions = Vec::new(); + + // Search through dependencies for xous-core references + for (name, dep) in deps.iter() { + if let Dependency::Detailed(detailed) = dep { + if let (Some(git), Some(rev)) = (&detailed.git, &detailed.rev) { + if git == xous_core_url || git == &format!("{}.git", xous_core_url) { + found_revisions.push((name.clone(), rev.clone())); + } + } + } else if let Dependency::Simple(simple) = dep { + unimplemented!("Can't handle dep: {}", simple); + } + } + + if found_revisions.is_empty() { + return Ok(None); + } + + if found_revisions.len() > 1 { + eprintln!("Warning: Found multiple xous-core revisions:"); + for (name, rev) in &found_revisions { + eprintln!(" {} -> {}", name, rev); + } + eprintln!("Using the first one: {}", found_revisions[0].1); + } + + Ok(Some(found_revisions[0].1.clone())) +} + +fn get_latest_tag_from_github(repo: &str) -> Result { + let url = format!("https://api.github.com/repos/{}/tags", repo); + + let client = reqwest::blocking::Client::builder() + .user_agent("xous-app-uf2-tool") // GitHub requires a user agent + .build()?; + + let mut request = client.get(&url); + + // Optional: use token if available (no token required by default) + let using_token = if let Ok(token) = std::env::var("GITHUB_TOKEN") { + request = request.header("Authorization", format!("token {}", token)); + true + } else { + false + }; + + let response = request.send().context("Failed to fetch tags from GitHub")?; + + // Check for rate limit errors + if response.status() == reqwest::StatusCode::FORBIDDEN { + // Check if this is a rate limit error + if let Some(remaining) = response.headers().get("x-ratelimit-remaining") { + if remaining.to_str().unwrap_or("") == "0" { + if using_token { + anyhow::bail!( + "GitHub API rate limit exceeded (5000 requests/hour with token).\n\ + Please wait before trying again." + ); + } else { + anyhow::bail!( + "GitHub API rate limit exceeded (60 requests/hour per IP without authentication).\n\ + \n\ + To increase your rate limit to 5000 requests/hour, set the GITHUB_TOKEN environment variable:\n\ + \n\ + 1. Create a GitHub Personal Access Token at:\n\ + https://github.com/settings/tokens\n\ + 2. No special permissions needed - you can leave all scopes unchecked\n\ + 3. Set the token:\n\ + Linux/Mac: export GITHUB_TOKEN=your_token_here\n\ + Windows: set GITHUB_TOKEN=your_token_here\n\ + \n\ + For more info: https://docs.github.com/en/rest/overview/rate-limits-for-the-rest-api" + ); + } + } + } + } + + if !response.status().is_success() { + anyhow::bail!("GitHub API request failed: {}", response.status()); + } + + let tags: Vec = response.json().context("Failed to parse GitHub API response")?; + + tags.first().map(|tag| tag.name.clone()).ok_or_else(|| anyhow::anyhow!("No tags found in repository")) +} + +pub fn get_xous_version() -> Result { + // Assume we're running in the root directory + let cargo_toml_path = "Cargo.toml"; + + println!("Parsing {} for xous-core dependencies...", cargo_toml_path); + + let rev = find_xous_core_revision(cargo_toml_path)? + .ok_or_else(|| anyhow::anyhow!("No xous-core git dependency found in Cargo.toml"))?; + + println!("Found xous-core revision: {}", rev); + println!("Fetching latest tag from GitHub..."); + + let version = get_latest_tag_from_github("betrusted-io/xous-core")?; + + println!("Latest xous-core version: {}", version); + + Ok(version) +} diff --git a/tools/src/lib.rs b/tools/src/lib.rs index 6a2efd11f..05ab4131c 100644 --- a/tools/src/lib.rs +++ b/tools/src/lib.rs @@ -3,6 +3,7 @@ extern crate log; #[macro_use] pub mod xous_arguments; pub mod elf; +pub mod git_remote_version; pub mod sign_image; pub mod swap_writer; pub mod tags; From 47e0899f1b36210cf93883b29cb7390ced2be2f2 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 30 Jan 2026 19:40:05 +0800 Subject: [PATCH 2/6] prune the previous feature added to resolve versions via web interface The problem is that this feature, while neat, pulls in a huge amount of code into the SBOM, a lot of which looks pretty scary, and we're also including the ability to hit the network in the build system which is also scary and potentially full of software supply chain exploits. So, while it would be "neat" to have the system be "smart enough" to guess a semver based on a git rev of xous-core without having to pull down tags or clone the full repo, the cost is a huge amount of tooling and code and trusting a very large attack surface to also not use the same mechanism to exfiltrate your keys, hack your computer, or otherwise cause abuse. For such a minor feature, I think this risk is not worth it. --- tools/Cargo.toml | 11 +++++++---- tools/src/bin/xous-app-uf2.rs | 15 ++++++++++++++- tools/src/git_remote_version.rs | 6 ++++++ tools/src/lib.rs | 5 ++++- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/tools/Cargo.toml b/tools/Cargo.toml index 1a5ec3412..bd9b41262 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -39,10 +39,13 @@ serde_json = "1.0" # bao1x-api = { path = "../libs/bao1x-api" } bao1x-api = "0.1.0" # use crates.io to refer to this -# for remote resolution of github version in out-of-tree builds -reqwest = { version = "0.11", features = ["blocking", "json"] } -anyhow = "1.0" -toml = "0.8" +# for remote resolution of github version in out-of-tree builds. Note that pulling +# in this dependency tree *greatly* increases the attack surface of the SBOM. I don't +# think the convenience is worth it. But these are noted here in case we need to revisit +# this decision later. +# reqwest = { version = "0.11", features = ["blocking", "json"] } +# anyhow = "1.0" +# toml = "0.8" [[bin]] name = "xous-copy-object" diff --git a/tools/src/bin/xous-app-uf2.rs b/tools/src/bin/xous-app-uf2.rs index ab3605eac..3d2d6bc07 100644 --- a/tools/src/bin/xous-app-uf2.rs +++ b/tools/src/bin/xous-app-uf2.rs @@ -109,7 +109,20 @@ fn main() -> Result<(), Box> { let mut source = Cursor::new(Vec::new()); args.write(&mut source).expect("Couldn't write out ELF files"); - let version = xous_tools::git_remote_version::get_xous_version().unwrap_or("v0.0.0".to_string()); + // whack a dummy version into the image. This will cause version compatibility checks to fail, + // if and when they happen. The alternatives are: + // - force the user to specify a version. I think this annoys the user and they probably won't get it + // right + // - automatically resolve the version from the web. A commit + // e41195e3495cb27b447f0aec897c8928f29ced9d temporarily pulls in the code to do this, but the + // problem is that querying github to automatically resolve versions pulls in a *huge* attack + // surface, and also builds now try to tickle network resources which feels distasteful to me and + // not the right direction to go. + // + // So between two bad options, the decision for now is to do nothing and leave this field at 0, which + // as of now doesn't cause trouble but if in the future we want to do something where a kernel checks + // the version of a binary to make sure it's compatible before running it - it'll break. + let version = "v0.0.0".to_string(); let semver: [u8; 16] = SemVer::from_str(&version)?.into(); let result = xous_tools::sign_image::sign_image( diff --git a/tools/src/git_remote_version.rs b/tools/src/git_remote_version.rs index d85a566e8..32fc3d72f 100644 --- a/tools/src/git_remote_version.rs +++ b/tools/src/git_remote_version.rs @@ -1,3 +1,9 @@ +// This code is noted as an option we could pull into the tool set, but the problem with it is +// that its dependence on `reqwest` to interface with github to try and guess semantic versions +// pulls a huge amount of code into the dependency tree that I prefer not to have in the SBOM. +// Thus to get a semantic version users have to either check out tags, assign a version manually, +// or just go with a nil-rev on the versioning. + use std::collections::HashMap; use std::fs; diff --git a/tools/src/lib.rs b/tools/src/lib.rs index 05ab4131c..80b5b7d92 100644 --- a/tools/src/lib.rs +++ b/tools/src/lib.rs @@ -3,8 +3,11 @@ extern crate log; #[macro_use] pub mod xous_arguments; pub mod elf; -pub mod git_remote_version; pub mod sign_image; pub mod swap_writer; pub mod tags; pub mod utils; + +// This option is "hard-commented" out because we're trying to avoid even having +// the dependencies for this feature in our build system. +// pub mod git_remote_version; From 6d6f41f426ad3a480d77653055a7abde8457c70c Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 30 Jan 2026 19:42:24 +0800 Subject: [PATCH 3/6] bump minor rev on xous-tools this forces the semver to nil so that we don't get errors in a signing routine that lacks access to versioning. The upshot is that out of tree apps have no version assigned to them, and they can't be checked for version compatibility. --- tools/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/Cargo.toml b/tools/Cargo.toml index bd9b41262..cd25944c7 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -3,7 +3,7 @@ authors = ["Sean Cross ", "bunnie "] default-run = "xous-app-uf2" edition = "2018" name = "xous-tools" -version = "0.1.0" +version = "0.1.1" description = "A set of tools for managing Xous ecosystem binaries" license = "Apache-2.0" From d01615ff6e1a46590694f1c8b2578bdb353d99eb Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 30 Jan 2026 20:25:51 +0800 Subject: [PATCH 4/6] add handling for anti-rollback code in signed images for out of tree builds, we'll just stick with the default code of '1': if you're doing a build out of tree, it's assumed that you don't care about security (not tying your application to a given OS version opens up an attack surface; presumably if you're doing something security-critical, the extra hundred megabytes to clone the xous-core repo isn't a big deal? but if you're just trying to blink some LEDs you really don't care about the anti-rollback feature). --- tools/src/bin/xous-app-uf2.rs | 30 +++++++++++++++++++++++++++++- tools/src/bin/xous-create-image.rs | 2 +- tools/src/sign_image.rs | 20 ++++++++++++++------ tools/src/swap_writer.rs | 8 +++++++- 4 files changed, 51 insertions(+), 9 deletions(-) diff --git a/tools/src/bin/xous-app-uf2.rs b/tools/src/bin/xous-app-uf2.rs index 3d2d6bc07..00b239e53 100644 --- a/tools/src/bin/xous-app-uf2.rs +++ b/tools/src/bin/xous-app-uf2.rs @@ -15,6 +15,7 @@ use xous_tools::swap_writer::SwapWriter; use xous_tools::tags::inif::IniF; use xous_tools::tags::inis::IniS; use xous_tools::tags::pnam::ProcessNames; +use xous_tools::utils::parse_u32; use xous_tools::xous_arguments::XousArgumentCode; use xous_tools::xous_arguments::XousArguments; @@ -36,6 +37,19 @@ fn main() -> Result<(), Box> { .required(true) .help("List of ELF files to incorporate in the detached app"), ) + .arg( + Arg::with_name("antirollback") + .long("antirollback") + .takes_value(true) + .help("Anti-rollback number. Must be greater than or equal to the current anti-rollback number on the target system.") + // 1 is probably reasonable default value, as for out-of-tree builds I don't see any scenario where for developers + // the anti-rollback counter would be incremented. Security-conscious developers would care to see that the kernel + // version is intimately linked to the app version; if you're preferring to do out of tree builds then you've + // YOLO'd on security, anyways. The place where this might need to be notched up is if someone had a device + // once upon a time used for secure things, and then they decided to give it a new life as a toy, in which case, + // the anti-rollback counter could be incremented and they'd have to increment this to match the current ARB state. + .default_value("1") + ) .arg( Arg::with_name("swap") .long("swap") @@ -48,6 +62,19 @@ fn main() -> Result<(), Box> { let mut pid: u32 = 1; + let anti_rollback = if let Some(arb) = matches.value_of("antirollback") { + parse_u32(arb).map_err(|_| String::from("Antirollback should be a number"))? + } else { + 1 + }; + // set this to a...somewhat conservative value. Hopefully we're not deprecating 500 firmware + // versions ever, but also much less than the wear-out threshold of the counter. This helps + // prevent someone "just poking around" from configuring this value to something harmful + // to the hardware. + if anti_rollback > 500 { + panic!("Antirollback value of {} is too large, refusing to sign", anti_rollback); + } + let mut args = if matches.is_present("swap") { XousArguments::new( 0, @@ -95,7 +122,7 @@ fn main() -> Result<(), Box> { // Create the swap target image and encrypt swap_buffer to it let mut swap = Cursor::new(Vec::new()); - swap_buffer.encrypt_to(&mut swap, &private_key)?; + swap_buffer.encrypt_to(&mut swap, &private_key, Some(anti_rollback as usize))?; // generate a uf2 file let swap_uf2 = "swap.uf2"; @@ -135,6 +162,7 @@ fn main() -> Result<(), Box> { bao1x_api::signatures::SIGBLOCK_LEN, xous_tools::sign_image::Version::Bao1xV1, Some("app"), + Some(anti_rollback as usize), )?; let app_uf2 = "apps.uf2"; diff --git a/tools/src/bin/xous-create-image.rs b/tools/src/bin/xous-create-image.rs index 2ef6004ff..70bfb9cbb 100644 --- a/tools/src/bin/xous-create-image.rs +++ b/tools/src/bin/xous-create-image.rs @@ -508,7 +508,7 @@ fn main() -> Result<(), Box> { { let sf = File::create(swap_filename) .unwrap_or_else(|_| panic!("Couldn't create output file {}", swap_filename)); - swap_buffer.encrypt_to(sf, &swap_pkey).expect("Couldn't flush swap buffer to disk"); + swap_buffer.encrypt_to(sf, &swap_pkey, None).expect("Couldn't flush swap buffer to disk"); } // drop sf, so it closes println!("Swap arguments: {}", sargs); diff --git a/tools/src/sign_image.rs b/tools/src/sign_image.rs index bac9256ef..b9ff5602b 100644 --- a/tools/src/sign_image.rs +++ b/tools/src/sign_image.rs @@ -75,6 +75,7 @@ pub fn sign_image( length: usize, version: Version, function_code: Option<&str>, + anti_rollback_manual: Option, ) -> Result, Box> { let mut dest_file = vec![]; @@ -188,8 +189,6 @@ pub fn sign_image( Ok(dest_file) } Version::Bao1xV1 => { - let anti_rollback = read_anti_rollback("./signing/anti-rollback.hjson")?; - let pkinfo = PrivateKeyInfo::from_der(&private_key.contents).map_err(|e| format!("{}", e))?; // First 2 bytes of the `private_key` are a record specifier and length field. Check they are // correct. @@ -207,9 +206,17 @@ pub fn sign_image( .map_err(|e| format!("{}", e))?; let pubkey = sk.public_key(); */ - let anti_rollback = anti_rollback - .get(function_code.unwrap_or("unspecified")) - .expect("anti-rollback code not specified"); + let anti_rollback = if let Some(code) = anti_rollback_manual { + code as u32 + } else { + let anti_rollback = + read_anti_rollback("./signing/anti-rollback.hjson").inspect_err(|_e| { + println!("anti-rollback.hjson file not present, can't determine anti-rollback code!"); + })?; + *(anti_rollback + .get(function_code.unwrap_or("unspecified")) + .expect("anti-rollback code not specified")) + }; let function_code = match function_code { Some("boot0") => FunctionCode::Boot0, @@ -225,7 +232,7 @@ pub fn sign_image( 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.anti_rollback = *anti_rollback; + header.sealed_data.anti_rollback = anti_rollback; header.sealed_data.min_semver = minver_bytes; header.sealed_data.semver = semver; @@ -317,6 +324,7 @@ where sector_length, version, function_code, + None, )?; dest_file.write_all(&result)?; Ok(()) diff --git a/tools/src/swap_writer.rs b/tools/src/swap_writer.rs index da6142030..62859ce37 100644 --- a/tools/src/swap_writer.rs +++ b/tools/src/swap_writer.rs @@ -83,7 +83,12 @@ impl SwapWriter { /// Take the swap file and wrap it data structures that facilitate per-device encryption /// after deployment to a user device. - pub fn encrypt_to(&mut self, mut f: T, private_key: &pem::Pem) -> Result + pub fn encrypt_to( + &mut self, + mut f: T, + private_key: &pem::Pem, + anti_rollback_manual: Option, + ) -> Result where T: Write + Seek, { @@ -136,6 +141,7 @@ impl SwapWriter { bao1x_api::signatures::SIGBLOCK_LEN, Version::Bao1xV1, function, + anti_rollback_manual, ) .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Can't sign swap image"))?; // write the header, less space for the signature From f08a04308dd13daa0bcb22ed33da4dbf53e0339d Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 30 Jan 2026 20:28:26 +0800 Subject: [PATCH 5/6] bump version for xous-tools publishing the antirollback feature --- Cargo.lock | 2 +- tools/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 579b3b35a..07ae49e7d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7744,7 +7744,7 @@ dependencies = [ [[package]] name = "xous-tools" -version = "0.1.0" +version = "0.1.2" dependencies = [ "aes-gcm-siv", "bao1x-api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/tools/Cargo.toml b/tools/Cargo.toml index cd25944c7..edf5c3f59 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -3,7 +3,7 @@ authors = ["Sean Cross ", "bunnie "] default-run = "xous-app-uf2" edition = "2018" name = "xous-tools" -version = "0.1.1" +version = "0.1.2" description = "A set of tools for managing Xous ecosystem binaries" license = "Apache-2.0" From b6b37f601e36a72cc158da2d7a1dc7bf752cc1e0 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 30 Jan 2026 21:02:31 +0800 Subject: [PATCH 6/6] note out of tree build feature in the README docs --- README-baochip.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/README-baochip.md b/README-baochip.md index d023aab06..df251a521 100644 --- a/README-baochip.md +++ b/README-baochip.md @@ -58,6 +58,22 @@ Three application targets are supported by Xous: 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. +#### Out of Tree Application Builds + +For developers that don't need strong security, "out of tree" builds are available. An out of tree build allows just the app to be built on its own, targeting a xous-core revision via a github revision. See this [out of tree demo app](https://github.com/bunnie/dabao-console) for more information on how to set up and run an out of tree build. + +Out of tree advantages: +- Just the application code is cloned +- Faster, lighter-weight builds + +Out of tree disadvantages: +- Application and kernel can be out of sync +- Features like anti-rollback, version checking, and secure signing don't work + +If you're looking to use the Baochip as a lightweight microcontroller for write-once projects, out of tree builds might be a good match for your scenario. + +If you're looking to build a more durable application meant to be distributed as a product with firmware signing, you'll want to do an in-tree build. + ## Security Model The default `bao1x` chips come from the factory with four public keys burned into them: