diff --git a/Cargo.toml b/Cargo.toml index 7a8c3ec53..e8a722802 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -90,6 +90,3 @@ webrtc = "0.13.0" # keep in lockstep with [dependencies] webrtc (rustc 1.75 pin, [target.'cfg(target_os = "linux")'.dependencies] users = { version = "0.11" } x11 = "2.21" - -[target.'cfg(target_os = "windows")'.dependencies] -windows = { version = "0.61", features = ["Win32_Storage_FileSystem", "Win32_System_IO", "Win32_Security"] } diff --git a/src/config.rs b/src/config.rs index efeb4b8c7..c6354099e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,7 +10,6 @@ use std::{ }; use anyhow::{anyhow, Result}; -use bytes::Bytes; use rand::Rng; use regex::Regex; use serde as de; @@ -19,9 +18,7 @@ use serde_json; use sodiumoxide::base64; use sodiumoxide::crypto::sign; -mod file_storage; mod permanent_password; -pub use file_storage::FileStorage; pub use permanent_password::{ compute_permanent_password_h1, decode_permanent_password_h1_from_storage, @@ -67,7 +64,6 @@ lazy_static::lazy_static! { static ref CONFIG2: RwLock = RwLock::new(Config2::load()); static ref LOCAL_CONFIG: RwLock = RwLock::new(LocalConfig::load()); static ref STATUS: RwLock = RwLock::new(Status::load()); - static ref TRUSTED_DEVICES: RwLock<(Vec, bool)> = Default::default(); static ref ONLINE: Mutex> = Default::default(); pub static ref PROD_RENDEZVOUS_SERVER: RwLock = RwLock::new("".to_owned()); pub static ref EXE_RENDEZVOUS_SERVER: RwLock = Default::default(); @@ -248,9 +244,6 @@ pub struct Config2 { serial: i32, #[serde(default, deserialize_with = "deserialize_string")] unlock_pin: String, - #[serde(default, deserialize_with = "deserialize_string")] - trusted_devices: String, - #[serde( default, deserialize_with = "deserialize_string", @@ -276,6 +269,8 @@ pub struct Resolution { pub struct PeerConfig { #[serde(default, deserialize_with = "deserialize_vec_u8")] pub password: Vec, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub trusted_device_v2: String, #[serde(default, deserialize_with = "deserialize_size")] pub size: Size, #[serde(default, deserialize_with = "deserialize_size")] @@ -403,6 +398,7 @@ impl Default for PeerConfig { fn default() -> Self { Self { password: Default::default(), + trusted_device_v2: Default::default(), size: Default::default(), size_ft: Default::default(), size_pf: Default::default(), @@ -527,10 +523,9 @@ impl Config2 { } fn try_store(&self) -> crate::ResultType<()> { - let storage = FileStorage::lock(&Self::file())?; let mut config = self.clone(); - let stored: Config2 = storage.read_toml()?; - // Ordinary settings and stale process snapshots must never restore grants. + let stored: Config2 = try_load_path(Self::file())?; + // Ordinary settings must not restore grants from a stale snapshot. config.trusted_devices_v2 = stored.trusted_devices_v2; if let Some(mut socks) = config.socks { let stored_password = stored @@ -544,19 +539,20 @@ impl Config2 { } config.unlock_pin = keep_encrypted_storage_if_plaintext_unchanged(&config.unlock_pin, &stored.unlock_pin); - storage.write_toml(&config) + store_path(Self::file(), config) } pub fn get_trusted_devices_v2() -> crate::ResultType { - let config: Self = FileStorage::lock(&Self::file())?.read_toml()?; + let _lock = CONFIG2.read().unwrap(); + let config: Self = try_load_path(Self::file())?; Ok(config.trusted_devices_v2) } pub fn set_trusted_devices_v2(value: String) -> crate::ResultType<()> { - let storage = FileStorage::lock(&Self::file())?; - let mut config: Self = storage.read_toml()?; + let _lock = CONFIG2.write().unwrap(); + let mut config: Self = try_load_path(Self::file())?; config.trusted_devices_v2 = value; - storage.write_toml(&config) + store_path(Self::file(), config) } pub fn without_trusted_devices_v2(self) -> Self { @@ -589,6 +585,21 @@ fn keep_encrypted_storage_if_plaintext_unchanged(plain: &str, stored: &str) -> S encrypt_str_or_original(plain, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN) } +fn try_load_path( + path: PathBuf, +) -> crate::ResultType { + 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()), + } +} + pub fn load_path( file: PathBuf, ) -> T { @@ -1352,7 +1363,6 @@ impl Config { } config.password = stored; config.store(); - Self::clear_trusted_devices(); true } @@ -1388,7 +1398,6 @@ impl Config { } config.store(); - Self::clear_trusted_devices(); Ok(true) } @@ -1626,70 +1635,10 @@ impl Config { 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 { - 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 = - 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) { - 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) { - 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 { 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 { let mut lock = CONFIG.write().unwrap(); if *lock == cfg { @@ -1734,6 +1683,7 @@ impl Config { } const PEERS: &str = "peers"; +static PEER_CONFIG_WRITE_LOCK: Mutex<()> = Mutex::new(()); impl PeerConfig { pub fn load(id: &str) -> PeerConfig { @@ -1757,6 +1707,8 @@ impl PeerConfig { if store { config.store_(id); } + // Credentials must not reach general-purpose peer settings or UI data. + config.trusted_device_v2.clear(); config } Err(err) => { @@ -1785,12 +1737,36 @@ impl PeerConfig { *v = encrypt_str_or_original(v, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN) } } - if let Err(err) = store_path(Self::path(id), config) { + let result = (|| { + let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap(); + // A stale settings snapshot must not overwrite a newly issued credential. + config.trusted_device_v2 = try_load_path::(Self::path(id))?.trusted_device_v2; + store_path(Self::path(id), config) + })(); + if let Err(err) = result { log::error!("Failed to store config: {}", err); } NEW_STORED_PEER_CONFIG.lock().unwrap().insert(id.to_owned()); } + pub fn get_trusted_device_v2(id: &str) -> crate::ResultType { + 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) { fs::remove_file(Self::path(id)).ok(); } @@ -2741,22 +2717,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_bool, bool); deserialize_default!(deserialize_i32, i32); diff --git a/src/config/file_storage.rs b/src/config/file_storage.rs deleted file mode 100644 index fdf05b896..000000000 --- a/src/config/file_storage.rs +++ /dev/null @@ -1,162 +0,0 @@ -use crate::{anyhow::Context, ResultType}; -use serde::{de::DeserializeOwned, Serialize}; -use std::{ - fs::{self, File, OpenOptions}, - io::{ErrorKind, Write}, - path::{Path, PathBuf}, -}; - -#[cfg(unix)] -const PRIVATE_DIRECTORY_MODE: u32 = 0o700; -#[cfg(unix)] -const PRIVATE_FILE_MODE: u32 = 0o600; - -pub struct FileStorage { - path: PathBuf, - _lock: File, -} - -impl FileStorage { - pub fn lock(path: &Path) -> ResultType { - let parent = path - .parent() - .ok_or_else(|| crate::anyhow::anyhow!("Missing credential directory"))?; - let mut directories = fs::DirBuilder::new(); - directories.recursive(true); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt; - directories.mode(PRIVATE_DIRECTORY_MODE); - } - directories - .create(parent) - .context("Create trusted-device credential directory")?; - let lock = lock_file(&path.with_extension("lock"))?; - Ok(Self { - path: path.to_owned(), - _lock: lock, - }) - } - - pub fn read(&self) -> ResultType { - match File::open(&self.path) { - Ok(file) => serde_json::from_reader(file).context("Read trusted-device credentials"), - Err(error) if error.kind() == ErrorKind::NotFound => Ok(T::default()), - Err(error) => Err(error).context("Open trusted-device credentials"), - } - } - - pub fn read_toml(&self) -> ResultType { - match fs::read_to_string(&self.path) { - Ok(value) => crate::toml::from_str(&value) - .map_err(|_| crate::anyhow::anyhow!("Invalid configuration file")), - Err(error) if error.kind() == ErrorKind::NotFound => Ok(T::default()), - Err(error) => Err(error).context("Open configuration file"), - } - } - - pub fn write_toml(&self, value: &T) -> ResultType<()> { - let value = crate::toml::to_string(value).context("Encode configuration update")?; - self.write_with(|file| Ok(file.write_all(value.as_bytes())?)) - } - - pub fn write(&self, value: &T) -> ResultType<()> { - self.write_with(|file| { - serde_json::to_writer(file, value).context("Encode trusted-device credential update") - }) - } - - fn write_with(&self, write: impl FnOnce(&mut File) -> ResultType<()>) -> ResultType<()> { - let temporary = self - .path - .with_extension(format!("{}.tmp", crate::uuid::Uuid::new_v4())); - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(PRIVATE_FILE_MODE); - } - let mut file = options - .open(&temporary) - .context("Create trusted-device credential update")?; - write(&mut file)?; - file.sync_all() - .context("Persist trusted-device credential update")?; - #[cfg(not(windows))] - fs::rename(&temporary, &self.path).context("Commit trusted-device credential update")?; - #[cfg(windows)] - replace_file(&temporary, &self.path)?; - #[cfg(unix)] - if let Some(parent) = self.path.parent() { - File::open(parent)? - .sync_all() - .context("Persist trusted-device credential directory")?; - } - Ok(()) - } -} - -fn lock_file(path: &Path) -> ResultType { - let mut options = OpenOptions::new(); - options.read(true).write(true).create(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options - .mode(PRIVATE_FILE_MODE) - .custom_flags(crate::libc::O_NOFOLLOW | crate::libc::O_CLOEXEC); - } - #[cfg(windows)] - { - use std::os::windows::fs::OpenOptionsExt; - use windows::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE}; - options.share_mode(FILE_SHARE_READ.0 | FILE_SHARE_WRITE.0); - } - let file = options - .open(path) - .context("Lock trusted-device credentials")?; - #[cfg(unix)] - { - use std::os::fd::AsRawFd; - let result = unsafe { crate::libc::flock(file.as_raw_fd(), crate::libc::LOCK_EX) }; - if result != 0 { - return Err(std::io::Error::last_os_error()).context("Lock trusted-device credentials"); - } - } - #[cfg(windows)] - lock_windows_file(&file)?; - Ok(file) -} - -#[cfg(windows)] -fn lock_windows_file(file: &File) -> ResultType<()> { - use std::os::windows::io::AsRawHandle; - use windows::Win32::{Foundation::HANDLE, Storage::FileSystem, System::IO::OVERLAPPED}; - const LOCK_BYTES: u32 = 1; - // This is a synchronous handle: wait for the lock; closing the handle releases it. - unsafe { - FileSystem::LockFileEx( - HANDLE(file.as_raw_handle()), - FileSystem::LOCKFILE_EXCLUSIVE_LOCK, - None, - LOCK_BYTES, - 0, - &mut OVERLAPPED::default(), - ) - } - .context("Lock trusted-device credentials") -} - -#[cfg(windows)] -fn replace_file(source: &Path, destination: &Path) -> ResultType<()> { - use windows::{core::HSTRING, Win32::Storage::FileSystem}; - unsafe { - FileSystem::MoveFileExW( - &HSTRING::from(source), - &HSTRING::from(destination), - FileSystem::MOVEFILE_REPLACE_EXISTING | FileSystem::MOVEFILE_WRITE_THROUGH, - ) - } - .context("Commit trusted-device credential update") -}