feat: persist opaque device anchors

This commit is contained in:
Kevin Yue committed 2026-09-29 20:42:27 +08:00
1 parent ba1a70f3ce
commit 91c480c274
6 files changed
+337 -31

No files matched your search

Generated
+2 -1
View File
@@ -1850,7 +1850,6 @@ dependencies = [
"humantime", "humantime",
"log", "log",
"log-reload", "log-reload",
"mac_address",
"md5", "md5",
"netdev", "netdev",
"openssl", "openssl",
@@ -1976,9 +1975,11 @@ dependencies = [
"compile-time", "compile-time",
"env_logger", "env_logger",
"futures", "futures",
"getrandom 0.4.3",
"gpapi", "gpapi",
"gphip", "gphip",
"log", "log",
"mac_address",
"nix 0.31.3", "nix 0.31.3",
"openconnect", "openconnect",
"serde", "serde",
+2
View File
@@ -28,6 +28,8 @@ thiserror.workspace = true
uuid = { workspace = true, features = ["v4"] } uuid = { workspace = true, features = ["v4"] }
zeroize.workspace = true zeroize.workspace = true
tempfile.workspace = true tempfile.workspace = true
getrandom = "0.4"
mac_address = "1"
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
nix = { version = "0.31", features = ["fs", "socket", "user"] } nix = { version = "0.31", features = ["fs", "socket", "user"] }
+246 -5
View File
@@ -17,8 +17,28 @@ struct Record {
} }
pub fn resolve() -> anyhow::Result<DeviceAnchor> { pub fn resolve() -> anyhow::Result<DeviceAnchor> {
resolve_in(Path::new("/var/lib/gp"), 0, gpapi::device_anchor::collect_unix) resolve_in(Path::new("/var/lib/gp"), 0, collect_unix).context("cannot resolve persistent GUI device anchor")
.context("cannot resolve persistent GUI device anchor") }
fn collect_unix() -> anyhow::Result<DeviceAnchor> {
collect_from(mac_address::get_mac_address()?, || {
let mut random = [0_u8; 32];
getrandom::fill(&mut random).map_err(|_| anyhow::anyhow!("cannot initialize device anchor"))?;
Ok(random)
})
}
fn collect_from(
mac: Option<mac_address::MacAddress>,
random: impl FnOnce() -> anyhow::Result<[u8; 32]>,
) -> anyhow::Result<DeviceAnchor> {
if let Some(mac) = mac {
let bytes = mac.bytes();
if bytes != [0; 6] && bytes[0] & 1 == 0 {
return Ok(DeviceAnchor::derive(AnchorSource::UnixMac, bytes));
}
}
Ok(DeviceAnchor::derive(AnchorSource::UnixRandom, random()?))
} }
fn validate_metadata(metadata: &fs::Metadata, owner: u32, directory: bool) -> anyhow::Result<()> { fn validate_metadata(metadata: &fs::Metadata, owner: u32, directory: bool) -> anyhow::Result<()> {
@@ -61,7 +81,7 @@ fn read_record(path: &Path, owner: u32) -> anyhow::Result<Option<DeviceAnchor>>
"unsupported or invalid device anchor record" "unsupported or invalid device anchor record"
); );
ensure!( ensure!(
matches!(record.anchor.source, AnchorSource::LinuxMac | AnchorSource::LinuxRandom), matches!(record.anchor.source, AnchorSource::UnixMac | AnchorSource::UnixRandom),
"invalid Unix device anchor source" "invalid Unix device anchor source"
); );
Ok(Some(record.anchor)) Ok(Some(record.anchor))
@@ -98,7 +118,7 @@ fn resolve_in(
} }
let anchor = collect()?; let anchor = collect()?;
ensure!( ensure!(
anchor.validate() && matches!(anchor.source, AnchorSource::LinuxMac | AnchorSource::LinuxRandom), anchor.validate() && matches!(anchor.source, AnchorSource::UnixMac | AnchorSource::UnixRandom),
"invalid collected Unix device anchor" "invalid collected Unix device anchor"
); );
let mut temporary = tempfile::NamedTempFile::new_in(directory)?; let mut temporary = tempfile::NamedTempFile::new_in(directory)?;
@@ -120,7 +140,7 @@ mod tests {
fn anchor() -> anyhow::Result<DeviceAnchor> { fn anchor() -> anyhow::Result<DeviceAnchor> {
Ok(DeviceAnchor { Ok(DeviceAnchor {
hardware_id: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_owned(), hardware_id: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_owned(),
source: AnchorSource::LinuxMac, source: AnchorSource::UnixMac,
}) })
} }
@@ -136,4 +156,225 @@ mod tests {
anchor().unwrap() anchor().unwrap()
); );
} }
#[test]
fn collector_preserves_an_eligible_mac_and_randomizes_ineligible_addresses() {
use mac_address::MacAddress;
let eligible = collect_from(Some(MacAddress::new([0, 17, 34, 51, 68, 85])), || {
anyhow::bail!("must not randomize")
})
.unwrap();
assert_eq!(
eligible,
DeviceAnchor::derive(AnchorSource::UnixMac, [0, 17, 34, 51, 68, 85])
);
for rejected in [[0; 6], [1, 2, 3, 4, 5, 6], [0xff; 6]] {
assert_eq!(
collect_from(Some(MacAddress::new(rejected)), || Ok([9; 32])).unwrap(),
DeviceAnchor::derive(AnchorSource::UnixRandom, [9; 32])
);
}
assert_eq!(
collect_from(None, || Ok([8; 32])).unwrap(),
DeviceAnchor::derive(AnchorSource::UnixRandom, [8; 32])
);
}
#[test]
fn deleting_the_record_recreates_the_same_mac_anchor() {
let temporary = tempfile::tempdir().unwrap();
let path = temporary.path().join("state");
let owner = nix::unistd::Uid::current().as_raw();
let first = resolve_in(&path, owner, anchor).unwrap();
fs::remove_file(path.join("hardware-id")).unwrap();
assert_eq!(resolve_in(&path, owner, anchor).unwrap(), first);
}
#[test]
fn parallel_first_start_converges_on_one_record() {
use std::sync::{Arc, Barrier};
let temporary = tempfile::tempdir().unwrap();
let path = Arc::new(temporary.path().join("state"));
fs::create_dir(&*path).unwrap();
fs::set_permissions(&*path, fs::Permissions::from_mode(0o700)).unwrap();
let owner = nix::unistd::Uid::current().as_raw();
let barrier = Arc::new(Barrier::new(2));
let handles: Vec<_> = [AnchorSource::UnixMac, AnchorSource::UnixRandom]
.into_iter()
.map(|source| {
let path = Arc::clone(&path);
let barrier = Arc::clone(&barrier);
std::thread::spawn(move || {
barrier.wait();
resolve_in(&path, owner, || Ok(DeviceAnchor::derive(source, [source.into()])))
})
})
.collect();
let results: Vec<_> = handles
.into_iter()
.map(|handle| handle.join().unwrap().unwrap())
.collect();
assert_eq!(results[0], results[1]);
assert_eq!(
read_record(&path.join("hardware-id"), owner).unwrap(),
Some(results[0].clone())
);
}
#[test]
fn rejects_malformed_linked_and_unsafe_records() {
use std::os::unix::fs::symlink;
let owner = nix::unistd::Uid::current().as_raw();
for case in ["malformed", "symlink", "hard-link", "permissions"] {
let temporary = tempfile::tempdir().unwrap();
let directory = temporary.path().join("state");
fs::create_dir(&directory).unwrap();
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
let record = directory.join("hardware-id");
match case {
"malformed" => fs::write(&record, b"not-json").unwrap(),
"symlink" => {
let target = temporary.path().join("target");
fs::write(
&target,
serde_json::to_vec(&Record {
version: 1,
anchor: anchor().unwrap(),
})
.unwrap(),
)
.unwrap();
symlink(target, &record).unwrap();
}
"hard-link" => {
fs::write(
&record,
serde_json::to_vec(&Record {
version: 1,
anchor: anchor().unwrap(),
})
.unwrap(),
)
.unwrap();
fs::hard_link(&record, temporary.path().join("second-link")).unwrap();
}
"permissions" => {
fs::write(
&record,
serde_json::to_vec(&Record {
version: 1,
anchor: anchor().unwrap(),
})
.unwrap(),
)
.unwrap();
fs::set_permissions(&record, fs::Permissions::from_mode(0o644)).unwrap();
}
_ => unreachable!(),
}
if case != "symlink" && case != "permissions" {
fs::set_permissions(&record, fs::Permissions::from_mode(0o600)).unwrap();
}
assert!(resolve_in(&directory, owner, anchor).is_err(), "accepted {case}");
}
}
#[test]
fn recovers_with_an_interrupted_temporary_file_present() {
let temporary = tempfile::tempdir().unwrap();
let directory = temporary.path().join("state");
fs::create_dir(&directory).unwrap();
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
fs::write(directory.join(".hardware-id.interrupted"), b"partial").unwrap();
assert_eq!(
resolve_in(&directory, nix::unistd::Uid::current().as_raw(), anchor).unwrap(),
anchor().unwrap()
);
}
#[test]
fn rejects_unsafe_directory_and_lock_metadata_and_read_only_storage() {
use std::os::unix::fs::symlink;
let owner = nix::unistd::Uid::current().as_raw();
let temporary = tempfile::tempdir().unwrap();
let directory = temporary.path().join("state");
fs::create_dir(&directory).unwrap();
fs::set_permissions(&directory, fs::Permissions::from_mode(0o755)).unwrap();
assert!(resolve_in(&directory, owner, anchor).is_err());
let temporary = tempfile::tempdir().unwrap();
let directory = temporary.path().join("state");
fs::create_dir(&directory).unwrap();
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
assert!(resolve_in(&directory, owner.wrapping_add(1), anchor).is_err());
let temporary = tempfile::tempdir().unwrap();
let directory = temporary.path().join("state");
fs::write(&directory, b"not-a-directory").unwrap();
assert!(resolve_in(&directory, owner, anchor).is_err());
for case in ["symlink", "hard-link", "permissions"] {
let temporary = tempfile::tempdir().unwrap();
let directory = temporary.path().join("state");
fs::create_dir(&directory).unwrap();
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
let lock = directory.join("hardware-id.lock");
match case {
"symlink" => {
let target = temporary.path().join("target");
fs::write(&target, b"").unwrap();
symlink(target, &lock).unwrap();
}
"hard-link" => {
fs::write(&lock, b"").unwrap();
fs::set_permissions(&lock, fs::Permissions::from_mode(0o600)).unwrap();
fs::hard_link(&lock, temporary.path().join("second-link")).unwrap();
}
"permissions" => {
fs::write(&lock, b"").unwrap();
fs::set_permissions(&lock, fs::Permissions::from_mode(0o644)).unwrap();
}
_ => unreachable!(),
}
assert!(resolve_in(&directory, owner, anchor).is_err(), "accepted {case} lock");
}
let temporary = tempfile::tempdir().unwrap();
let directory = temporary.path().join("state");
fs::create_dir(&directory).unwrap();
fs::set_permissions(&directory, fs::Permissions::from_mode(0o500)).unwrap();
assert!(resolve_in(&directory, owner, anchor).is_err());
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
}
#[test]
fn record_serializes_source_as_a_number_and_rejects_unknown_codes() {
let record = Record {
version: 1,
anchor: anchor().unwrap(),
};
let json = serde_json::to_value(&record).unwrap();
assert_eq!(json["anchor"]["source"], 1);
assert_eq!(
serde_json::to_string(&record).unwrap(),
r#"{"version":1,"anchor":{"hardware_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","source":1}}"#
);
for source in [0, 4] {
let json = serde_json::json!({
"version": 1,
"anchor": {
"hardware_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
"source": source
}
});
assert!(serde_json::from_value::<Record>(json).is_err());
}
}
} }
-1
View File
@@ -9,7 +9,6 @@ license = "MIT"
common = { path = "../common" } common = { path = "../common" }
anyhow.workspace = true anyhow.workspace = true
base64.workspace = true base64.workspace = true
mac_address = "1"
dns-lookup.workspace = true dns-lookup.workspace = true
log.workspace = true log.workspace = true
reqwest.workspace = true reqwest.workspace = true
+63 -22
View File
@@ -1,15 +1,50 @@
//! Neutral device-anchor transport model and Linux collection. //! Neutral device-anchor transport model and deterministic derivation.
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(try_from = "u8", into = "u8")]
pub enum AnchorSource { pub enum AnchorSource {
LinuxMac, UnixMac,
LinuxRandom, UnixRandom,
MacosIokit, MacosIokit,
} }
impl From<AnchorSource> for u8 {
fn from(source: AnchorSource) -> Self {
match source {
AnchorSource::UnixMac => 1,
AnchorSource::UnixRandom => 2,
AnchorSource::MacosIokit => 3,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidAnchorSource(u8);
impl fmt::Display for InvalidAnchorSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "unsupported device anchor source {}", self.0)
}
}
impl std::error::Error for InvalidAnchorSource {}
impl TryFrom<u8> for AnchorSource {
type Error = InvalidAnchorSource;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
1 => Ok(Self::UnixMac),
2 => Ok(Self::UnixRandom),
3 => Ok(Self::MacosIokit),
value => Err(InvalidAnchorSource(value)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct DeviceAnchor { pub struct DeviceAnchor {
@@ -26,8 +61,8 @@ impl DeviceAnchor {
pub fn derive(source: AnchorSource, seed: impl AsRef<[u8]>) -> Self { pub fn derive(source: AnchorSource, seed: impl AsRef<[u8]>) -> Self {
let domain = match source { let domain = match source {
AnchorSource::LinuxMac => b"gp-device-anchor:v1:linux-mac:".as_slice(), AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
AnchorSource::LinuxRandom => b"gp-device-anchor:v1:linux-random:".as_slice(), AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".as_slice(),
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(), AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
}; };
let mut input = domain.to_vec(); let mut input = domain.to_vec();
@@ -39,30 +74,36 @@ impl DeviceAnchor {
} }
} }
#[cfg(unix)]
pub fn collect_unix() -> anyhow::Result<DeviceAnchor> {
if let Some(mac) = mac_address::get_mac_address()? {
let bytes = mac.bytes();
if bytes != [0; 6] && bytes[0] & 1 == 0 {
return Ok(DeviceAnchor::derive(AnchorSource::LinuxMac, bytes));
}
}
let mut random = [0_u8; 32];
getrandom::fill(&mut random).map_err(|_| anyhow::anyhow!("cannot initialize device anchor"))?;
Ok(DeviceAnchor::derive(AnchorSource::LinuxRandom, random))
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test] #[test]
fn hashes_are_domain_separated_and_canonical() { fn hashes_original_seed_order_with_stable_domain_separation() {
let mac = DeviceAnchor::derive(AnchorSource::LinuxMac, [0, 17, 34, 51, 68, 85]); let mac = DeviceAnchor::derive(AnchorSource::UnixMac, [0, 17, 34, 51, 68, 85]);
assert!(mac.validate()); assert!(mac.validate());
assert_eq!(mac.hardware_id, "UWDOx4AVJEuCAYfJBaPioyGtRfAkJBhMYSi8LuFsE1A");
assert_ne!( assert_ne!(
mac.hardware_id, mac.hardware_id,
DeviceAnchor::derive(AnchorSource::LinuxRandom, [0, 17, 34, 51, 68, 85]).hardware_id DeviceAnchor::derive(AnchorSource::UnixMac, [85, 68, 51, 34, 17, 0]).hardware_id
);
assert_ne!(
mac.hardware_id,
DeviceAnchor::derive(AnchorSource::UnixRandom, [0, 17, 34, 51, 68, 85]).hardware_id
); );
} }
#[test]
fn source_uses_stable_numeric_json_codes() {
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1");
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3");
assert_eq!(
serde_json::from_str::<AnchorSource>("1").unwrap(),
AnchorSource::UnixMac
);
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
}
} }
@@ -189,13 +189,35 @@ mod tests {
fn credential_round_trips_a_validated_device_anchor() { fn credential_round_trips_a_validated_device_anchor() {
let anchor = DeviceAnchor { let anchor = DeviceAnchor {
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]), hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
source: crate::device_anchor::AnchorSource::LinuxMac, source: crate::device_anchor::AnchorSource::UnixMac,
}; };
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5") let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
.unwrap() .unwrap()
.with_device_anchor(anchor.clone()) .with_device_anchor(anchor.clone())
.unwrap(); .unwrap();
let decoded = SessionCredential::decode_frame(&credential.encode_frame().unwrap()).unwrap(); let frame = credential.encode_frame().unwrap();
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
assert_eq!(payload["device_anchor"]["source"], 1);
let decoded = SessionCredential::decode_frame(&frame).unwrap();
assert_eq!(decoded.device_anchor(), Some(&anchor)); assert_eq!(decoded.device_anchor(), Some(&anchor));
} }
#[test]
fn credential_rejects_reserved_and_unknown_anchor_sources() {
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5").unwrap();
let frame = credential.encode_frame().unwrap();
let mut payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
let hardware_id = general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]);
for source in [0, 4] {
payload["device_anchor"] = serde_json::json!({
"hardware_id": hardware_id,
"source": source
});
let bytes = serde_json::to_vec(&payload).unwrap();
let mut invalid_frame = (bytes.len() as u16).to_be_bytes().to_vec();
invalid_frame.extend_from_slice(&bytes);
assert!(SessionCredential::decode_frame(&invalid_frame).is_err());
}
}
} }