mirror of
https://github.com/rustdesk/hbb_common.git
synced 2026-11-28 16:54:14 +00:00
Merge pull request #619 from fufesou/fix/trusted-device-v2
Add trusted-device storage with atomic legacy migration
This commit is contained in:
1 file changed
+180
-82
+180
-82
@@ -10,7 +10,6 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use bytes::Bytes;
|
|
||||||
use rand::Rng;
|
use rand::Rng;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use serde as de;
|
use serde as de;
|
||||||
@@ -51,6 +50,7 @@ pub const READ_TIMEOUT: u64 = 18_000;
|
|||||||
pub const REG_INTERVAL: i64 = 15_000;
|
pub const REG_INTERVAL: i64 = 15_000;
|
||||||
pub const COMPRESS_LEVEL: i32 = 3;
|
pub const COMPRESS_LEVEL: i32 = 3;
|
||||||
const SERIAL: i32 = 3;
|
const SERIAL: i32 = 3;
|
||||||
|
const CONFIG_STORE_LOG_INTERVAL: Duration = Duration::from_secs(30);
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
lazy_static::lazy_static! {
|
lazy_static::lazy_static! {
|
||||||
@@ -65,7 +65,6 @@ lazy_static::lazy_static! {
|
|||||||
static ref CONFIG2: RwLock<Config2> = RwLock::new(Config2::load());
|
static ref CONFIG2: RwLock<Config2> = RwLock::new(Config2::load());
|
||||||
static ref LOCAL_CONFIG: RwLock<LocalConfig> = RwLock::new(LocalConfig::load());
|
static ref LOCAL_CONFIG: RwLock<LocalConfig> = RwLock::new(LocalConfig::load());
|
||||||
static ref STATUS: RwLock<Status> = RwLock::new(Status::load());
|
static ref STATUS: RwLock<Status> = RwLock::new(Status::load());
|
||||||
static ref TRUSTED_DEVICES: RwLock<(Vec<TrustedDevice>, bool)> = Default::default();
|
|
||||||
static ref ONLINE: Mutex<HashMap<String, i64>> = Default::default();
|
static ref ONLINE: Mutex<HashMap<String, i64>> = Default::default();
|
||||||
pub static ref PROD_RENDEZVOUS_SERVER: RwLock<String> = RwLock::new("".to_owned());
|
pub static ref PROD_RENDEZVOUS_SERVER: RwLock<String> = RwLock::new("".to_owned());
|
||||||
pub static ref EXE_RENDEZVOUS_SERVER: RwLock<String> = Default::default();
|
pub static ref EXE_RENDEZVOUS_SERVER: RwLock<String> = Default::default();
|
||||||
@@ -246,8 +245,15 @@ pub struct Config2 {
|
|||||||
serial: i32,
|
serial: i32,
|
||||||
#[serde(default, deserialize_with = "deserialize_string")]
|
#[serde(default, deserialize_with = "deserialize_string")]
|
||||||
unlock_pin: String,
|
unlock_pin: String,
|
||||||
#[serde(default, deserialize_with = "deserialize_string")]
|
// Imported by clients that support legacy trusted-device compatibility.
|
||||||
|
#[serde(
|
||||||
|
default,
|
||||||
|
deserialize_with = "deserialize_string",
|
||||||
|
skip_serializing_if = "String::is_empty"
|
||||||
|
)]
|
||||||
trusted_devices: String,
|
trusted_devices: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
trusted_devices_v2: Option<toml::Value>,
|
||||||
|
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
socks: Option<Socks5Server>,
|
socks: Option<Socks5Server>,
|
||||||
@@ -267,6 +273,8 @@ pub struct Resolution {
|
|||||||
pub struct PeerConfig {
|
pub struct PeerConfig {
|
||||||
#[serde(default, deserialize_with = "deserialize_vec_u8")]
|
#[serde(default, deserialize_with = "deserialize_vec_u8")]
|
||||||
pub password: Vec<u8>,
|
pub password: Vec<u8>,
|
||||||
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
|
pub trusted_device_v2: String,
|
||||||
#[serde(default, deserialize_with = "deserialize_size")]
|
#[serde(default, deserialize_with = "deserialize_size")]
|
||||||
pub size: Size,
|
pub size: Size,
|
||||||
#[serde(default, deserialize_with = "deserialize_size")]
|
#[serde(default, deserialize_with = "deserialize_size")]
|
||||||
@@ -394,6 +402,7 @@ impl Default for PeerConfig {
|
|||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
password: Default::default(),
|
password: Default::default(),
|
||||||
|
trusted_device_v2: Default::default(),
|
||||||
size: Default::default(),
|
size: Default::default(),
|
||||||
size_ft: Default::default(),
|
size_ft: Default::default(),
|
||||||
size_pf: Default::default(),
|
size_pf: Default::default(),
|
||||||
@@ -513,7 +522,31 @@ impl Config2 {
|
|||||||
|
|
||||||
fn store(&self) {
|
fn store(&self) {
|
||||||
let mut config = self.clone();
|
let mut config = self.clone();
|
||||||
let stored = Config::load_::<Config2>("2");
|
let stored = match try_load_path_for_store::<Self>(Self::file()) {
|
||||||
|
Ok(mut stored) => {
|
||||||
|
if stored.trusted_devices_v2().is_err() {
|
||||||
|
crate::throttled_log!(
|
||||||
|
CONFIG_STORE_LOG_INTERVAL,
|
||||||
|
warn,
|
||||||
|
"Invalid trusted-device grants field; saving settings without V2 trust credentials"
|
||||||
|
);
|
||||||
|
stored.trusted_devices_v2 = None;
|
||||||
|
}
|
||||||
|
stored
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
crate::throttled_log!(
|
||||||
|
CONFIG_STORE_LOG_INTERVAL,
|
||||||
|
error,
|
||||||
|
"Failed to read config2; skipping save: {}",
|
||||||
|
err
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Ordinary settings must not restore grants from a stale snapshot.
|
||||||
|
config.trusted_devices_v2 = stored.trusted_devices_v2;
|
||||||
|
config.trusted_devices = stored.trusted_devices;
|
||||||
if let Some(mut socks) = config.socks {
|
if let Some(mut socks) = config.socks {
|
||||||
let stored_password = stored
|
let stored_password = stored
|
||||||
.socks
|
.socks
|
||||||
@@ -529,6 +562,71 @@ impl Config2 {
|
|||||||
Config::store_(&config, "2");
|
Config::store_(&config, "2");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn get_trusted_devices_v2() -> crate::ResultType<String> {
|
||||||
|
Self::get_trusted_device_stores().map(|(current, _)| current)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_trusted_device_stores() -> crate::ResultType<(String, String)> {
|
||||||
|
let _lock = CONFIG2.read().unwrap();
|
||||||
|
let config: Self = try_load_path(Self::file())?;
|
||||||
|
Ok((config.trusted_devices_v2()?.to_owned(), config.trusted_devices))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn has_trusted_devices_v2() -> crate::ResultType<bool> {
|
||||||
|
let _lock = CONFIG2.read().unwrap();
|
||||||
|
let config: Self = try_load_path(Self::file())?;
|
||||||
|
// Explicit revocation must also replace malformed grant fields.
|
||||||
|
Ok(config
|
||||||
|
.trusted_devices_v2
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|value| value.as_str() != Some("")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trusted_devices_v2(&self) -> crate::ResultType<&str> {
|
||||||
|
match &self.trusted_devices_v2 {
|
||||||
|
None => Ok(""),
|
||||||
|
Some(toml::Value::String(value)) => Ok(value),
|
||||||
|
Some(_) => Err(anyhow!("Invalid trusted-device grants field")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_trusted_devices_v2(value: String) -> crate::ResultType<()> {
|
||||||
|
Self {
|
||||||
|
trusted_devices_v2: (!value.is_empty()).then(|| toml::Value::String(value)),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.sync_trusted_devices()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sync_trusted_devices(&self) -> crate::ResultType<()> {
|
||||||
|
self.trusted_devices_v2()?;
|
||||||
|
let mut current = CONFIG2.write().unwrap();
|
||||||
|
let mut stored: Self = try_load_path(Self::file())?;
|
||||||
|
if stored.trusted_devices != self.trusted_devices
|
||||||
|
|| stored.trusted_devices_v2 != self.trusted_devices_v2
|
||||||
|
{
|
||||||
|
stored.trusted_devices.clone_from(&self.trusted_devices);
|
||||||
|
stored
|
||||||
|
.trusted_devices_v2
|
||||||
|
.clone_from(&self.trusted_devices_v2);
|
||||||
|
store_path(Self::file(), &stored)?;
|
||||||
|
}
|
||||||
|
current.trusted_devices = stored.trusted_devices;
|
||||||
|
current.trusted_devices_v2 = stored.trusted_devices_v2;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_for_sync() -> crate::ResultType<Self> {
|
||||||
|
let current = CONFIG2.read().unwrap();
|
||||||
|
// The login-screen server can share this file with the system service.
|
||||||
|
let stored: Self = try_load_path(Self::file())?;
|
||||||
|
Ok(Self {
|
||||||
|
trusted_devices: stored.trusted_devices,
|
||||||
|
trusted_devices_v2: stored.trusted_devices_v2,
|
||||||
|
..current.clone()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get() -> Config2 {
|
pub fn get() -> Config2 {
|
||||||
return CONFIG2.read().unwrap().clone();
|
return CONFIG2.read().unwrap().clone();
|
||||||
}
|
}
|
||||||
@@ -552,6 +650,47 @@ fn keep_encrypted_storage_if_plaintext_unchanged(plain: &str, stored: &str) -> S
|
|||||||
encrypt_str_or_original(plain, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN)
|
encrypt_str_or_original(plain, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn try_load_path<T: serde::Serialize + serde::de::DeserializeOwned + Default>(
|
||||||
|
path: PathBuf,
|
||||||
|
) -> crate::ResultType<T> {
|
||||||
|
match confy::load_path(path) {
|
||||||
|
Ok(config) => Ok(config),
|
||||||
|
Err(confy::ConfyError::GeneralLoadError(error))
|
||||||
|
if error.kind() == std::io::ErrorKind::NotFound =>
|
||||||
|
{
|
||||||
|
Ok(T::default())
|
||||||
|
}
|
||||||
|
Err(confy::ConfyError::BadTomlData(_)) => Err(anyhow!("Invalid configuration file")),
|
||||||
|
Err(error) => Err(error.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_load_path_for_store<T: serde::Serialize + serde::de::DeserializeOwned + Default>(
|
||||||
|
path: PathBuf,
|
||||||
|
) -> crate::ResultType<T> {
|
||||||
|
match confy::load_path(path) {
|
||||||
|
Ok(config) => Ok(config),
|
||||||
|
Err(error)
|
||||||
|
if matches!(&error, confy::ConfyError::BadTomlData(_))
|
||||||
|
|| matches!(&error, confy::ConfyError::ReadConfigurationFileError(error)
|
||||||
|
if error.kind() == std::io::ErrorKind::InvalidData) =>
|
||||||
|
{
|
||||||
|
crate::throttled_log!(
|
||||||
|
CONFIG_STORE_LOG_INTERVAL,
|
||||||
|
warn,
|
||||||
|
"Invalid configuration file; saving settings without trust credentials"
|
||||||
|
);
|
||||||
|
Ok(T::default())
|
||||||
|
}
|
||||||
|
Err(confy::ConfyError::GeneralLoadError(error))
|
||||||
|
if error.kind() == std::io::ErrorKind::NotFound =>
|
||||||
|
{
|
||||||
|
Ok(T::default())
|
||||||
|
}
|
||||||
|
Err(error) => Err(error.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn load_path<T: serde::Serialize + serde::de::DeserializeOwned + Default + std::fmt::Debug>(
|
pub fn load_path<T: serde::Serialize + serde::de::DeserializeOwned + Default + std::fmt::Debug>(
|
||||||
file: PathBuf,
|
file: PathBuf,
|
||||||
) -> T {
|
) -> T {
|
||||||
@@ -1315,7 +1454,6 @@ impl Config {
|
|||||||
}
|
}
|
||||||
config.password = stored;
|
config.password = stored;
|
||||||
config.store();
|
config.store();
|
||||||
Self::clear_trusted_devices();
|
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1351,7 +1489,6 @@ impl Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
config.store();
|
config.store();
|
||||||
Self::clear_trusted_devices();
|
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1589,70 +1726,10 @@ impl Config {
|
|||||||
config.store();
|
config.store();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_trusted_devices_json() -> String {
|
|
||||||
serde_json::to_string(&Self::get_trusted_devices()).unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_trusted_devices() -> Vec<TrustedDevice> {
|
|
||||||
let (devices, synced) = TRUSTED_DEVICES.read().unwrap().clone();
|
|
||||||
if synced {
|
|
||||||
return devices;
|
|
||||||
}
|
|
||||||
let devices = CONFIG2.read().unwrap().trusted_devices.clone();
|
|
||||||
let (devices, succ, store) = decrypt_str_or_original(&devices, PASSWORD_ENC_VERSION);
|
|
||||||
if succ {
|
|
||||||
let mut devices: Vec<TrustedDevice> =
|
|
||||||
serde_json::from_str(&devices).unwrap_or_default();
|
|
||||||
let len = devices.len();
|
|
||||||
devices.retain(|d| !d.outdate());
|
|
||||||
if store || devices.len() != len {
|
|
||||||
Self::set_trusted_devices(devices.clone());
|
|
||||||
}
|
|
||||||
*TRUSTED_DEVICES.write().unwrap() = (devices.clone(), true);
|
|
||||||
devices
|
|
||||||
} else {
|
|
||||||
Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_trusted_devices(mut trusted_devices: Vec<TrustedDevice>) {
|
|
||||||
trusted_devices.retain(|d| !d.outdate());
|
|
||||||
let devices = serde_json::to_string(&trusted_devices).unwrap_or_default();
|
|
||||||
let max_len = 1024 * 1024;
|
|
||||||
if devices.bytes().len() > max_len {
|
|
||||||
log::error!("Trusted devices too large: {}", devices.bytes().len());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let devices = encrypt_str_or_original(&devices, PASSWORD_ENC_VERSION, max_len);
|
|
||||||
let mut config = CONFIG2.write().unwrap();
|
|
||||||
config.trusted_devices = devices;
|
|
||||||
config.store();
|
|
||||||
*TRUSTED_DEVICES.write().unwrap() = (trusted_devices, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn add_trusted_device(device: TrustedDevice) {
|
|
||||||
let mut devices = Self::get_trusted_devices();
|
|
||||||
devices.retain(|d| d.hwid != device.hwid);
|
|
||||||
devices.push(device);
|
|
||||||
Self::set_trusted_devices(devices);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove_trusted_devices(hwids: &Vec<Bytes>) {
|
|
||||||
let mut devices = Self::get_trusted_devices();
|
|
||||||
devices.retain(|d| !hwids.contains(&d.hwid));
|
|
||||||
Self::set_trusted_devices(devices);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clear_trusted_devices() {
|
|
||||||
Self::set_trusted_devices(Default::default());
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get() -> Config {
|
pub fn get() -> Config {
|
||||||
return CONFIG.read().unwrap().clone();
|
return CONFIG.read().unwrap().clone();
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: `Config::set()` does not invalidate trusted devices when permanent password/salt changes.
|
|
||||||
// This matches historical behavior, but may need revisiting in a separate PR.
|
|
||||||
pub fn set(cfg: Config) -> bool {
|
pub fn set(cfg: Config) -> bool {
|
||||||
let mut lock = CONFIG.write().unwrap();
|
let mut lock = CONFIG.write().unwrap();
|
||||||
if *lock == cfg {
|
if *lock == cfg {
|
||||||
@@ -1697,6 +1774,7 @@ impl Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const PEERS: &str = "peers";
|
const PEERS: &str = "peers";
|
||||||
|
static PEER_CONFIG_WRITE_LOCK: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
impl PeerConfig {
|
impl PeerConfig {
|
||||||
pub fn load(id: &str) -> PeerConfig {
|
pub fn load(id: &str) -> PeerConfig {
|
||||||
@@ -1720,6 +1798,8 @@ impl PeerConfig {
|
|||||||
if store {
|
if store {
|
||||||
config.store_(id);
|
config.store_(id);
|
||||||
}
|
}
|
||||||
|
// Credentials must not reach general-purpose peer settings or UI data.
|
||||||
|
config.trusted_device_v2.clear();
|
||||||
config
|
config
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
@@ -1748,13 +1828,47 @@ impl PeerConfig {
|
|||||||
*v = encrypt_str_or_original(v, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN)
|
*v = encrypt_str_or_original(v, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap();
|
||||||
|
// A stale settings snapshot must not overwrite a newly issued credential.
|
||||||
|
config.trusted_device_v2 = match try_load_path_for_store::<Self>(Self::path(id)) {
|
||||||
|
Ok(stored) => stored.trusted_device_v2,
|
||||||
|
Err(err) => {
|
||||||
|
crate::throttled_log!(
|
||||||
|
CONFIG_STORE_LOG_INTERVAL,
|
||||||
|
error,
|
||||||
|
"Failed to read peer config '{}'; skipping save: {}",
|
||||||
|
id,
|
||||||
|
err
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
if let Err(err) = store_path(Self::path(id), config) {
|
if let Err(err) = store_path(Self::path(id), config) {
|
||||||
log::error!("Failed to store config: {}", err);
|
log::error!("Failed to store config: {}", err);
|
||||||
}
|
}
|
||||||
NEW_STORED_PEER_CONFIG.lock().unwrap().insert(id.to_owned());
|
NEW_STORED_PEER_CONFIG.lock().unwrap().insert(id.to_owned());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn get_trusted_device_v2(id: &str) -> crate::ResultType<String> {
|
||||||
|
let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap();
|
||||||
|
let config: Self = try_load_path(Self::path(id))?;
|
||||||
|
Ok(config.trusted_device_v2)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_trusted_device_v2(
|
||||||
|
id: &str,
|
||||||
|
value: String,
|
||||||
|
info: PeerInfoSerde,
|
||||||
|
) -> crate::ResultType<()> {
|
||||||
|
let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap();
|
||||||
|
let mut config: Self = try_load_path(Self::path(id))?;
|
||||||
|
config.trusted_device_v2 = value;
|
||||||
|
config.info = info;
|
||||||
|
store_path(Self::path(id), config)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn remove(id: &str) {
|
pub fn remove(id: &str) {
|
||||||
|
let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap();
|
||||||
fs::remove_file(Self::path(id)).ok();
|
fs::remove_file(Self::path(id)).ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2704,22 +2818,6 @@ impl Group {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
|
||||||
pub struct TrustedDevice {
|
|
||||||
pub hwid: Bytes,
|
|
||||||
pub time: i64,
|
|
||||||
pub id: String,
|
|
||||||
pub name: String,
|
|
||||||
pub platform: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TrustedDevice {
|
|
||||||
pub fn outdate(&self) -> bool {
|
|
||||||
const DAYS_90: i64 = 90 * 24 * 60 * 60 * 1000;
|
|
||||||
self.time + DAYS_90 < crate::get_time()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
deserialize_default!(deserialize_string, String);
|
deserialize_default!(deserialize_string, String);
|
||||||
deserialize_default!(deserialize_bool, bool);
|
deserialize_default!(deserialize_bool, bool);
|
||||||
deserialize_default!(deserialize_i32, i32);
|
deserialize_default!(deserialize_i32, i32);
|
||||||
|
|||||||
Reference in new issue
Block a user