mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-15 08:30:02 +00:00
add initial scripts & strategy for image signing
- poc signing flow using hardware key is demonstrated - tested with signature verification using python script - beta key committed to tree (the "secret" key just contains the key identifier, not the key itself; the key resides in the token)
This commit is contained in:
parent
f2cd62dbbf
commit
fc3b226414
10 changed files with 1496 additions and 0 deletions
5
.gitignore
vendored
5
.gitignore
vendored
|
|
@ -84,3 +84,8 @@ share/python-wheels/
|
|||
*.egg
|
||||
*.pyc
|
||||
MANIFEST
|
||||
|
||||
# Deployment credentials
|
||||
signing/credentials
|
||||
# Signer target directory
|
||||
signing/fido-signer/target
|
||||
|
|
@ -143,6 +143,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]
|
||||
|
|
|
|||
28
signing/README.md
Normal file
28
signing/README.md
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# Image Signing and Deployment
|
||||
|
||||
The scripts in this directory are used for image signing and deployment.
|
||||
|
||||
The primary method for securing images is by signing them with a Precursor or Baochip device. There is a `beta` key, which is kept within such a device, but the device is regularly accessible for testing purposes. There is also at least one `deployment` key, which is kept in a similar device, but the device is kept in a physically secured location and deploying it requires some ceremony and effort.
|
||||
|
||||
Here is the flow for generating and deploying signatures:
|
||||
|
||||
## Preparation
|
||||
1. The "HSM" (as it may be -- really just a signing token) is a Precursor/Baochip device. The signature type is `ed25519`. The device is primed with a PIN like a normal FIDO device.
|
||||
1. A residential SSH key is created on the device using `ssh-keygen -t ed25519-sk`
|
||||
1. The "private key" resulting from this contains the credential ID, public key, relying party,
|
||||
|
||||
## Signing
|
||||
2. The image to be signed is fed into `fido-signer`:
|
||||
1. The signing token must be connected to the computer
|
||||
2. The PIN must be provided by the signer
|
||||
3. Depending on the host, this may need to run at an elevated privilege level (Windows in particular enforces that)
|
||||
3. Assuming the prequisites are met, `fido-signer` patches a unified signed Baochip image to inject the `signature` and `auth_data` into the designated key slot. It also generates a `.uf2` file for convenience.
|
||||
|
||||
In the case that a `deployment` key is used, additional physical security measures are invoked, a list of which are not publicly documented because in physical security, obscurity and the element of surprise are valid and useful countermeasures.
|
||||
|
||||
## Other notes
|
||||
|
||||
The `credentials` directory is in the `.gitignore` and should not be checked in. If you see a `credentials` directory in the tree, there was an operational security problem.
|
||||
|
||||
That being said, `credentials` does *not* store the actual private key used for signing. The main thing the directory contains is the PIN to unlock the signing token, which is a secondary security precaution.
|
||||
|
||||
1
signing/beta_ed25519_sk.pub
Normal file
1
signing/beta_ed25519_sk.pub
Normal file
|
|
@ -0,0 +1 @@
|
|||
sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIICXmSnt0E5AEktSyumuVLJL3/cqe4oATEEGW9FAIHinAAAABHNzaDo= bunnie@bunnie-desktop
|
||||
12
signing/beta_id_ed25519_sk
Normal file
12
signing/beta_id_ed25519_sk
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAASgAAABpzay1zc2
|
||||
gtZWQyNTUxOUBvcGVuc3NoLmNvbQAAACCAl5kp7dBOQBJLUsrprlSyS9/3KnuKAExBBlvR
|
||||
QCB4pwAAAARzc2g6AAABaBoLZaIaC2WiAAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY2
|
||||
9tAAAAIICXmSnt0E5AEktSyumuVLJL3/cqe4oATEEGW9FAIHinAAAABHNzaDoBAAAA8QEG
|
||||
YIv6BSgkDVszkhuxOE6+rvPkc3pestB+d4BbiMse1ur8ddQhyUH6jQniS0pM7JiF3XbA/a
|
||||
FmDE1ucuTzumu6wGjIdTJ7T029q4c2gOdSWCiE8beA0fyw3s1TAH56a1uMYYHqdPG1c95y
|
||||
mS0sB5ZfXIEIde0R80JDZosY65lCVoxXj3wD+r9uvcgZyUjZyWnvK7EmbNDRoNUuHDfjI2
|
||||
oHVuVBDzF+YiixCIXIM6qulKiJe+RvtnvUyMJrASEWLLBGFa74LGpub6drnF8DSj3aFQTN
|
||||
LgmdzB0D/7gr5Jf+lh96SthrfWzNcz+q/pRKhYsAAAAAAAAAFWJ1bm5pZUBidW5uaWUtZG
|
||||
Vza3RvcAECAw==
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
98
signing/extract_sk_credential.py
Normal file
98
signing/extract_sk_credential.py
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Extract FIDO/U2F credential id (key_handle) from an OpenSSH sk private key.
|
||||
|
||||
Usage:
|
||||
python3 extract_sk_credential.py /path/to/id_ed25519_sk
|
||||
cat /path/to/id_ed25519_sk | python3 extract_sk_credential.py -
|
||||
"""
|
||||
import sys, argparse, base64, struct
|
||||
from pathlib import Path
|
||||
|
||||
def read_u32(buf, off):
|
||||
if off+4 > len(buf):
|
||||
raise ValueError("unexpected end while reading u32")
|
||||
return struct.unpack(">I", buf[off:off+4])[0], off+4
|
||||
|
||||
def read_string(buf, off):
|
||||
l, off = read_u32(buf, off)
|
||||
if off + l > len(buf):
|
||||
raise ValueError("unexpected end while reading string")
|
||||
return buf[off:off+l], off + l
|
||||
|
||||
def read_byte(buf, off):
|
||||
if off >= len(buf):
|
||||
raise ValueError("unexpected end while reading byte")
|
||||
return buf[off], off+1
|
||||
|
||||
def extract_key_info(priv_blob):
|
||||
# priv_blob layout: two checkints, then for each key:
|
||||
# string keytype
|
||||
# string pubkey_blob
|
||||
# string privkey_blob
|
||||
off = 0
|
||||
_, off = read_u32(priv_blob, off)
|
||||
_, off = read_u32(priv_blob, off)
|
||||
key_type, off = read_string(priv_blob, off)
|
||||
print(f"Key type: {key_type.decode('utf-8')}")
|
||||
pubkey_blob, off = read_string(priv_blob, off)
|
||||
relying_party, off = read_string(priv_blob, off)
|
||||
print(f"Relying party: {relying_party.decode('utf-8')}")
|
||||
flags, off = read_byte(priv_blob, off)
|
||||
key_handle, off = read_string(priv_blob, off)
|
||||
return (pubkey_blob, key_handle)
|
||||
|
||||
def load_openssh_private(data_bytes):
|
||||
b = data_bytes.strip()
|
||||
if b.startswith(b"-----BEGIN OPENSSH PRIVATE KEY-----"):
|
||||
body = b.split(b"-----BEGIN OPENSSH PRIVATE KEY-----",1)[1]
|
||||
body = body.split(b"-----END OPENSSH PRIVATE KEY-----",1)[0]
|
||||
body = b"".join(body.splitlines())
|
||||
raw = base64.b64decode(body)
|
||||
else:
|
||||
# try base64 decode; if invalid, assume already binary openssh blob
|
||||
try:
|
||||
raw = base64.b64decode(b, validate=True)
|
||||
except Exception:
|
||||
raw = data_bytes
|
||||
return raw
|
||||
|
||||
def extract_from_file(path):
|
||||
data = sys.stdin.buffer.read() if path == "-" else open(path, "rb").read()
|
||||
raw = load_openssh_private(data)
|
||||
magic = b"openssh-key-v1\0"
|
||||
if not raw.startswith(magic):
|
||||
raise ValueError("not an openssh-key-v1 private key (magic mismatch)")
|
||||
off = len(magic)
|
||||
# string ciphername, string kdfname, string kdfoptions, uint32 nkeys
|
||||
_, off = read_string(raw, off)
|
||||
_, off = read_string(raw, off)
|
||||
_, off = read_string(raw, off)
|
||||
nkeys, off = read_u32(raw, off)
|
||||
for _ in range(nkeys):
|
||||
_, off = read_string(raw, off) # public key blob(s)
|
||||
priv_block, off = read_string(raw, off)
|
||||
return extract_key_info(priv_block)
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="Extract FIDO/U2F key_handle (credential id) from an OpenSSH sk private key")
|
||||
p.add_argument("infile", nargs="?", default="./testing_id_ed25519_sk", help="private key file (PEM or base64). Use '-' for stdin")
|
||||
args, _ = p.parse_known_args()
|
||||
infile = Path(args.infile)
|
||||
|
||||
try:
|
||||
(pubkey_blob, key_handle) = extract_from_file(infile)
|
||||
except Exception as e:
|
||||
sys.stderr.write("ERROR: " + str(e) + "\n")
|
||||
sys.exit(2)
|
||||
|
||||
name = infile.stem.upper()
|
||||
pubkey_formatted = ', '.join(f"0x{byte:02x}" for byte in pubkey_blob)
|
||||
print(f"pub const {name}_PUB: [u8; 32] = [{pubkey_formatted}];")
|
||||
print(f"pubkey base64: {base64.b64encode(pubkey_blob)}")
|
||||
key_handle_formatted = ', '.join(f"0x{byte:02x}" for byte in key_handle)
|
||||
print(f"pub const {name}_CRED_ID: [u8; 32] = [{key_handle_formatted}];")
|
||||
print(f"cred id base64: {base64.b64encode(key_handle)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
1158
signing/fido-signer/Cargo.lock
generated
Normal file
1158
signing/fido-signer/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
20
signing/fido-signer/Cargo.toml
Normal file
20
signing/fido-signer/Cargo.toml
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
[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"
|
||||
|
||||
# For Windows USB support
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.48", features = [
|
||||
"Win32_Devices_HumanInterfaceDevice",
|
||||
] }
|
||||
128
signing/fido-signer/src/main.rs
Normal file
128
signing/fido-signer/src/main.rs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
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 serde::{Deserialize, Serialize};
|
||||
|
||||
/// FIDO Signer - Sign messages or files using FIDO credentials
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "fido-signer")]
|
||||
#[command(author, version, about, long_about = None)]
|
||||
#[command(group(
|
||||
ArgGroup::new("input")
|
||||
.required(true)
|
||||
.args(["message", "file"])
|
||||
))]
|
||||
struct Args {
|
||||
/// Path to the credential file (JSON format)
|
||||
#[arg(short = 'c', long, value_name = "FILE")]
|
||||
credential_file: PathBuf,
|
||||
|
||||
/// Message to sign (base64 encoded)
|
||||
#[arg(short = 'm', long, value_name = "BASE64_MESSAGE", conflicts_with = "file")]
|
||||
message: Option<String>,
|
||||
|
||||
/// File to sign
|
||||
#[arg(short = 'f', long, value_name = "FILE", conflicts_with = "message")]
|
||||
file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct Credentials {
|
||||
credential_id: String, // Base64 encoded, will be decoded to Vec<u8>
|
||||
pin: String, // UTF-8 string
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("Ed25519 Signing with FIDO2 Token");
|
||||
println!("================================\n");
|
||||
|
||||
// Parse command line arguments
|
||||
let args = Args::parse();
|
||||
|
||||
// Load and parse the credential file
|
||||
let credential_data = fs::read_to_string(&args.credential_file)
|
||||
.map_err(|e| format!("Failed to read credential file: {}", e))?;
|
||||
|
||||
let credentials: Credentials = serde_json::from_str(&credential_data)
|
||||
.map_err(|e| format!("Failed to parse credential JSON: {}", e))?;
|
||||
|
||||
// Decode the credential_id from base64
|
||||
let credential_id: Vec<u8> = general_purpose::STANDARD
|
||||
.decode(&credentials.credential_id)
|
||||
.map_err(|e| format!("Failed to decode credential_id: {}", e))?;
|
||||
|
||||
// Get the PIN as a string (already UTF-8)
|
||||
let pin: String = credentials.pin;
|
||||
|
||||
// Determine what to sign
|
||||
let data_to_sign: Vec<u8> = if let Some(message_b64) = args.message {
|
||||
// Decode message from base64
|
||||
general_purpose::STANDARD
|
||||
.decode(&message_b64)
|
||||
.map_err(|e| format!("Failed to decode message: {}", e))?
|
||||
} else if let Some(file_path) = args.file {
|
||||
// Read file contents
|
||||
fs::read(&file_path).map_err(|e| format!("Failed to read file '{}': {}", file_path.display(), e))?
|
||||
} 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
|
||||
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::encode(r));
|
||||
println!(" S: {}", hex::encode(s));
|
||||
println!(" auth_data: {}", hex::encode(&assertion.auth_data));
|
||||
|
||||
println!(" signature: {}", general_purpose::STANDARD.encode(assertion.signature));
|
||||
println!(" auth_data: {}", general_purpose::STANDARD.encode(&assertion.auth_data));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Using the ctap-hid crate (Pure Rust, no C dependencies)
|
||||
// #[cfg(feature = "pure-rust")]
|
||||
fn sign_ed25519_hash(
|
||||
credential_id: &[u8],
|
||||
hash: &[u8],
|
||||
pin: &str,
|
||||
) -> Result<Assertion, Box<dyn std::error::Error>> {
|
||||
let cfg = Cfg::init();
|
||||
|
||||
let mut devices = ctap_hid_fido2::get_fidokey_devices();
|
||||
if devices.is_empty() {
|
||||
return Err("No FIDO2 devices found".into());
|
||||
}
|
||||
|
||||
let device = devices.pop().unwrap();
|
||||
let fidokey = FidoKeyHidFactory::create_by_params(&[device.param], &cfg).unwrap();
|
||||
// println!("Using key {:?}", fidokey.get_info().unwrap());
|
||||
|
||||
let assertion = GetAssertionArgsBuilder::new("ssh:", hash).pin(pin).credential_id(credential_id).build();
|
||||
match fidokey.get_assertion_with_args(&assertion) {
|
||||
Ok(mut a) => {
|
||||
println!("Key used {} times", a[0].sign_count);
|
||||
Ok(a.pop().unwrap())
|
||||
}
|
||||
Err(e) => Err(e.try_into().unwrap()),
|
||||
}
|
||||
}
|
||||
44
signing/test-verify.py
Normal file
44
signing/test-verify.py
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
#!/usr/bin/env python3
|
||||
import base64
|
||||
import hashlib
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from cryptography.hazmat.primitives.asymmetric import ed25519
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
|
||||
def verify_signature(file_path: Path, pubkey_b64: str, sig_b64: str, authdata_b64: str):
|
||||
pubkey = base64.b64decode(pubkey_b64)
|
||||
signature = base64.b64decode(sig_b64)
|
||||
authdata = base64.b64decode(authdata_b64)
|
||||
|
||||
client_data = file_path.read_bytes()
|
||||
client_data_hash = hashlib.sha256(client_data).digest()
|
||||
message = authdata + client_data_hash
|
||||
|
||||
public_key = ed25519.Ed25519PublicKey.from_public_bytes(pubkey)
|
||||
try:
|
||||
public_key.verify(signature, message)
|
||||
print("Signature is valid.")
|
||||
except InvalidSignature:
|
||||
print("Signature is INVALID.")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Verify FIDO2 Ed25519-SK signature for a given clientDataJSON file."
|
||||
)
|
||||
parser.add_argument("file", type=Path, help="Path to clientDataJSON file")
|
||||
parser.add_argument("pubkey_b64", help="Base64-encoded 32-byte Ed25519 public key")
|
||||
parser.add_argument("sig_b64", help="Base64-encoded 64-byte signature")
|
||||
parser.add_argument("authdata_b64", help="Base64-encoded 37-byte authenticator data")
|
||||
|
||||
args = parser.parse_args()
|
||||
verify_signature(args.file, args.pubkey_b64, args.sig_b64, args.authdata_b64)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
# test data is 64 bytes of 0, signed with beta-key
|
||||
#
|
||||
# pubkey gJeZKe3QTkASS1LK6a5Uskvf9yp7igBMQQZb0UAgeKc=
|
||||
# authdata 4wYQ6KFiEVlg/h7CI+ZSnJ9LboAgDcteXDIcivHisb8FAAACDw==
|
||||
# signature uYiL6JV0h4LcZ95F3i4o09Lf29zI7PAM11LGfIolkOiJooeOUDm2tOIk2u/OuaiZgN62UZ4a6coNSwZkV9UxCg==
|
||||
Loading…
Reference in a new issue