1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
|
//! Code for migrating between different versions of the settings.
//! Migration only supports migrating forward, to newer formats.
//!
//! A settings migration module is responsible for converting
//! from its own version to the next version. So `v3::migrate`
//! migrates from settings version `V3` to `V4` etc.
//!
//! Migration modules may NOT import and use structs that may
//! change. Because then a later change to the current code can break
//! old migrations. The only items a settings migration module may import
//! are anything from `std`, `jnix`, `serde` and the following:
//!
//! ```ignore
//! use super::{Error, Result};
//! use mullvad_types::relay_constraints::Constraint;
//! use mullvad_types::settings::SettingsVersion;
//! ```
//!
//! Any other type must be vendored into the migration module so the format
//! it has is locked over time.
//!
//! There should never be multiple migrations between two official releases. At most one.
//! Between releases, dev builds can break the settings without having a proper migration path.
//!
//! # Creating a migration
//!
//! 1. Copy `vX.rs.template` to `vX.rs` where `X` is the latest settings version right now.
//! 1. Add the new version (`Y = X+1`) to `SettingsVersion` and bump `CURRENT_SETTINGS_VERSION` to
//! `Y`.
//! 1. Write a comment in the new module about how the format changed, what it needs to migrate.
//! 1. Implement the migration and add adequate tests.
//! 1. Add to the changelog: "Settings format updated to `vY`"
use std::{
path::Path,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use tokio::{
fs,
io::{self, AsyncWriteExt},
};
mod account_history;
mod device;
mod v1;
mod v10;
mod v11;
mod v12;
mod v2;
mod v3;
mod v4;
mod v5;
mod v6;
mod v7;
mod v8;
mod v9;
const SETTINGS_FILE: &str = "settings.json";
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Failed to read the settings")]
Read(#[source] io::Error),
#[error("Failed to deserialize settings")]
Deserialize(#[source] serde_json::Error),
#[error("Unexpected settings format")]
InvalidSettingsContent,
#[error("Unable to serialize settings to JSON")]
Serialize(#[source] serde_json::Error),
#[error("Unable to open settings for writing")]
Open(#[source] io::Error),
#[error("Unable to write new settings")]
Write(#[source] io::Error),
#[error("Unable to sync settings to disk")]
SyncSettings(#[source] io::Error),
#[error("Failed to read the account history")]
ReadHistory(#[source] io::Error),
#[error("Failed to write new account history")]
WriteHistory(#[source] io::Error),
#[error("Failed to parse account history")]
ParseHistory,
#[cfg(windows)]
#[error("Failed to restore Windows update backup")]
WinMigration(#[source] windows::Error),
}
pub type Result<T> = std::result::Result<T, Error>;
/// Returns whether there is any background work remaining.
#[derive(Clone)]
pub struct MigrationComplete(Arc<AtomicBool>);
impl MigrationComplete {
pub fn new(state: bool) -> Self {
Self(Arc::new(AtomicBool::new(state)))
}
pub fn is_complete(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
fn set_complete(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
/// Contains discarded data that may be useful for later work.
pub type MigrationData = v5::MigrationData;
/// Directories that may be passed to the migration logic.
pub struct Directories<'path> {
cache_dir: &'path Path,
settings_dir: &'path Path,
}
pub async fn migrate_all(cache_dir: &Path, settings_dir: &Path) -> Result<Option<MigrationData>> {
#[cfg(windows)]
windows::migrate_after_windows_update(settings_dir)
.await
.map_err(Error::WinMigration)?;
let path = settings_dir.join(SETTINGS_FILE);
if !path.is_file() {
return Ok(None);
}
let settings_bytes = fs::read(&path).await.map_err(Error::Read)?;
let mut settings: serde_json::Value =
serde_json::from_reader(&settings_bytes[..]).map_err(Error::Deserialize)?;
let old_settings = settings.clone();
let directories = Directories {
cache_dir,
settings_dir,
};
let migration_data = migrate_settings(Some(directories), &mut settings).await?;
if settings == old_settings {
// Nothing changed
return Ok(migration_data);
}
let buffer = serde_json::to_string_pretty(&settings).map_err(Error::Serialize)?;
let mut file = fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&path)
.await
.map_err(Error::Open)?;
file.write_all(&buffer.into_bytes())
.await
.map_err(Error::Write)?;
file.sync_data().await.map_err(Error::SyncSettings)?;
log::debug!("Migrated settings. Wrote settings to {}", path.display());
Ok(migration_data)
}
async fn migrate_settings(
directories: Option<Directories<'_>>,
settings: &mut serde_json::Value,
) -> Result<Option<MigrationData>> {
if !settings.is_object() {
return Err(Error::InvalidSettingsContent);
}
v1::migrate(settings)?;
v2::migrate(settings)?;
v3::migrate(settings)?;
v4::migrate(settings)?;
if let Some(Directories {
cache_dir,
settings_dir,
}) = directories
{
account_history::migrate_location(cache_dir, settings_dir).await;
account_history::migrate_formats(settings_dir, settings).await?;
}
let migration_data = v5::migrate(settings)?;
v6::migrate(settings)?;
v7::migrate(settings)?;
v8::migrate(settings)?;
v9::migrate(
settings,
#[cfg(target_os = "android")]
directories.map(|directories| v9::Directories {
settings: directories.settings_dir,
}),
)?;
v10::migrate(settings)?;
v11::migrate(settings)?;
v12::migrate(settings)?;
Ok(migration_data)
}
pub(crate) fn migrate_device(
migration_data: MigrationData,
rest_handle: mullvad_api::rest::MullvadRestHandle,
daemon_tx: crate::DaemonEventSender,
) -> MigrationComplete {
let migration_complete = MigrationComplete::new(false);
device::generate_device(
migration_data,
migration_complete.clone(),
rest_handle,
daemon_tx,
);
migration_complete
}
#[cfg(windows)]
mod windows {
use std::{
ffi::OsStr,
io,
os::windows::ffi::OsStrExt,
path::Path,
ptr::{self, NonNull},
};
use talpid_types::ErrorExt;
use tokio::fs;
use windows_sys::Win32::{
Foundation::{ERROR_SUCCESS, LocalFree},
Security::{
Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT, SE_OBJECT_TYPE},
IsWellKnownSid, OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID,
SECURITY_DESCRIPTOR, SID, WELL_KNOWN_SID_TYPE, WinBuiltinAdministratorsSid,
WinLocalSystemSid,
},
};
#[allow(non_camel_case_types)]
type SECURITY_INFORMATION = u32;
const MIGRATION_DIRNAME: &str = "windows.old";
const MIGRATE_FILES: [(&str, bool); 3] = [
("settings.json", true),
("device.json", true),
("account-history.json", false),
];
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Unable to find local appdata directory")]
FindAppData,
#[error("Could not acquire security descriptor of backup directory")]
SecurityInformation(#[source] io::Error),
#[error("Backup directory is not owned by SYSTEM or Built-in Administrators")]
WrongOwner,
#[error("Failed to copy files during migration")]
Io(#[source] io::Error),
}
/// Attempts to restore the Mullvad settings from `C:\windows.old` after an update of Windows.
/// Upon success, it returns `Ok(true)` if the migration succeeded, and `Ok(false)` if no
/// migration was needed.
pub async fn migrate_after_windows_update(
destination_settings_dir: &Path,
) -> Result<bool, Error> {
let system_appdata_dir = dirs::data_local_dir().ok_or(Error::FindAppData)?;
if !destination_settings_dir.starts_with(system_appdata_dir) {
return Ok(false);
}
let settings_path = destination_settings_dir.join(super::SETTINGS_FILE);
if settings_path.exists() {
return Ok(false);
}
let mut components = destination_settings_dir.components();
let prefix = if let Some(prefix) = components.next() {
prefix
} else {
return Ok(false);
};
let root = if let Some(root) = components.next() {
root
} else {
return Ok(false);
};
let windows_old_dir = Path::new(&prefix).join(root).join(MIGRATION_DIRNAME);
let source_settings_dir = Path::new(&windows_old_dir).join(&components);
if !source_settings_dir.exists() {
return Ok(false);
}
let security_info =
SecurityInformation::from_file(windows_old_dir.as_path(), OWNER_SECURITY_INFORMATION)
.map_err(Error::SecurityInformation)?;
let owner_sid = security_info.owner().ok_or(Error::WrongOwner)?;
if !is_well_known_sid(owner_sid, WinLocalSystemSid)
&& !is_well_known_sid(owner_sid, WinBuiltinAdministratorsSid)
{
return Err(Error::WrongOwner);
}
if !destination_settings_dir.exists() {
fs::create_dir_all(destination_settings_dir)
.await
.map_err(Error::Io)?;
}
let mut result = Ok(true);
for (file, required) in &MIGRATE_FILES {
let from = source_settings_dir.join(file);
let to = destination_settings_dir.join(file);
log::debug!("Migrating {} to {}", from.display(), to.display());
match fs::copy(&from, &to).await {
Ok(_) => {
let _ = fs::remove_file(from).await;
}
Err(error) => {
log::error!(
"{}",
error.display_chain_with_msg(&format!(
"Failed to copy {} to {}",
from.display(),
to.display()
))
);
if *required {
result = Err(Error::Io(error));
}
}
}
}
if let Err(error) = fs::remove_dir(source_settings_dir).await {
log::trace!(
"{}",
error.display_chain_with_msg("Failed to delete backup directory")
);
}
result
}
struct SecurityInformation {
security_descriptor: NonNull<SECURITY_DESCRIPTOR>,
owner: Option<NonNull<SID>>,
}
impl SecurityInformation {
pub fn from_file<T: AsRef<OsStr>>(
path: T,
security_information: SECURITY_INFORMATION,
) -> Result<Self, io::Error> {
Self::from_object(path, SE_FILE_OBJECT, security_information)
}
pub fn from_object<T: AsRef<OsStr>>(
object_name: T,
object_type: SE_OBJECT_TYPE,
security_information: SECURITY_INFORMATION,
) -> Result<Self, io::Error> {
let mut u16_path: Vec<u16> = object_name.as_ref().encode_wide().collect();
u16_path.push(0u16);
let mut security_descriptor: PSECURITY_DESCRIPTOR = ptr::null_mut();
let mut owner: PSID = ptr::null_mut();
// SAFETY:
// - u16_path is a null-terminated UTF-16 string
// - The *mut pointers are allowed to be null
let status = unsafe {
GetNamedSecurityInfoW(
u16_path.as_ptr(),
object_type,
security_information,
&mut owner,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
&mut security_descriptor,
)
};
if status != ERROR_SUCCESS {
return Err(std::io::Error::from_raw_os_error(status as i32));
}
let Some(security_descriptor) = NonNull::new(security_descriptor) else {
return Err(std::io::Error::other("GetNamedSecurityInfoW returned null"));
};
Ok(SecurityInformation {
security_descriptor: security_descriptor.cast::<SECURITY_DESCRIPTOR>(),
owner: NonNull::new(owner.cast::<SID>()),
})
}
pub fn owner(&self) -> Option<&SID> {
// SAFETY: GetNamedSecurityInfoW promises that this pointer was valid,
// and it should stay valid until we deallocate self.security_descriptor.
self.owner.map(|ptr| unsafe { ptr.as_ref() })
}
}
impl Drop for SecurityInformation {
fn drop(&mut self) {
// SAFETY: GetNamedSecurityInfoW promises that this pointer was valid,
// and we do not deallocate it before this point. Since we have &mut self,
// we know that no one else has a reference to security_descriptor.
unsafe { LocalFree(self.security_descriptor.as_ptr() as PSECURITY_DESCRIPTOR) };
}
}
fn is_well_known_sid(sid: &SID, well_known_sid_type: WELL_KNOWN_SID_TYPE) -> bool {
// SAFETY: this function doesn't take ownership of sid, and is trivially safe to call.
unsafe { IsWellKnownSid(sid as *const SID as PSID, well_known_sid_type) == 1 }
}
}
#[cfg(test)]
mod test {
use mullvad_types::settings::{CURRENT_SETTINGS_VERSION, Settings};
use crate::migrations::migrate_settings;
/// Ensure that no migration logic runs for the default settings by checking whether anything
/// has changed after running the migration code
#[tokio::test]
async fn test_settings_format_version() {
let default_settings = serde_json::to_value(Settings::default()).unwrap();
let mut migrated_settings = default_settings.clone();
migrate_settings(None, &mut migrated_settings)
.await
.unwrap();
assert_eq!(default_settings, migrated_settings);
}
/// Ensure that the settings version is correct after running all migration code
#[tokio::test]
async fn test_all_migrations() {
const V1_SETTINGS: &str = include_str!("v1_settings.json");
let mut settings = serde_json::from_str(V1_SETTINGS).unwrap();
migrate_settings(None, &mut settings).await.unwrap();
let deserialized: Settings = serde_json::from_value(settings).unwrap();
assert_eq!(deserialized.settings_version, CURRENT_SETTINGS_VERSION);
}
}
|