summaryrefslogtreecommitdiffhomepage
path: root/mullvad-daemon/src/migrations/v9.rs
blob: f2fc86e472d4d9d82b706558398960a2e890ce57 (plain)
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
#[cfg(target_os = "android")]
use serde_json::json;
#[cfg(target_os = "android")]
use std::{
    fs::{read_to_string, remove_file},
    path::Path,
};

use mullvad_types::settings::SettingsVersion;

use super::{Error, Result};

// ======================================================
// Section for vendoring types and values that
// this settings version depend on. See `mod.rs`.
type JsonSettings = serde_json::Map<String, serde_json::Value>;

/// Directories which the migration may want to touch.
#[cfg(target_os = "android")]
pub struct Directories<'path> {
    /// The path to the directory where `settings.json` is stored.
    pub settings: &'path Path,
}

/// The file where all currently split-tunnelled apps are stored.
#[cfg(target_os = "android")]
const SPLIT_TUNNELING_APPS: &str = "split-tunnelling.txt";
/// The file where the split-tunnelling state (enabled / disabled) is stored.
#[cfg(target_os = "android")]
const SPLIT_TUNNELING_STATE: &str = "split-tunnelling-enabled.txt";

// ======================================================

/// This migration onboards the Android app's split tunnel settings into the daemon's settings.
///
/// Until now, split tunneling has been completely handled client side by the Android app. This
/// includes keeping track of the setting itself (enabled / disabled) as well as all apps whose
/// traffic is supposed to be routed outside of any active tunnel. This migration reads all split
/// apps which has been stored by the Android client and writes them to the daemon's settings,
/// adding the 'split_tunnel' key to the settings object in the process.
///
/// # Note
/// This `migrate` function needs to get passed a `settings_dir` to work on Android. This is
/// because the Android client will pass the settings directory when initializing the daemon,
/// which means that we can not know ahead of time where the settings are stored.
pub fn migrate(
    settings: &mut serde_json::Value,
    #[cfg(target_os = "android")] directories: Option<Directories<'_>>,
) -> Result<()> {
    if !version_matches(settings) {
        return Ok(());
    }

    log::info!("Migrating settings format to V10");

    let json_blob = to_settings_object(settings)?;

    // TODO: Remove this comment when closing the migration:
    // While this is an open migration, we check to see if the split tunnel apps have been migrated
    // already. If so, we don't want to run the migration code again. The call to
    // `split_tunnel_subkey_exists` can safely be removed when closing this migration.
    #[cfg(target_os = "android")]
    if !android::split_tunnel_subkey_exists(json_blob) {
        if let Some(directories) = directories {
            android::migrate_split_tunnel_settings(json_blob, directories)?;
        } else {
            log::warn!(
                "Did not migrate old split tunnelled apps due to missing settings directory"
            );
        }
    }

    json_blob["settings_version"] = serde_json::json!(SettingsVersion::V10);

    Ok(())
}

fn version_matches(settings: &serde_json::Value) -> bool {
    settings
        .get("settings_version")
        .map(|version| version == SettingsVersion::V9 as u64)
        .unwrap_or(false)
}

/// Represent the settings blob for what it is: A JSON-object.
fn to_settings_object(settings: &mut serde_json::Value) -> Result<&mut JsonSettings> {
    settings
        .as_object_mut()
        .ok_or(Error::InvalidSettingsContent)
}

#[cfg(target_os = "android")]
mod android {
    use super::*;

    /// Check if the "split_tunnel" subkey already exists on the settings blob.
    /// On Android, this key *should not* exist before this migration.
    pub fn split_tunnel_subkey_exists(settings: &mut JsonSettings) -> bool {
        settings.get("split_tunnel").is_some()
    }

    /// Read the existing split-tunneling settings which the Android client has kept track off and
    /// write them to the settings object.
    pub fn migrate_split_tunnel_settings(
        settings: &mut JsonSettings,
        directories: Directories<'_>,
    ) -> Result<()> {
        // Read the split tunnel state (enabled / disabled) & all split apps
        // If both files can not be read for whatever reason we should not migrate any actual data.
        // Instead, we fill in conservative default values instead.
        let (enabled, split_apps) = match (
            read_split_tunnel_state(&directories),
            read_split_apps(&directories),
        ) {
            (Some(enabled), Some(apps)) => (enabled, apps),
            _ => (false, vec![]),
        };

        // Write the split tunnel settings to the settings object.
        add_split_tunneling_settings(settings, enabled, split_apps);

        // Remove the old leftover settings files.
        remove_old_split_tunneling_directories(&directories);

        Ok(())
    }

    /// Add the "split_tunnel" subkey to the settings object while setting it's own subkeys to
    /// `enabled` and `apps`.
    pub fn add_split_tunneling_settings(
        settings: &mut JsonSettings,
        enabled: bool,
        apps: Vec<String>,
    ) {
        // Create the "split_tunnel" key in the settings object and store the read split tunnel
        // state in the daemon's settings
        settings.insert(
            "split_tunnel".to_string(),
            json!({ "enable_exclusions": enabled, "apps": apps }),
        );
    }

    /// Read the target file and parse the stored split tunneling state. If split tunneling was
    /// previously enabled in the android app, the return value of this function will be
    /// `Some(true)`, otherwise `Some(false)`.
    ///
    /// If the file could not be found or read, some logging will occur and `None` will be returned.
    pub fn read_split_tunnel_state(directories: &Directories<'_>) -> Option<bool> {
        let path = directories.settings.join(SPLIT_TUNNELING_STATE);
        log::trace!("Reading split tunnel state from {}", path.display());
        let enabled = read_to_string(path.clone())
            .inspect_err(|_| {
                log::error!("Could not read split tunnel state from {}", path.display())
            })
            .ok()?
            .trim()
            .eq("true");
        Some(enabled)
    }

    /// Read the target file and parse the stored split tunneled apps.
    ///
    /// If the file could not be found or read, some logging will occur and `None` will be returned.
    pub fn read_split_apps(directories: &Directories<'_>) -> Option<Vec<String>> {
        let path = directories.settings.join(SPLIT_TUNNELING_APPS);
        log::trace!("Reading split tunnel apps from {}", path.display());
        let split_apps = read_to_string(path.clone())
            .inspect_err(|_| {
                log::error!("Could not read split tunnel apps from {}", path.display())
            })
            .ok()?
            .lines()
            .map(str::to_owned)
            .collect();
        Some(split_apps)
    }

    /// Remove the lingering, old files split tunnelling related files. They should have been
    /// completely migrated to the daemon settings at this point, so they won't be needed any
    /// longer.
    ///
    /// Note: We don't really care if these operations fail - they won't ever be read again, and new
    /// app installations shall not create them.
    pub fn remove_old_split_tunneling_directories(directories: &Directories<'_>) {
        remove_file(directories.settings.join(SPLIT_TUNNELING_STATE))
            .inspect_err(|error| log::error!("Failed to remove {SPLIT_TUNNELING_STATE}: {error}"))
            .ok();
        remove_file(directories.settings.join(SPLIT_TUNNELING_APPS))
            .inspect_err(|error| log::error!("Failed to remove {SPLIT_TUNNELING_APPS}: {error}"))
            .ok();
    }
}

#[cfg(test)]
mod test {
    use super::{migrate, version_matches};

    #[cfg(target_os = "android")]
    mod android {
        /// Assert that split-tunneling settings has been added to the android settings post-migration.
        #[test]
        fn test_v9_to_v10_migration() {
            use crate::migrations::v9::{
                add_split_tunneling_settings,
                test::android::constants::{V9_ANDROID_SETTINGS, V10_ANDROID_SETTINGS},
            };

            let enabled = true;
            let apps = ["com.android.chrome", "net.mullvad.mullvadvpn"];

            let mut settings = serde_json::from_str(V9_ANDROID_SETTINGS).unwrap();
            // Perform the actual settings migration while skipping the I/O performed in
            // `migrate_split_tunnel_settings`.
            add_split_tunneling_settings(settings, enabled, apps);
            let new_settings = serde_json::from_str(V10_ANDROID_SETTINGS).unwrap();
            assert_eq!(settings, new_settings);
        }

        mod constants {
            /// This settings blob does not contain the "split_tunnel" option.
            pub const V9_ANDROID_SETTINGS: &str = r#"
  {
  "relay_settings": {
    "normal": {
      "location": {
        "only": {
          "location": {
            "hostname": "at-vie-ovpn-001"
          }
        }
      },
      "providers": "any",
      "ownership": "any",
      "tunnel_protocol": "any",
      "wireguard_constraints": {
        "port": "any",
        "ip_version": "any",
        "use_multihop": false,
        "entry_location": {
          "only": {
            "location": {
              "country": "se"
            }
          }
        }
      },
      "openvpn_constraints": {
        "port": "any"
      }
    }
  },
  "bridge_settings": {
    "bridge_type": "normal",
    "normal": {
      "location": "any",
      "providers": "any",
      "ownership": "any"
    },
    "custom": null
  },
  "obfuscation_settings": {
    "selected_obfuscation": "auto",
    "udp2tcp": {
      "port": "any"
    }
  },
  "bridge_state": "auto",
  "custom_lists": {
    "custom_lists": []
  },
  "api_access_methods": {
    "direct": {
      "id": "d81121bf-c942-4ca4-971f-8ea6581bc915",
      "name": "Direct",
      "enabled": true,
      "access_method": {
        "built_in": "direct"
      }
    },
    "mullvad_bridges": {
      "id": "92135711-534d-4950-963d-93e446a792e4",
      "name": "Mullvad Bridges",
      "enabled": true,
      "access_method": {
        "built_in": "bridge"
      }
    },
    "custom": []
  },
  "allow_lan": false,
  "block_when_disconnected": false,
  "auto_connect": false,
  "tunnel_options": {
    "openvpn": {
      "mssfix": null
    },
    "wireguard": {
      "mtu": null,
      "quantum_resistant": "auto",
      "rotation_interval": null
    },
    "generic": {
      "enable_ipv6": false
    },
    "dns_options": {
      "state": "default",
      "default_options": {
        "block_ads": false,
        "block_trackers": false,
        "block_malware": false,
        "block_adult_content": false,
        "block_gambling": false,
        "block_social_media": false
      },
      "custom_options": {
        "addresses": []
      }
    }
  },
  "relay_overrides": [],
  "show_beta_releases": true,
  "settings_version": 9
  }
  "#;

            /// This settings blob *should* contain the "split_tunnel" option.
            pub const V10_ANDROID_SETTINGS: &str = r#"
  {
  "relay_settings": {
    "normal": {
      "location": {
        "only": {
          "location": {
            "country": "se"
          }
        }
      },
      "providers": "any",
      "ownership": "any",
      "tunnel_protocol": "wireguard",
      "wireguard_constraints": {
        "port": "any",
        "ip_version": "any",
        "use_multihop": false,
        "entry_location": {
          "only": {
            "location": {
              "country": "se"
            }
          }
        }
      },
      "openvpn_constraints": {
        "port": "any"
      }
    }
  },
  "bridge_settings": {
    "bridge_type": "normal",
    "normal": {
      "location": "any",
      "providers": "any",
      "ownership": "any"
    },
    "custom": null
  },
  "obfuscation_settings": {
    "selected_obfuscation": "auto",
    "udp2tcp": {
      "port": "any"
    }
  },
  "bridge_state": "auto",
  "custom_lists": {
    "custom_lists": []
  },
  "api_access_methods": {
    "direct": {
      "id": "d81121bf-c942-4ca4-971f-8ea6581bc915",
      "name": "Direct",
      "enabled": true,
      "access_method": {
        "built_in": "direct"
      }
    },
    "mullvad_bridges": {
      "id": "92135711-534d-4950-963d-93e446a792e4",
      "name": "Mullvad Bridges",
      "enabled": true,
      "access_method": {
        "built_in": "bridge"
      }
    },
    "custom": []
  },
  "allow_lan": false,
  "block_when_disconnected": false,
  "auto_connect": false,
  "tunnel_options": {
    "openvpn": {
      "mssfix": null
    },
    "wireguard": {
      "mtu": null,
      "quantum_resistant": "auto",
      "rotation_interval": null
    },
    "generic": {
      "enable_ipv6": false
    },
    "dns_options": {
      "state": "default",
      "default_options": {
        "block_ads": false,
        "block_trackers": false,
        "block_malware": false,
        "block_adult_content": false,
        "block_gambling": false,
        "block_social_media": false
      },
      "custom_options": {
        "addresses": []
      }
    }
  },
  "relay_overrides": [],
  "show_beta_releases": true,
  "split_tunnel": {
    "enable_exclusions": true,
    "apps": ["com.android.chrome", "net.mullvad.mullvadvpn"]
  }
  "settings_version": 10
  }
  "#;
        }
    }

    /// Assert that tunnel type is migrated
    #[test]
    fn test_v9_to_v10_migration() {
        // TODO: Also test the case where the location is not an openvpn relay and the tunnel type is any
        let mut old_settings = serde_json::from_str(V9_SETTINGS).unwrap();

        assert!(version_matches(&old_settings));
        migrate(&mut old_settings).unwrap();
        let new_settings: serde_json::Value = serde_json::from_str(V10_SETTINGS).unwrap();

        eprintln!(
            "old_settings: {}",
            serde_json::to_string_pretty(&old_settings).unwrap()
        );
        eprintln!(
            "new_settings: {}",
            serde_json::to_string_pretty(&new_settings).unwrap()
        );

        assert_eq!(&old_settings, &new_settings);
    }

    /// This settings blob contains no constraint for tunnel type
    pub const V9_SETTINGS: &str = r#"
{
  "relay_settings": {
    "normal": {
      "location": {
        "only": {
          "location": {
            "hostname": "at-vie-ovpn-001"
          }
        }
      },
      "providers": "any",
      "ownership": "any",
      "tunnel_protocol": "any",
      "wireguard_constraints": {
        "port": "any",
        "ip_version": "any",
        "use_multihop": false,
        "entry_location": {
          "only": {
            "location": {
              "country": "se"
            }
          }
        }
      },
      "openvpn_constraints": {
        "port": "any"
      }
    }
  },
  "bridge_settings": {
    "bridge_type": "normal",
    "normal": {
      "location": "any",
      "providers": "any",
      "ownership": "any"
    },
    "custom": null
  },
  "obfuscation_settings": {
    "selected_obfuscation": "auto",
    "udp2tcp": {
      "port": "any"
    }
  },
  "bridge_state": "auto",
  "custom_lists": {
    "custom_lists": []
  },
  "api_access_methods": {
    "direct": {
      "id": "d81121bf-c942-4ca4-971f-8ea6581bc915",
      "name": "Direct",
      "enabled": true,
      "access_method": {
        "built_in": "direct"
      }
    },
    "mullvad_bridges": {
      "id": "92135711-534d-4950-963d-93e446a792e4",
      "name": "Mullvad Bridges",
      "enabled": true,
      "access_method": {
        "built_in": "bridge"
      }
    },
    "custom": []
  },
  "allow_lan": false,
  "block_when_disconnected": false,
  "auto_connect": false,
  "tunnel_options": {
    "openvpn": {
      "mssfix": null
    },
    "wireguard": {
      "mtu": null,
      "quantum_resistant": "auto",
      "rotation_interval": null
    },
    "generic": {
      "enable_ipv6": false
    },
    "dns_options": {
      "state": "default",
      "default_options": {
        "block_ads": false,
        "block_trackers": false,
        "block_malware": false,
        "block_adult_content": false,
        "block_gambling": false,
        "block_social_media": false
      },
      "custom_options": {
        "addresses": []
      }
    }
  },
  "relay_overrides": [],
  "show_beta_releases": true,
  "settings_version": 9
}
"#;

    /// This settings blob does not contain an "any" tunnel type
    pub const V10_SETTINGS: &str = r#"
{
  "relay_settings": {
    "normal": {
      "location": {
        "only": {
          "location": {
            "hostname": "at-vie-ovpn-001"
          }
        }
      },
      "providers": "any",
      "ownership": "any",
      "tunnel_protocol": "any",
      "wireguard_constraints": {
        "port": "any",
        "ip_version": "any",
        "use_multihop": false,
        "entry_location": {
          "only": {
            "location": {
              "country": "se"
            }
          }
        }
      },
      "openvpn_constraints": {
        "port": "any"
      }
    }
  },
  "bridge_settings": {
    "bridge_type": "normal",
    "normal": {
      "location": "any",
      "providers": "any",
      "ownership": "any"
    },
    "custom": null
  },
  "obfuscation_settings": {
    "selected_obfuscation": "auto",
    "udp2tcp": {
      "port": "any"
    }
  },
  "bridge_state": "auto",
  "custom_lists": {
    "custom_lists": []
  },
  "api_access_methods": {
    "direct": {
      "id": "d81121bf-c942-4ca4-971f-8ea6581bc915",
      "name": "Direct",
      "enabled": true,
      "access_method": {
        "built_in": "direct"
      }
    },
    "mullvad_bridges": {
      "id": "92135711-534d-4950-963d-93e446a792e4",
      "name": "Mullvad Bridges",
      "enabled": true,
      "access_method": {
        "built_in": "bridge"
      }
    },
    "custom": []
  },
  "allow_lan": false,
  "block_when_disconnected": false,
  "auto_connect": false,
  "tunnel_options": {
    "openvpn": {
      "mssfix": null
    },
    "wireguard": {
      "mtu": null,
      "quantum_resistant": "auto",
      "rotation_interval": null
    },
    "generic": {
      "enable_ipv6": false
    },
    "dns_options": {
      "state": "default",
      "default_options": {
        "block_ads": false,
        "block_trackers": false,
        "block_malware": false,
        "block_adult_content": false,
        "block_gambling": false,
        "block_social_media": false
      },
      "custom_options": {
        "addresses": []
      }
    }
  },
  "relay_overrides": [],
  "show_beta_releases": true,
  "settings_version": 10
}
"#;
}