Compare commits

...
Author SHA1 Message Date
noah 75b7424a0d Merge pull request 'Avoid duplicate Toolkit feature branch CI' (#14) from ci/drop-duplicate-toolkit-feature-verify into next
next-build / candidate (push) Successful in 11m8s
2026-10-21 06:58:54 -06:00
noah 8d4fe502be Avoid duplicate Toolkit feature branch CI 2026-10-21 06:57:38 -06:00
noah 038c1b1c2b Merge pull request 'Add fast next pull request source gate' (#13) from ci/next-pr-source-check into next 2026-10-21 06:55:56 -06:00
noah 20d7f49c9d Scope Toolkit source checks to changed Rust 2026-10-21 06:54:48 -06:00
noah 74cee50d35 Add fast next pull request source gate 2026-10-21 06:51:32 -06:00
noah 32a75c92ef Merge pull request 'Route toolkit benchmark publication to verifier' (#9) from ci/isolate-fast-runner-next into next 2026-10-21 06:49:08 -06:00
noah f4d9c12bb6 Route toolkit benchmark publication to verifier 2026-10-20 18:45:04 -06:00
noah b610ce3d7f Validate SDK archive contents in Rust before install 2026-10-17 11:13:17 -06:00
noah 1a5dcd17a9 Verify SDK release archives from checksum sidecar 2026-10-17 10:11:15 -06:00
noah 3b1b1fa63e Document running build verification and lock CLI dependency 2026-10-17 10:08:34 -06:00
noah 7880b14e47 Expose running build verification in toolkit CLI 2026-10-17 10:03:34 -06:00
noah 5bbf5b71b7 Verify running board build marker against CI artifact 2026-10-17 10:01:04 -06:00
noah cfec9606a4 Require observed MTD geometry before resolving flash target 2026-10-17 09:02:13 -06:00
noah e8d7cdc77a Parse MTD layouts before board flash planning 2026-10-17 08:02:02 -06:00
noah 8ba585679a Add bounded read-only SSH board probes 2026-10-17 07:02:01 -06:00
10 changed files with 1061 additions and 13 deletions
+3 -1
View File
@@ -11,7 +11,9 @@ concurrency:
jobs:
publish:
runs-on: alkane-pages
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
permissions:
contents: read
steps:
+89
View File
@@ -0,0 +1,89 @@
name: source
on:
pull_request:
branches: [next]
concurrency:
group: alkane-toolkit-source-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
runs-on: alkane-fast
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check changed source
id: surface
run: |
base="$(git merge-base HEAD origin/next)"
git diff --check "$base" HEAD
python3 - "$base" <<'PY' >> "$GITHUB_OUTPUT"
import os
from pathlib import Path
import re
import subprocess
import sys
changed = subprocess.check_output(
['git', 'diff', '--name-only', '-z', sys.argv[1], 'HEAD']
).split(b'\0')
pem = re.compile(
rb'^[ \t]*-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[ \t]*$'
)
for raw in changed:
path = Path(os.fsdecode(raw))
if not raw or not path.is_file() or path.is_symlink():
continue
with path.open('rb') as source:
for number, line in enumerate(source, 1):
if pem.fullmatch(line.rstrip(b'\r\n')):
print(f'private key material: {path}:{number}', file=sys.stderr)
raise SystemExit(1)
rust_prefixes = (
b'crates/alkane-core/', b'crates/alkane-discovery/',
b'crates/alkane-access/', b'crates/alkane-flash/',
b'crates/alkane-artifacts/', b'crates/alkane-cli/',
b'thirdparty/asic-rs/', b'.cargo/',
)
rust = any(
path in (b'Cargo.toml', b'Cargo.lock', b'rust-toolchain.toml')
or path.startswith(rust_prefixes)
for path in changed if path
)
print(f"rust={'true' if rust else 'false'}")
PY
python3 - <<'PY'
from pathlib import Path
for path in Path('ci').glob('*.py'):
compile(path.read_text(), str(path), 'exec')
PY
for script in ci/*.sh scripts/*.sh; do
bash -n "$script"
done
- name: Check non-GUI Rust format
if: steps.surface.outputs.rust == 'true'
run: |
rustup component add rustfmt
cargo fmt --check \
--package alkane-core \
--package alkane-discovery \
--package alkane-access \
--package alkane-flash \
--package alkane-artifacts \
--package alkane-cli
- name: Check non-GUI Rust crates
if: steps.surface.outputs.rust == 'true'
env:
CARGO_TARGET_DIR: target
run: |
cargo check --offline --locked \
-p alkane-core -p alkane-discovery -p alkane-access \
-p alkane-flash -p alkane-artifacts -p alkane-cli
- name: Clean generated work
if: always()
run: python3 ci/cleanup-generated.py
+7 -7
View File
@@ -1,14 +1,14 @@
name: verify
# Pre-merge quality gate: clippy + build + tests + microbenchmarks + the headless
# UI self-test, plus a best-effort dependency audit. Runs on pull requests and on
# pushes to any branch EXCEPT main (main is gated by release.yml, which repeats
# these checks before it cuts a release -- so no work is duplicated on main).
# Full quality gate for pull requests to main. The fast source workflow checks
# pull requests to next, and branch workflows build after each merge.
on:
pull_request:
branches-ignore: [next]
push:
branches-ignore: [main, next]
branches: [main]
concurrency:
group: alkane-toolkit-verify-${{ github.ref }}
cancel-in-progress: true
jobs:
verify:
Generated
+3
View File
@@ -40,7 +40,9 @@ name = "alkane-artifacts"
version = "0.1.0"
dependencies = [
"alkane-core",
"flate2",
"sha2",
"tar",
"thiserror",
]
@@ -48,6 +50,7 @@ dependencies = [
name = "alkane-cli"
version = "0.1.0"
dependencies = [
"alkane-access",
"alkane-artifacts",
"alkane-core",
]
+15
View File
@@ -55,6 +55,21 @@ Installation must follow the [SDK install rules](https://gitea.bluefla.re/bluefl
use the exact board's packer and boot-switch procedure, verify through an
independent channel, and never write bootloader or secure regions.
After an Alkane image boots, compare its build marker with the verified
archive from a separate host:
```sh
alkane-cli verify-sdk-release <SHA256SUMS> <downloaded-board-archive>
alkane-cli verify-running-build <ip> <ssh-user> <absolute-known-hosts-file> <board> <sdk-commit> <os-commit>
```
The first command checks the release checksum, inner file list, checksums,
and SDK and OS revisions for a board archive. It prints the revisions to use
in the second command. The QEMU research archive has no board revision
metadata, so only its release checksum is checked. The second command reads
`/etc/alkane-build` over SSH and fails on a mismatch. Neither command installs
firmware or establishes the recovery path.
## License
[MIT](LICENSE). Vendored dependencies keep their own terms.
+537 -1
View File
@@ -1 +1,537 @@
// alkane-access
// SPDX-License-Identifier: MIT
//! Bounded, read-only SSH probes for board identification.
use std::collections::HashSet;
use std::fs;
use std::io::{self, Read};
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
const MAX_PROBE_BYTES: usize = 64 * 1024;
const PROBE_TIMEOUT: Duration = Duration::from_secs(12);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Probe {
KernelRelease,
MtdTable,
DeviceTreeModel,
AlkaneBuildMarker,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AlkaneBuildMarker {
pub board: String,
pub sdk_revision: String,
pub os_revision: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BuildMarkerError {
InvalidFormat,
InvalidBoard,
InvalidRevision,
UnexpectedBuild,
}
/// A running board must report the identity embedded in the CI artifact.
/// This parser accepts the exact three-line marker emitted by the SDK.
pub fn parse_build_marker(bytes: &[u8]) -> Result<AlkaneBuildMarker, BuildMarkerError> {
if bytes.len() > 256 {
return Err(BuildMarkerError::InvalidFormat);
}
let text = std::str::from_utf8(bytes).map_err(|_| BuildMarkerError::InvalidFormat)?;
let mut lines = text.lines();
let board = lines
.next()
.and_then(|line| line.strip_prefix("board="))
.ok_or(BuildMarkerError::InvalidFormat)?;
let sdk_revision = lines
.next()
.and_then(|line| line.strip_prefix("sdk_revision="))
.ok_or(BuildMarkerError::InvalidFormat)?;
let os_revision = lines
.next()
.and_then(|line| line.strip_prefix("os_revision="))
.ok_or(BuildMarkerError::InvalidFormat)?;
if lines.next().is_some() || !text.ends_with('\n') {
return Err(BuildMarkerError::InvalidFormat);
}
if !matches!(
board,
"am335x-bb"
| "zynq-7010"
| "cv1835"
| "a113d"
| "allwinner-h3"
| "allwinner-h6"
| "allwinner-h616"
) {
return Err(BuildMarkerError::InvalidBoard);
}
for revision in [sdk_revision, os_revision] {
if revision.len() != 40
|| !revision
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
{
return Err(BuildMarkerError::InvalidRevision);
}
}
Ok(AlkaneBuildMarker {
board: board.to_owned(),
sdk_revision: sdk_revision.to_owned(),
os_revision: os_revision.to_owned(),
})
}
pub fn verify_build_marker(
observed: &AlkaneBuildMarker,
expected: &AlkaneBuildMarker,
) -> Result<(), BuildMarkerError> {
if observed == expected {
Ok(())
} else {
Err(BuildMarkerError::UnexpectedBuild)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MtdPartition {
pub index: u32,
pub size_bytes: u64,
pub erase_bytes: u64,
pub name: String,
}
/// The partition identity and geometry required by an SDK flash plan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MtdRequirement {
pub index: u32,
pub name: String,
pub size_bytes: u64,
pub erase_bytes: u64,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MtdTarget {
pub device: PathBuf,
pub size_bytes: u64,
}
#[derive(Debug, Eq, PartialEq)]
pub enum MtdMatchError {
MissingIndex,
AmbiguousIndex,
NameMismatch,
SizeMismatch,
EraseMismatch,
}
/// Resolve a character device only after comparing the observed partition
/// with the expected identity and geometry. This does not authorize a write.
pub fn resolve_mtd_target(
observed: &[MtdPartition],
expected: &MtdRequirement,
) -> Result<MtdTarget, MtdMatchError> {
let mut matches = observed
.iter()
.filter(|entry| entry.index == expected.index);
let entry = matches.next().ok_or(MtdMatchError::MissingIndex)?;
if matches.next().is_some() {
return Err(MtdMatchError::AmbiguousIndex);
}
if entry.name != expected.name {
return Err(MtdMatchError::NameMismatch);
}
if entry.size_bytes != expected.size_bytes {
return Err(MtdMatchError::SizeMismatch);
}
if entry.erase_bytes != expected.erase_bytes {
return Err(MtdMatchError::EraseMismatch);
}
Ok(MtdTarget {
device: PathBuf::from(format!("/dev/mtd{}", entry.index)),
size_bytes: entry.size_bytes,
})
}
#[derive(Debug, Eq, PartialEq)]
pub enum MtdError {
InvalidHeader,
InvalidEntry(usize),
DuplicateIndex,
DuplicateName,
TooManyEntries,
}
/// Parse `/proc/mtd` as data. A flash plan must match both partition index
/// and name against its board-specific layout before using a device path.
pub fn parse_mtd_table(bytes: &[u8]) -> Result<Vec<MtdPartition>, MtdError> {
if bytes.len() > MAX_PROBE_BYTES {
return Err(MtdError::TooManyEntries);
}
let text = std::str::from_utf8(bytes).map_err(|_| MtdError::InvalidHeader)?;
let mut lines = text.lines();
if lines
.next()
.map(str::split_whitespace)
.map(Iterator::collect::<Vec<_>>)
!= Some(vec!["dev:", "size", "erasesize", "name"])
{
return Err(MtdError::InvalidHeader);
}
let mut entries = Vec::new();
let mut indices = HashSet::new();
let mut names = HashSet::new();
for (offset, line) in lines.enumerate() {
if line.trim().is_empty() {
continue;
}
let line_number = offset + 2;
if entries.len() >= 128 {
return Err(MtdError::TooManyEntries);
}
let invalid = || MtdError::InvalidEntry(line_number);
let start = line.find('"').ok_or_else(invalid)?;
let end = line.rfind('"').ok_or_else(invalid)?;
if start == end || !line[end + 1..].trim().is_empty() {
return Err(invalid());
}
let fields: Vec<_> = line[..start].split_whitespace().collect();
if fields.len() != 3 {
return Err(invalid());
}
let index = fields[0]
.strip_prefix("mtd")
.and_then(|value| value.strip_suffix(':'))
.and_then(|value| value.parse::<u32>().ok())
.ok_or_else(invalid)?;
let size_bytes = u64::from_str_radix(fields[1], 16).map_err(|_| invalid())?;
let erase_bytes = u64::from_str_radix(fields[2], 16).map_err(|_| invalid())?;
let name = &line[start + 1..end];
if size_bytes == 0
|| erase_bytes == 0
|| name.is_empty()
|| name.len() > 128
|| !name
.bytes()
.all(|byte| byte.is_ascii_graphic() || byte == b' ')
|| name.contains('"')
{
return Err(invalid());
}
if !indices.insert(index) {
return Err(MtdError::DuplicateIndex);
}
if !names.insert(name.to_owned()) {
return Err(MtdError::DuplicateName);
}
entries.push(MtdPartition {
index,
size_bytes,
erase_bytes,
name: name.to_owned(),
});
}
if entries.is_empty() {
return Err(MtdError::InvalidHeader);
}
Ok(entries)
}
impl Probe {
fn command(self) -> &'static str {
match self {
Self::KernelRelease => "uname -r",
Self::MtdTable => "cat /proc/mtd",
Self::DeviceTreeModel => "cat /proc/device-tree/model",
Self::AlkaneBuildMarker => "cat /etc/alkane-build",
}
}
}
#[derive(Debug)]
pub enum AccessError {
InvalidTarget,
InvalidKnownHosts,
Timeout,
OutputTooLarge,
RemoteFailure,
Io(io::Error),
}
impl From<io::Error> for AccessError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
pub struct SshTarget {
address: IpAddr,
port: u16,
user: String,
known_hosts: PathBuf,
}
impl SshTarget {
pub fn new(
address: IpAddr,
port: u16,
user: &str,
known_hosts: &Path,
) -> Result<Self, AccessError> {
if port == 0
|| user.is_empty()
|| !user
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
{
return Err(AccessError::InvalidTarget);
}
if !known_hosts.is_absolute()
|| !fs::metadata(known_hosts).is_ok_and(|metadata| metadata.is_file())
{
return Err(AccessError::InvalidKnownHosts);
}
Ok(Self {
address,
port,
user: user.to_owned(),
known_hosts: known_hosts.to_owned(),
})
}
fn command(&self, probe: Probe) -> Command {
let mut command = Command::new("ssh");
command
.arg("-F")
.arg("none")
.arg("-o")
.arg("BatchMode=yes")
.arg("-o")
.arg("StrictHostKeyChecking=yes")
.arg("-o")
.arg("GlobalKnownHostsFile=none")
.arg("-o")
.arg(format!("UserKnownHostsFile={}", self.known_hosts.display()))
.arg("-o")
.arg("ConnectTimeout=5")
.arg("-o")
.arg("ServerAliveInterval=5")
.arg("-o")
.arg("ServerAliveCountMax=1")
.arg("-o")
.arg("RequestTTY=no")
.arg("-p")
.arg(self.port.to_string())
.arg(format!("{}@{}", self.user, self.address))
.arg(probe.command());
command
}
pub fn probe(&self, probe: Probe) -> Result<Vec<u8>, AccessError> {
run_bounded(self.command(probe))
}
}
fn collect_bounded<R: Read + Send + 'static>(
mut reader: R,
) -> thread::JoinHandle<Result<Vec<u8>, AccessError>> {
thread::spawn(move || {
let mut data = Vec::new();
let mut chunk = [0_u8; 4096];
loop {
let count = reader.read(&mut chunk)?;
if count == 0 {
return Ok(data);
}
if data.len() + count > MAX_PROBE_BYTES {
return Err(AccessError::OutputTooLarge);
}
data.extend_from_slice(&chunk[..count]);
}
})
}
fn run_bounded(command: Command) -> Result<Vec<u8>, AccessError> {
run_bounded_with_timeout(command, PROBE_TIMEOUT)
}
fn run_bounded_with_timeout(
mut command: Command,
timeout: Duration,
) -> Result<Vec<u8>, AccessError> {
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = command.spawn()?;
let stdout = collect_bounded(child.stdout.take().expect("piped stdout"));
let stderr = collect_bounded(child.stderr.take().expect("piped stderr"));
let deadline = Instant::now() + timeout;
let result = loop {
if let Some(status) = child.try_wait()? {
break status.success();
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
let _ = stdout.join();
let _ = stderr.join();
return Err(AccessError::Timeout);
}
thread::sleep(Duration::from_millis(10));
};
let output = stdout.join().map_err(|_| AccessError::RemoteFailure)??;
let error_output = stderr.join().map_err(|_| AccessError::RemoteFailure)??;
if !result || !error_output.is_empty() {
return Err(AccessError::RemoteFailure);
}
Ok(output)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn target_rejects_injected_user_and_unknown_host_file() {
let address = "127.0.0.1".parse().unwrap();
assert!(matches!(
SshTarget::new(
address,
22,
"root;id",
Path::new("/etc/ssh/ssh_known_hosts")
),
Err(AccessError::InvalidTarget)
));
assert!(matches!(
SshTarget::new(address, 22, "root", Path::new("relative-known-hosts")),
Err(AccessError::InvalidKnownHosts)
));
}
#[cfg(unix)]
#[test]
fn bounded_runner_rejects_excess_output_and_failed_command() {
let mut success = Command::new("/bin/sh");
success.args(["-c", "printf board"]);
assert_eq!(run_bounded(success).unwrap(), b"board");
let mut overflow = Command::new("/bin/sh");
overflow.args(["-c", "head -c 70000 /dev/zero"]);
assert!(matches!(
run_bounded(overflow),
Err(AccessError::OutputTooLarge)
));
let mut failed = Command::new("/bin/sh");
failed.args(["-c", "exit 7"]);
assert!(matches!(
run_bounded(failed),
Err(AccessError::RemoteFailure)
));
let mut hanging = Command::new("/bin/sleep");
hanging.arg("1");
assert!(matches!(
run_bounded_with_timeout(hanging, Duration::from_millis(20)),
Err(AccessError::Timeout)
));
}
#[test]
fn parses_captured_mtd_layout_and_rejects_duplicate_targets() {
let captured = b"dev: size erasesize name\n\
mtd0: 02800000 00020000 \"BOOT.bin-dts-marker-kernel\"\n\
mtd1: 02000000 00020000 \"ramfs\"\n";
let entries = parse_mtd_table(captured).unwrap();
assert_eq!(entries[0].index, 0);
assert_eq!(entries[0].size_bytes, 0x0280_0000);
assert_eq!(entries[0].erase_bytes, 0x0002_0000);
assert_eq!(entries[0].name, "BOOT.bin-dts-marker-kernel");
let duplicate = b"dev: size erasesize name\n\
mtd0: 00020000 00020000 \"boot\"\n\
mtd0: 00020000 00020000 \"root\"\n";
assert_eq!(parse_mtd_table(duplicate), Err(MtdError::DuplicateIndex));
assert_eq!(
parse_mtd_table(b"mtd0: 1 1 \"boot\"\n"),
Err(MtdError::InvalidHeader)
);
}
#[test]
fn flash_target_requires_captured_identity_and_geometry() {
let observed = parse_mtd_table(
b"dev: size erasesize name\n\
mtd0: 02800000 00020000 \"BOOT.bin-dts-marker-kernel\"\n\
mtd1: 02000000 00020000 \"ramfs\"\n",
)
.unwrap();
let mut required = MtdRequirement {
index: 0,
name: "BOOT.bin-dts-marker-kernel".to_owned(),
size_bytes: 0x0280_0000,
erase_bytes: 0x0002_0000,
};
assert_eq!(
resolve_mtd_target(&observed, &required).unwrap().device,
Path::new("/dev/mtd0")
);
required.name = "ramfs".to_owned();
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::NameMismatch)
);
required.name = observed[0].name.clone();
required.size_bytes -= 1;
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::SizeMismatch)
);
required.size_bytes = observed[0].size_bytes;
required.erase_bytes *= 2;
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::EraseMismatch)
);
required.index = 2;
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::MissingIndex)
);
}
#[test]
fn running_build_marker_must_match_the_artifact() {
let sha = "0123456789abcdef0123456789abcdef01234567";
let marker = format!("board=am335x-bb\nsdk_revision={sha}\nos_revision={sha}\n");
let expected = parse_build_marker(marker.as_bytes()).unwrap();
assert_eq!(verify_build_marker(&expected, &expected), Ok(()));
let other = AlkaneBuildMarker {
board: "zynq-7010".to_owned(),
..expected.clone()
};
assert_eq!(
verify_build_marker(&expected, &other),
Err(BuildMarkerError::UnexpectedBuild)
);
assert_eq!(
parse_build_marker(
marker
.replace("board=am335x-bb", "board=unknown")
.as_bytes()
),
Err(BuildMarkerError::InvalidBoard)
);
assert_eq!(
parse_build_marker(marker.replace(sha, "not-a-commit").as_bytes()),
Err(BuildMarkerError::InvalidRevision)
);
assert_eq!(
parse_build_marker(format!("{marker}extra=value\n").as_bytes()),
Err(BuildMarkerError::InvalidFormat)
);
}
}
+2
View File
@@ -8,3 +8,5 @@ license.workspace = true
alkane-core = { path = "../alkane-core" }
sha2.workspace = true
thiserror.workspace = true
flate2 = "1"
tar = "0.4"
+345 -1
View File
@@ -1,8 +1,9 @@
// SPDX-License-Identifier: MIT
//! Verify local firmware artifacts before an install path consumes them.
use flate2::read::GzDecoder;
use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Component, Path, PathBuf};
@@ -10,6 +11,26 @@ use thiserror::Error;
const SEED: &str = include_str!("../data/manifest-seed.csv");
const HEADER: &str = "sha256,size_bytes,path,family,format,applicability";
const SDK_RELEASE_ASSETS: [&str; 8] = [
"alkane-sdk-a113d.tar.gz",
"alkane-sdk-allwinner-h3.tar.gz",
"alkane-sdk-allwinner-h6.tar.gz",
"alkane-sdk-allwinner-h616.tar.gz",
"alkane-sdk-am335x-bb.tar.gz",
"alkane-sdk-cv1835.tar.gz",
"alkane-sdk-qemu-zynq-research.tar.gz",
"alkane-sdk-zynq-7010.tar.gz",
];
const MAX_SDK_FILES: usize = 64;
const MAX_SDK_FILE_BYTES: u64 = 1024 * 1024 * 1024;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SdkArchiveInfo {
pub board: String,
pub sdk_revision: String,
pub os_revision: String,
pub artifact_count: usize,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ArtifactRecord {
@@ -35,6 +56,10 @@ pub enum VerifyError {
Digest,
#[error("artifact format is not recognized")]
UnsupportedFormat,
#[error("release asset name or path is invalid")]
ReleasePath,
#[error("SDK release archive contents are invalid")]
ReleaseContents,
}
/// A verified, rewound descriptor. Consumers should read this descriptor
@@ -108,6 +133,205 @@ pub fn parse_manifest(text: &str) -> Result<Vec<ArtifactRecord>, VerifyError> {
Ok(records)
}
/// Verify one archive against the complete checksum sidecar from its SDK
/// release. Keep the returned descriptor for any subsequent guarded use.
pub fn verify_sdk_release_archive(
checksums: &Path,
archive: &Path,
) -> Result<VerifiedArtifact, VerifyError> {
if std::fs::metadata(checksums)?.len() > 4096 {
return Err(VerifyError::Manifest(1));
}
let name = archive
.file_name()
.and_then(|value| value.to_str())
.ok_or(VerifyError::ReleasePath)?;
let listed = parse_sdk_release_checksums(&std::fs::read_to_string(checksums)?)?;
let sha256 = listed
.into_iter()
.find_map(|(entry, digest)| (entry == name).then_some(digest))
.ok_or(VerifyError::ReleasePath)?;
let record = ArtifactRecord {
sha256,
size_bytes: std::fs::metadata(archive)?.len(),
path: PathBuf::from(name),
family: name
.strip_prefix("alkane-sdk-")
.and_then(|value| value.strip_suffix(".tar.gz"))
.ok_or(VerifyError::ReleasePath)?
.to_owned(),
format: "tar-gzip".to_owned(),
applicability: "sdk-release".to_owned(),
};
verify_file(archive, &record)
}
/// Check the inner file list and revisions of a previously verified SDK archive.
/// This reads the verified descriptor; it never extracts archive paths.
pub fn inspect_sdk_release_archive(
verified: &mut VerifiedArtifact,
) -> Result<SdkArchiveInfo, VerifyError> {
let board = verified
.record
.family
.strip_prefix("qemu-")
.unwrap_or(&verified.record.family)
.to_owned();
let prefix = format!("alkane-sdk-{board}/");
verified.file.seek(SeekFrom::Start(0))?;
let decoder = GzDecoder::new(&mut verified.file);
let mut archive = tar::Archive::new(decoder);
let mut digests = HashMap::new();
let mut metadata = HashMap::new();
let mut count = 0;
for entry in archive.entries()?.raw(true) {
let mut entry = entry?;
count += 1;
if count > MAX_SDK_FILES {
return Err(VerifyError::ReleaseContents);
}
let path = entry.path_bytes().into_owned();
if count == 1 {
if !entry.header().entry_type().is_dir()
|| path.as_slice() != prefix.trim_end_matches('/').as_bytes()
&& path.as_slice() != prefix.as_bytes()
{
return Err(VerifyError::ReleaseContents);
}
continue;
}
if !entry.header().entry_type().is_file()
|| entry.size() > MAX_SDK_FILE_BYTES
|| !path.starts_with(prefix.as_bytes())
{
return Err(VerifyError::ReleaseContents);
}
let name =
std::str::from_utf8(&path[prefix.len()..]).map_err(|_| VerifyError::ReleaseContents)?;
if name.is_empty()
|| name == "."
|| name == ".."
|| !name.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'+' | b'-')
})
|| digests.contains_key(name)
{
return Err(VerifyError::ReleaseContents);
}
let mut hasher = Sha256::new();
let mut contents = Vec::new();
let is_metadata = matches!(name, "SDK-REVISION" | "OS-REVISION" | "SHA256SUMS");
if is_metadata && entry.size() > 100_000 {
return Err(VerifyError::ReleaseContents);
}
let mut buffer = [0_u8; 64 * 1024];
let mut read_bytes = 0_u64;
loop {
let length = entry.read(&mut buffer)?;
if length == 0 {
break;
}
read_bytes += length as u64;
hasher.update(&buffer[..length]);
if is_metadata {
contents.extend_from_slice(&buffer[..length]);
}
}
if read_bytes != entry.size() {
return Err(VerifyError::ReleaseContents);
}
if is_metadata {
metadata.insert(name.to_owned(), contents);
}
digests.insert(name.to_owned(), format!("{:x}", hasher.finalize()));
}
let mut decoder = archive.into_inner();
// Drain the gzip trailer to check its CRC, with a bound on tar padding.
if std::io::copy(
&mut decoder.by_ref().take(1024 * 1024 + 1),
&mut std::io::sink(),
)? > 1024 * 1024
{
return Err(VerifyError::ReleaseContents);
}
drop(decoder);
verified.revalidate()?;
let revision = |key| -> Result<String, VerifyError> {
let bytes = metadata.get(key).ok_or(VerifyError::ReleaseContents)?;
if bytes.len() != 41 || bytes[40] != b'\n' || !bytes[..40].iter().all(u8::is_ascii_hexdigit)
{
return Err(VerifyError::ReleaseContents);
}
let text = std::str::from_utf8(&bytes[..40]).map_err(|_| VerifyError::ReleaseContents)?;
if !text
.bytes()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
{
return Err(VerifyError::ReleaseContents);
}
Ok(text.to_owned())
};
let sdk_revision = revision("SDK-REVISION")?;
let os_revision = revision("OS-REVISION")?;
let checksums = metadata
.get("SHA256SUMS")
.ok_or(VerifyError::ReleaseContents)?;
let text = std::str::from_utf8(checksums).map_err(|_| VerifyError::ReleaseContents)?;
if !text.ends_with('\n') {
return Err(VerifyError::ReleaseContents);
}
let mut listed = HashMap::new();
for line in text.lines() {
let (digest, name) = line
.split_once(" ./")
.ok_or(VerifyError::ReleaseContents)?;
if digest.len() != 64
|| !digest
.bytes()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
|| !digests.contains_key(name)
|| listed.insert(name.to_owned(), digest.to_owned()).is_some()
{
return Err(VerifyError::ReleaseContents);
}
}
digests.remove("SHA256SUMS");
if listed != digests || digests.len() < 3 {
return Err(VerifyError::ReleaseContents);
}
Ok(SdkArchiveInfo {
board,
sdk_revision,
os_revision,
artifact_count: digests.len() - 2,
})
}
fn parse_sdk_release_checksums(text: &str) -> Result<Vec<(String, String)>, VerifyError> {
let mut entries = Vec::new();
let mut names = HashSet::new();
for (index, line) in text.lines().enumerate() {
let line_number = index + 1;
let (digest, name) = line
.split_once(" ")
.ok_or(VerifyError::Manifest(line_number))?;
if digest.len() != 64
|| !digest
.bytes()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
|| !SDK_RELEASE_ASSETS.contains(&name)
|| !names.insert(name.to_owned())
{
return Err(VerifyError::Manifest(line_number));
}
entries.push((name.to_owned(), digest.to_owned()));
}
if !text.ends_with('\n') || entries.len() != SDK_RELEASE_ASSETS.len() {
return Err(VerifyError::Manifest(1));
}
Ok(entries)
}
fn signature_matches(format: &str, first: &[u8]) -> Result<bool, VerifyError> {
let prefix: &[u8] = match format {
"IMAGEWTY-SD" | "update-zip" | "zip-installer" => b"PK\x03\x04",
@@ -116,6 +340,7 @@ fn signature_matches(format: &str, first: &[u8]) -> Result<bool, VerifyError> {
"wm-package-0x9a5ba57c" => b"\x7c\xa5\x5b\x9a",
"bmu" => b"\x26\x01",
"bin-AES-container" => b"\x3f\x0a\x64\xae",
"tar-gzip" => b"\x1f\x8b",
_ => return Err(VerifyError::UnsupportedFormat),
};
Ok(first.starts_with(prefix))
@@ -228,6 +453,125 @@ mod tests {
std::fs::remove_file(path).unwrap();
}
#[test]
fn sdk_release_requires_every_asset_and_exact_archive_digest() {
let directory =
std::env::temp_dir().join(format!("alkane-sdk-release-test-{}", std::process::id()));
std::fs::create_dir(&directory).unwrap();
let archive = directory.join(SDK_RELEASE_ASSETS[0]);
let checksums = directory.join("SHA256SUMS");
let bytes = b"\x1f\x8bfixture";
std::fs::write(&archive, bytes).unwrap();
let digest: String = Sha256::digest(bytes)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
let manifest = SDK_RELEASE_ASSETS
.iter()
.map(|name| format!("{digest} {name}\n"))
.collect::<String>();
std::fs::write(&checksums, &manifest).unwrap();
let mut verified = verify_sdk_release_archive(&checksums, &archive).unwrap();
verified.revalidate().unwrap();
std::fs::write(&archive, b"\x1f\x8bfixturX").unwrap();
assert!(matches!(verified.revalidate(), Err(VerifyError::Digest)));
assert!(matches!(
verify_sdk_release_archive(&checksums, &archive),
Err(VerifyError::Digest)
));
std::fs::write(
&checksums,
manifest.lines().take(7).collect::<Vec<_>>().join("\n") + "\n",
)
.unwrap();
assert!(matches!(
verify_sdk_release_archive(&checksums, &archive),
Err(VerifyError::Manifest(1))
));
std::fs::remove_file(archive).unwrap();
std::fs::remove_file(checksums).unwrap();
std::fs::remove_dir(directory).unwrap();
}
fn board_archive(files: &[(&str, &[u8])]) -> Vec<u8> {
let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
let mut builder = tar::Builder::new(encoder);
let mut directory = tar::Header::new_gnu();
directory.set_entry_type(tar::EntryType::Directory);
directory.set_size(0);
directory.set_mode(0o755);
directory.set_cksum();
builder
.append_data(&mut directory, "alkane-sdk-am335x-bb/", std::io::empty())
.unwrap();
for &(name, contents) in files {
let mut header = tar::Header::new_gnu();
header.set_size(contents.len() as u64);
header.set_mode(0o644);
header.set_cksum();
builder
.append_data(
&mut header,
format!("alkane-sdk-am335x-bb/{name}"),
contents,
)
.unwrap();
}
builder.into_inner().unwrap().finish().unwrap()
}
#[test]
fn sdk_inner_archive_requires_safe_files_and_matching_checksums() {
let directory =
std::env::temp_dir().join(format!("alkane-sdk-inner-test-{}", std::process::id()));
std::fs::create_dir(&directory).unwrap();
let archive = directory.join("alkane-sdk-am335x-bb.tar.gz");
let sdk = format!("{}\n", "a".repeat(40));
let os = format!("{}\n", "b".repeat(40));
let artifact = b"image".as_slice();
let files = [
("SDK-REVISION", sdk.as_bytes()),
("OS-REVISION", os.as_bytes()),
("image.bin", artifact),
];
let checksums = files
.iter()
.map(|(name, data)| format!("{:x} ./{name}\n", Sha256::digest(data)))
.collect::<String>();
let mut members = files.to_vec();
members.push(("SHA256SUMS", checksums.as_bytes()));
let good = board_archive(&members);
let record = ArtifactRecord {
sha256: format!("{:x}", Sha256::digest(&good)),
size_bytes: good.len() as u64,
path: PathBuf::from("alkane-sdk-am335x-bb.tar.gz"),
family: "am335x-bb".to_owned(),
format: "tar-gzip".to_owned(),
applicability: "sdk-release".to_owned(),
};
std::fs::write(&archive, &good).unwrap();
let mut verified = verify_file(&archive, &record).unwrap();
let info = inspect_sdk_release_archive(&mut verified).unwrap();
assert_eq!(info.board, "am335x-bb");
assert_eq!(info.sdk_revision, "a".repeat(40));
assert_eq!(info.os_revision, "b".repeat(40));
assert_eq!(info.artifact_count, 1);
members[2] = ("image.bin", b"other");
let changed = board_archive(&members);
std::fs::write(&archive, &changed).unwrap();
let mut changed_record = record.clone();
changed_record.sha256 = format!("{:x}", Sha256::digest(&changed));
changed_record.size_bytes = changed.len() as u64;
let mut verified = verify_file(&archive, &changed_record).unwrap();
assert!(matches!(
inspect_sdk_release_archive(&mut verified),
Err(VerifyError::ReleaseContents)
));
std::fs::remove_file(archive).unwrap();
std::fs::remove_dir(directory).unwrap();
}
#[test]
#[ignore = "microbenchmark"]
fn bench_verify_artifact() {
+1
View File
@@ -7,3 +7,4 @@ license.workspace = true
[dependencies]
alkane-core = { path = "../alkane-core" }
alkane-artifacts = { path = "../alkane-artifacts" }
alkane-access = { path = "../alkane-access" }
+59 -3
View File
@@ -1,14 +1,46 @@
// SPDX-License-Identifier: MIT
//! Headless entry point for read-only artifact verification.
use alkane_artifacts::{seed_manifest, verify_file};
use alkane_access::{parse_build_marker, verify_build_marker, Probe, SshTarget};
use alkane_artifacts::{
inspect_sdk_release_archive, seed_manifest, verify_file, verify_sdk_release_archive,
};
use std::io;
use std::net::IpAddr;
use std::path::Path;
fn run() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
if args.len() != 4 || args[1] != "verify-artifact" {
return Err("usage: alkane-cli verify-artifact <manifest-path> <local-file>".into());
match args.get(1).map(String::as_str) {
Some("verify-artifact") if args.len() == 4 => verify_artifact(&args),
Some("verify-sdk-release") if args.len() == 4 => verify_sdk_release(&args),
Some("verify-running-build") if args.len() == 8 => verify_running_build(&args),
_ => Err("usage: alkane-cli verify-artifact <manifest-path> <local-file>\n alkane-cli verify-sdk-release <SHA256SUMS> <archive>\n alkane-cli verify-running-build <ip> <user> <known-hosts> <board> <sdk-sha> <os-sha>".into()),
}
}
fn verify_sdk_release(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let mut verified = verify_sdk_release_archive(Path::new(&args[2]), Path::new(&args[3]))?;
if verified.record().family == "qemu-zynq-research" {
println!(
"verified checksum for SDK research archive {}; no board revision metadata is present",
verified.record().path.display()
);
return Ok(());
}
let info = inspect_sdk_release_archive(&mut verified)?;
println!(
"verified SDK release archive {} board={} sdk={} os={} artifacts={}",
verified.record().path.display(),
info.board,
info.sdk_revision,
info.os_revision,
info.artifact_count
);
Ok(())
}
fn verify_artifact(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let record = seed_manifest()?
.into_iter()
.find(|item| item.path == Path::new(&args[2]))
@@ -23,6 +55,30 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn verify_running_build(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let address: IpAddr = args[2].parse()?;
let expected_text = format!(
"board={}\nsdk_revision={}\nos_revision={}\n",
args[5], args[6], args[7]
);
let expected = parse_build_marker(expected_text.as_bytes())
.map_err(|error| io::Error::other(format!("invalid expected build: {error:?}")))?;
let target = SshTarget::new(address, 22, &args[3], Path::new(&args[4]))
.map_err(|error| io::Error::other(format!("SSH target: {error:?}")))?;
let raw = target
.probe(Probe::AlkaneBuildMarker)
.map_err(|error| io::Error::other(format!("running build read: {error:?}")))?;
let observed = parse_build_marker(&raw)
.map_err(|error| io::Error::other(format!("running build marker: {error:?}")))?;
verify_build_marker(&observed, &expected)
.map_err(|error| io::Error::other(format!("build comparison: {error:?}")))?;
println!(
"verified running build {} {} {}",
observed.board, observed.sdk_revision, observed.os_revision
);
Ok(())
}
fn main() {
if let Err(error) = run() {
eprintln!("artifact verification failed: {error}");