diff --git a/AGENTS.md b/AGENTS.md
index 4aeeff3..c217399 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -37,6 +37,7 @@ If a required command fails or emits a warning from project code, fix it in the
- Read the current per-user `biflow/debug.log` first when diagnosing a runtime report. It is permanent newline-delimited JSON across application sessions and is also included by **Diagnostics → Export**. Do not assume it exists before the app has launched, and do not commit a generated `debug.log`.
- Every new or changed desktop user action, background task, platform/helper boundary, warning, ignored failure, and error path in Rust must emit structured `tracing` events that reach `debug.log`. Reuse the command trace helpers in `src-tauri/src/diagnostics.rs` at Tauri boundaries. The separately privileged helper must emit the same safe fields to its service journal; the desktop records each helper request and result in `debug.log` without making the root service write into a user's data directory.
+- A command or check that repeats on a timer uses `diagnostics::trace_poll` or `record_poll`, which log only a change of outcome (ADR 0143). Never put `trace_action` or an `info!` success event on a timer.
- Action events must identify `event`, `section`, `initiator`, `cause`, and `trace_route`; use a stable operation/request UUID as `trace_id` when available. Never log passwords, controller secrets, tokens, credentials, subscription links, raw URLs, full settings, direct-rule values, diagnostic targets, or unredacted user content.
- Do not ignore fallible Rust operations with `let _ =` unless failure is provably irrelevant. Log the warning/error and cause when execution continues, and preserve a regression test for diagnostic lifecycle, redaction, and file-size behavior.
- `debug.log` stays in append mode across process launches and is flushed after every event. Do not truncate, rotate, cap, or delete it automatically on startup or shutdown. Only the explicit Diagnostics delete action clears its contents; it must keep the active file handle usable and resume logging immediately.
@@ -71,6 +72,36 @@ If a required command fails or emits a warning from project code, fix it in the
## Lessons
+- A path or a file that reaches the helper over IPC is attacker input, even
+ from the authorized user: the helper is root and the desktop is not. "Regular,
+ non-symlink file" is not trust. Check who can change the file and every
+ directory above it (ADR 0141).
+- Do not filter another program's config language with a list of bad words.
+ OpenVPN quotes, includes, escapes, `setenv opt`, and closes an inline block on
+ a prefix. Parse it once, allow a known list, and run the rendered copy.
+- A dropped future is not a rollback. A timeout around a multi-step operation
+ needs its own cleanup step and a test that asserts the released state, not
+ only that the lifecycle lock cleared (ADR 0144).
+- Returning Ok because "the same kind of operation is already busy" lets two
+ callers run together. Serialize work that shares a prepared generation, and
+ re-check the phase after waiting.
+- Replacing an application folder deletes whatever the app keeps beside its
+ executable. Hiddify's portable build stores subscriptions there. Read the
+ upstream source for its data folder before removing the old one.
+- Go encodes a nil slice as `null`. `#[serde(default)]` does not accept it, so
+ an idle Mihomo produced "error decoding response body". Run the bundled
+ binary with no traffic when writing a controller fixture.
+- A permanent log plus a one-second poll grew to 4.8 GB. Measure bytes per
+ minute with the window open when adding an event.
+- Never print files from the side-tunnel data folder while diagnosing. They can
+ hold VPN credentials; list names and sizes only. `NamedTempFile` is not
+ deleted by a crash, so clear leftovers at startup.
+- A runtime `cfg!(target_os = "macos")` branch changes what shared tests see on
+ a Mac while Linux and Windows stay green. Give each platform list its own
+ function and test that function by name on every host.
+- `cfg(unix)` constants used by a shared type are dead code in the Windows
+ library build. Run `cargo xwin clippy` after changing the helper.
+
- Hiddify can rename Linux release assets and wrap its Windows portable files
in an outer directory. Verify the publisher's asset names and SHA-256 values,
assert the real ZIP layout in the installer fixture, and publish the complete
diff --git a/Cargo.lock b/Cargo.lock
index 02f8caf..da2b6cd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2044,7 +2044,7 @@ dependencies = [
[[package]]
name = "iran-split-cli"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"async-trait",
"clap",
@@ -2062,7 +2062,7 @@ dependencies = [
[[package]]
name = "iran-split-clients"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"async-trait",
"ipnet",
@@ -2074,11 +2074,12 @@ dependencies = [
"thiserror 2.0.20",
"tokio",
"tokio-util",
+ "uuid",
]
[[package]]
name = "iran-split-config"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"hex",
"rand 0.9.5",
@@ -2091,7 +2092,7 @@ dependencies = [
[[package]]
name = "iran-split-core"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"async-trait",
"iran-split-config",
@@ -2108,7 +2109,7 @@ dependencies = [
[[package]]
name = "iran-split-desktop"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -2150,7 +2151,7 @@ dependencies = [
[[package]]
name = "iran-split-helper"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"clap",
"hex",
@@ -2175,7 +2176,7 @@ dependencies = [
[[package]]
name = "iran-split-helper-winacl"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"tokio",
"windows",
@@ -2183,7 +2184,7 @@ dependencies = [
[[package]]
name = "iran-split-ipc"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"bytes",
"serde",
@@ -2195,7 +2196,7 @@ dependencies = [
[[package]]
name = "iran-split-mihomo"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"futures-util",
"hex",
@@ -2218,7 +2219,7 @@ dependencies = [
[[package]]
name = "iran-split-netstats"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"libc",
"tempfile",
@@ -2227,7 +2228,7 @@ dependencies = [
[[package]]
name = "iran-split-platform-linux"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"async-trait",
"hex",
@@ -2251,7 +2252,7 @@ dependencies = [
[[package]]
name = "iran-split-platform-macos"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"async-trait",
"hex",
@@ -2275,7 +2276,7 @@ dependencies = [
[[package]]
name = "iran-split-platform-win"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"async-trait",
"iran-split-clients",
@@ -2298,7 +2299,7 @@ dependencies = [
[[package]]
name = "iran-split-rules"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"async-trait",
"hex",
@@ -2320,7 +2321,7 @@ dependencies = [
[[package]]
name = "iran-split-taskbar"
-version = "6.2.96"
+version = "6.3.0"
dependencies = [
"iran-split-config",
"objc2",
diff --git a/Cargo.toml b/Cargo.toml
index 4fcaad1..3b89383 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -19,7 +19,7 @@ members = [
]
[workspace.package]
-version = "6.2.96"
+version = "6.3.0"
edition = "2021"
license = "MIT OR Apache-2.0"
rust-version = "1.88"
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 4fc7155..7dfa1ec 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -1,6 +1,6 @@
{
"name": "@iran-split/desktop",
- "version": "6.2.96",
+ "version": "6.3.0",
"private": true,
"type": "module",
"scripts": {
diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx
index ead3adc..1b441bb 100644
--- a/apps/desktop/src/App.test.tsx
+++ b/apps/desktop/src/App.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen, within } from "@testing-library/react";
+import { act, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it } from "vitest";
import { App } from "./App";
@@ -79,6 +79,20 @@ describe("App", () => {
);
});
+ it("says so when startup replaced unreadable settings", async () => {
+ render();
+ await waitFor(() => expect(useAppStore.getState().boot).not.toBeNull());
+ const { boot } = useAppStore.getState();
+ act(() => {
+ useAppStore.setState({
+ boot: boot && { ...boot, settings_recovered: "defaults" },
+ });
+ });
+ expect(
+ await screen.findByText(/The settings file was damaged/),
+ ).toBeInTheDocument();
+ });
+
it("opens the legacy About page as the Settings About tab", async () => {
render();
await homeHeading();
diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx
index c8af2bd..bc187f1 100644
--- a/apps/desktop/src/App.tsx
+++ b/apps/desktop/src/App.tsx
@@ -73,6 +73,17 @@ export function App() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ const settingsRecovered = store.boot?.settings_recovered ?? null;
+ useEffect(() => {
+ if (settingsRecovered) {
+ useAppStore.setState({
+ error: t(`settingsRecovered_${settingsRecovered}`),
+ });
+ }
+ // Shown once per start; changing the language must not reopen it.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [settingsRecovered]);
+
useEffect(() => {
let unsubscribe: () => void = () => undefined;
void desktop
diff --git a/apps/desktop/src/api/models.ts b/apps/desktop/src/api/models.ts
index d380b8b..b25e741 100644
--- a/apps/desktop/src/api/models.ts
+++ b/apps/desktop/src/api/models.ts
@@ -317,6 +317,8 @@ export interface BootstrapResult {
cloud_rules: CloudRulesStatus;
dependencies: DependencyStatus[];
network_status: NetworkStatus;
+ /** Set when startup replaced settings it could not read. */
+ settings_recovered?: "last_saved" | "defaults" | null;
}
export type InternetState = "checking" | "online" | "offline";
diff --git a/apps/desktop/src/i18n/config.ts b/apps/desktop/src/i18n/config.ts
index e04d3b8..182b9be 100644
--- a/apps/desktop/src/i18n/config.ts
+++ b/apps/desktop/src/i18n/config.ts
@@ -169,6 +169,10 @@ const resources = {
downloadInstall: "Download & install",
downloadOpenVpn: "Download OpenVPN",
downloadPageUnavailable: "Could not open the download page.",
+ settingsRecovered_last_saved:
+ "The settings file was damaged. BiFlow loaded your last saved settings.",
+ settingsRecovered_defaults:
+ "The settings file was damaged. BiFlow started with default settings; check your clients.",
downloadWindscribeConfig: "Get Windscribe config",
directTooltip:
"Traffic leaves over your physical network with your real IP.",
@@ -593,6 +597,10 @@ const resources = {
downloadInstall: "دانلود و نصب",
downloadOpenVpn: "دانلود OpenVPN",
downloadPageUnavailable: "صفحهٔ دانلود باز نشد.",
+ settingsRecovered_last_saved:
+ "فایل تنظیمات خراب بود. آخرین تنظیمات ذخیرهشده بارگذاری شد.",
+ settingsRecovered_defaults:
+ "فایل تنظیمات خراب بود. برنامه با تنظیمات پیشفرض باز شد؛ کلاینتها را بررسی کنید.",
downloadWindscribeConfig: "دانلود کانفیگ Windscribe",
directTooltip: "ترافیک با آیپی واقعی از شبکه فیزیکی خارج میشود.",
clientDetails: "تنظیمات و میزبانهای سنجاقشده",
diff --git a/crates/iran-split-cli/src/main.rs b/crates/iran-split-cli/src/main.rs
index 6bed4c1..5801a6c 100644
--- a/crates/iran-split-cli/src/main.rs
+++ b/crates/iran-split-cli/src/main.rs
@@ -182,6 +182,7 @@ impl PlatformBackend for DemoBackend {
available: true,
authorized: true,
version: Some("demo".into()),
+ tun_name: None,
})
}
async fn ensure_hiddify(&self, _cancel: CancellationToken) -> Result<(), CoreError> {
diff --git a/crates/iran-split-clients/Cargo.toml b/crates/iran-split-clients/Cargo.toml
index c4e2421..0e77c51 100644
--- a/crates/iran-split-clients/Cargo.toml
+++ b/crates/iran-split-clients/Cargo.toml
@@ -15,6 +15,7 @@ serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tokio-util.workspace = true
+uuid.workspace = true
[dev-dependencies]
tempfile.workspace = true
diff --git a/crates/iran-split-clients/src/lib.rs b/crates/iran-split-clients/src/lib.rs
index 7a22900..77e5679 100644
--- a/crates/iran-split-clients/src/lib.rs
+++ b/crates/iran-split-clients/src/lib.rs
@@ -6,6 +6,7 @@
mod local_proxy;
mod openvpn;
mod profile_audit;
+mod profile_parse;
mod remote_pin;
mod remote_resolver;
@@ -19,9 +20,10 @@ use tokio_util::sync::CancellationToken;
pub use local_proxy::LocalProxyDriver;
pub use openvpn::OpenVpnDriver;
pub use profile_audit::{
- audit_openvpn_profile, openvpn_arguments, sanitize_openvpn_profile, OpenVpnProfileError,
+ audit_openvpn_profile, load_openvpn_profile, openvpn_arguments, OpenVpnProfileError,
OpenVpnProfileFacts,
};
+pub use profile_parse::CheckedProfile;
pub use remote_pin::{
pin_profile_remote, recall_remote_pin, remember_remote_pin, select_remote_pin, PinnedRemote,
};
@@ -153,6 +155,89 @@ pub fn process_bypass_union(
rules
}
+/// Drops local-proxy handles whose client was removed, disabled, or moved to
+/// another endpoint, and returns their ids. A handle keeps the endpoint it was
+/// verified with, so without this a live apply keeps routing to the old port.
+pub fn drop_outdated_handles(
+ clients: &[ClientInstance],
+ handles: &mut Vec,
+) -> Vec {
+ let mut dropped = Vec::new();
+ handles.retain(|handle| {
+ if handle.kind != EgressKind::LocalProxy {
+ return true;
+ }
+ let current = clients
+ .iter()
+ .find(|client| client.id == handle.client_id && client.enabled)
+ .and_then(local_proxy_endpoint);
+ let verified = handle
+ .outbound
+ .as_ref()
+ .and_then(|outbound| Some((outbound.server.clone()?, outbound.port?)));
+ let keep = current.is_some() && current == verified;
+ if !keep {
+ dropped.push(handle.client_id);
+ }
+ keep
+ });
+ dropped
+}
+
+/// Drops side-tunnel handles whose process the helper no longer runs, and
+/// returns their ids.
+pub fn drop_exited_tunnels(
+ running: &[uuid::Uuid],
+ handles: &mut Vec,
+) -> Vec {
+ let mut dropped = Vec::new();
+ handles.retain(|handle| {
+ let keep = handle.kind != EgressKind::OwnedSideTunnel
+ || running.contains(&handle.client_id.into());
+ if !keep {
+ dropped.push(handle.client_id);
+ }
+ keep
+ });
+ dropped
+}
+
+/// Shown on a client card after its tunnel process ended on its own.
+pub const SIDE_TUNNEL_EXITED: &str = "the tunnel stopped on its own; connect this client again";
+
+/// Removes credential files left by a run that did not exit cleanly.
+///
+/// `OpenVPN` re-reads the file on a soft restart, so a run keeps it until the
+/// tunnel stops. After a crash nothing owns it any more, and startup recovery
+/// has already ended the tunnel it belonged to.
+///
+/// # Errors
+///
+/// Returns the I/O error that kept the directory or a file from being cleared.
+pub fn clear_stale_auth_files(directory: &std::path::Path) -> std::io::Result {
+ let entries = match std::fs::read_dir(directory) {
+ Ok(entries) => entries,
+ Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => return Ok(0),
+ Err(cause) => return Err(cause),
+ };
+ let mut removed = 0;
+ for entry in entries {
+ let entry = entry?;
+ let name = entry.file_name();
+ let owned = name
+ .to_str()
+ .is_some_and(|name| name.starts_with(".tmp") || name.starts_with(AUTH_FILE_PREFIX));
+ if owned && entry.file_type()?.is_file() {
+ std::fs::remove_file(entry.path())?;
+ removed += 1;
+ }
+ }
+ Ok(removed)
+}
+
+/// Name prefix of a side-tunnel credential file.
+pub const AUTH_FILE_PREFIX: &str = "auth-";
+
/// Local-proxy endpoint from an instance, when the config is that kind.
#[must_use]
pub fn local_proxy_endpoint(instance: &ClientInstance) -> Option<(String, u16)> {
@@ -263,6 +348,64 @@ pub fn synthesized_egress_handle(instance: &ClientInstance) -> Option ClientInstance {
+ ClientInstance {
+ preset,
+ config: ClientConfig::from_preset(preset),
+ ..ClientInstance::hiddify_default(ClientId::new())
+ }
+ }
+
+ #[test]
+ fn a_moved_or_disabled_proxy_loses_its_verified_handle() {
+ let mut moved = client_for(PresetId::Hiddify);
+ let kept = client_for(PresetId::Happ);
+ let mut disabled = client_for(PresetId::Happ);
+ let mut handles: Vec<_> = [&moved, &kept, &disabled]
+ .into_iter()
+ .filter_map(synthesized_local_handle)
+ .collect();
+ assert_eq!(handles.len(), 3);
+ let ClientConfig::LocalProxy { port, .. } = &mut moved.config else {
+ panic!("local proxy fixture");
+ };
+ *port += 1;
+ disabled.enabled = false;
+ let (moved_id, kept_id, disabled_id) = (moved.id, kept.id, disabled.id);
+ let dropped = drop_outdated_handles(&[moved, kept, disabled], &mut handles);
+ assert_eq!(dropped, [moved_id, disabled_id]);
+ assert_eq!(handles.len(), 1);
+ assert_eq!(handles[0].client_id, kept_id);
+ }
+
+ #[test]
+ fn only_a_tunnel_the_helper_still_runs_keeps_its_handle() {
+ let proxy = synthesized_local_handle(&client_for(PresetId::Hiddify)).expect("proxy handle");
+ let tunnel = |id| EgressHandle {
+ client_id: id,
+ kind: EgressKind::OwnedSideTunnel,
+ ..proxy.clone()
+ };
+ let (alive, dead) = (ClientId::new(), ClientId::new());
+ let mut handles = vec![proxy.clone(), tunnel(alive), tunnel(dead)];
+ assert_eq!(drop_exited_tunnels(&[alive.into()], &mut handles), [dead]);
+ assert_eq!(handles.len(), 2);
+ }
+
+ #[test]
+ fn leftover_credential_files_are_removed_and_nothing_else() {
+ let directory = tempfile::tempdir().expect("tempdir");
+ for name in [".tmpAb12", "auth-Cd34", "office.ovpn"] {
+ std::fs::write(directory.path().join(name), b"x").expect("fixture");
+ }
+ assert_eq!(clear_stale_auth_files(directory.path()).expect("clear"), 2);
+ assert!(directory.path().join("office.ovpn").is_file());
+ assert_eq!(
+ clear_stale_auth_files(&directory.path().join("missing")).expect("missing"),
+ 0
+ );
+ }
+
#[test]
fn catalog_lists_every_planned_preset() {
let rows = catalog();
diff --git a/crates/iran-split-clients/src/profile_audit.rs b/crates/iran-split-clients/src/profile_audit.rs
index fa20261..70a3885 100644
--- a/crates/iran-split-clients/src/profile_audit.rs
+++ b/crates/iran-split-clients/src/profile_audit.rs
@@ -1,3 +1,4 @@
+use crate::profile_parse::CheckedProfile;
use ipnet::IpNet;
use std::{
net::IpAddr,
@@ -5,36 +6,20 @@ use std::{
};
use thiserror::Error;
-/// Directives that let a profile run code, or steal the interface.
-const FORBIDDEN_DIRECTIVES: [&str; 16] = [
- "up",
- "down",
- "up-restart",
- "route-up",
- "route-pre-down",
- "ipchange",
- "learn-address",
- "tls-verify",
- "auth-user-pass-verify",
- "client-connect",
- "client-disconnect",
- "plugin",
- "script-security",
- "daemon",
- "log",
- "log-append",
-];
-
#[derive(Debug, Error)]
pub enum OpenVpnProfileError {
#[error("profile is unreadable")]
Unreadable,
#[error("profile must be a regular, non-symlink file")]
NotRegularFile,
- #[error("profile uses the '{0}' directive, which would run commands as root")]
+ #[error("profile uses '{0}', which BiFlow does not allow because OpenVPN runs as root")]
ForbiddenDirective(String),
#[error("profile has an unterminated inline block")]
UnterminatedBlock,
+ #[error("profile has a line longer than OpenVPN accepts")]
+ LineTooLong,
+ #[error("profile has quoting or an inline block that cannot be read safely")]
+ Ambiguous,
#[error("profile declares no remote server")]
NoRemote,
}
@@ -48,148 +33,52 @@ pub struct OpenVpnProfileFacts {
pub server_networks: Vec,
}
-/// Reads a `.ovpn` file and rejects anything that would run code as root.
+/// Reads a `.ovpn` file and rejects anything outside the directive allowlist.
///
/// # Errors
///
/// Returns [`OpenVpnProfileError`] when the file is missing, not a regular
-/// file, carries a script directive, or declares no `remote`.
+/// file, uses a directive a client profile does not need, or declares no
+/// `remote`.
pub fn audit_openvpn_profile(path: &Path) -> Result {
+ load_openvpn_profile(path).map(|(facts, _)| facts)
+}
+
+/// Reads and checks a profile once, so the copy `OpenVPN` runs is rendered
+/// from the same bytes that were checked.
+///
+/// # Errors
+///
+/// Same conditions as [`audit_openvpn_profile`].
+pub fn load_openvpn_profile(
+ path: &Path,
+) -> Result<(OpenVpnProfileFacts, CheckedProfile), OpenVpnProfileError> {
let metadata = std::fs::symlink_metadata(path).map_err(|_| OpenVpnProfileError::Unreadable)?;
if !metadata.file_type().is_file() || metadata.file_type().is_symlink() {
return Err(OpenVpnProfileError::NotRegularFile);
}
let text = std::fs::read_to_string(path).map_err(|_| OpenVpnProfileError::Unreadable)?;
- let mut remote_hosts = Vec::new();
- let mut remote_port = None;
- let mut inline_block: Option = None;
- for line in text.lines() {
- let line = line.trim();
- if let Some(open) = inline_block.as_deref() {
- if line.eq_ignore_ascii_case(&format!("{open}>")) {
- inline_block = None;
- }
- continue;
- }
- if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
- continue;
- }
- if let Some(tag) = line
- .strip_prefix('<')
- .and_then(|rest| rest.strip_suffix('>'))
- {
- if !tag.starts_with('/') {
- inline_block = Some(tag.to_ascii_lowercase());
- }
- continue;
- }
- let mut parts = line.split_whitespace();
- let Some(directive) = parts.next() else {
- continue;
- };
- let directive = directive.trim_start_matches("--").to_ascii_lowercase();
- if FORBIDDEN_DIRECTIVES.contains(&directive.as_str()) {
- return Err(OpenVpnProfileError::ForbiddenDirective(directive));
- }
- if directive == "remote" {
- if let Some(host) = parts.next() {
- remote_hosts.push(host.to_owned());
- if remote_port.is_none() {
- remote_port = parts.next().and_then(|port| port.parse::().ok());
- }
- }
- }
- }
- if inline_block.is_some() {
- return Err(OpenVpnProfileError::UnterminatedBlock);
- }
- if remote_hosts.is_empty() {
- return Err(OpenVpnProfileError::NoRemote);
- }
- let server_networks = remote_hosts
+ let profile = CheckedProfile::parse(&text)?;
+ let remotes = profile.remotes();
+ let server_networks = remotes
.iter()
- .filter_map(|host| host.parse::().ok())
- .filter_map(|address| match address {
- IpAddr::V4(address) => IpNet::new(address.into(), 32).ok(),
- IpAddr::V6(address) => IpNet::new(address.into(), 128).ok(),
- })
+ .filter_map(|(host, _)| host.parse::().ok())
+ .filter_map(|address| crate::public_host_exclude(address).ok())
.collect();
- Ok(OpenVpnProfileFacts {
- remote_hosts,
- remote_port,
+ let facts = OpenVpnProfileFacts {
+ remote_port: remotes.first().and_then(|(_, port)| *port),
+ remote_hosts: remotes.into_iter().map(|(host, _)| host).collect(),
server_networks,
- })
-}
-
-const CONFLICTING_DIRECTIVES: [&str; 12] = [
- "redirect-gateway",
- "redirect-private",
- "block-outside-dns",
- "block-ipv6",
- "register-dns",
- "dhcp-option",
- "route",
- "route-ipv6",
- "route-metric",
- "dev-node",
- "ip-win32",
- "resolv-retry",
-];
-
-/// Drops directives that would steal the system default route, DNS, or an
-/// existing TUN adapter, and legacy cipher negotiation that disables DCO.
-/// Inline certificates and keys are kept verbatim. Server pushes of the same
-/// options are ignored separately on the command line.
-#[must_use]
-pub fn sanitize_openvpn_profile(text: &str, windows: bool) -> String {
- let mut sanitized = String::new();
- let mut inline_block: Option = None;
- for line in text.lines() {
- let trimmed = line.trim();
- if let Some(open) = inline_block.as_deref() {
- sanitized.push_str(line);
- sanitized.push('\n');
- if trimmed.eq_ignore_ascii_case(&format!("{open}>")) {
- inline_block = None;
- }
- continue;
- }
- if let Some(tag) = trimmed
- .strip_prefix('<')
- .and_then(|rest| rest.strip_suffix('>'))
- {
- if !tag.starts_with('/') {
- inline_block = Some(tag.to_ascii_lowercase());
- }
- sanitized.push_str(line);
- sanitized.push('\n');
- continue;
- }
- let directive = trimmed
- .split_whitespace()
- .next()
- .unwrap_or_default()
- .trim_start_matches("--")
- .to_ascii_lowercase();
- // A legacy Windows `ncp-ciphers` list can include CBC even when the
- // helper sets AEAD-only `data-ciphers`. OpenVPN 2.7 then disables DCO.
- if CONFLICTING_DIRECTIVES.contains(&directive.as_str())
- || (windows && directive == "ncp-ciphers")
- {
- continue;
- }
- sanitized.push_str(line);
- sanitized.push('\n');
- }
- sanitized
+ };
+ Ok((facts, profile))
}
/// Helper-owned `OpenVPN` argv. Always includes `--route-noexec` and pins
/// `--script-security 2` after `--config`.
///
/// Level 2 is the minimum `OpenVPN` 2.7 accepts for its own `netsh` address
-/// setup. Level 0 blocks that command and the tunnel exits. The sanitized
-/// profile still has no `up` or `down` scripts, so user scripts are not run.
+/// setup. Level 0 blocks that command and the tunnel exits. The checked profile
+/// cannot name a script, so none is run.
///
/// `pinned_remote` goes **before** `--config` so it becomes the first entry in
/// `OpenVPN`'s connection list and wins over the profile's own `remote`. The
@@ -374,8 +263,10 @@ resolv-retry infinite
not a real certificate
";
- let sanitized = sanitize_openvpn_profile(source, true);
- assert!(sanitized.contains("remote vpn.example.com 443"));
+ let sanitized = CheckedProfile::parse(source)
+ .expect("profile")
+ .render(Path::new("/profiles"), true);
+ assert!(sanitized.contains("remote \"vpn.example.com\" \"443\""));
assert!(sanitized.contains("auth-user-pass"));
assert!(sanitized.contains("not a real certificate"));
assert!(!sanitized.contains("ncp-ciphers"));
@@ -417,7 +308,9 @@ not a real certificate
#[test]
fn linux_profile_keeps_its_cipher_negotiation() {
let source = "client\nremote vpn.example.com 443\nncp-ciphers AES-256-CBC\n";
- let sanitized = sanitize_openvpn_profile(source, false);
- assert!(sanitized.contains("ncp-ciphers AES-256-CBC"));
+ let sanitized = CheckedProfile::parse(source)
+ .expect("profile")
+ .render(Path::new("/profiles"), false);
+ assert!(sanitized.contains("ncp-ciphers \"AES-256-CBC\""));
}
}
diff --git a/crates/iran-split-clients/src/profile_parse.rs b/crates/iran-split-clients/src/profile_parse.rs
new file mode 100644
index 0000000..c30ec2a
--- /dev/null
+++ b/crates/iran-split-clients/src/profile_parse.rs
@@ -0,0 +1,616 @@
+//! Parses an imported `.ovpn` the way `OpenVPN` does, against an allowlist.
+//!
+//! The helper runs `OpenVPN` as root, so a profile must not be able to say
+//! anything `BiFlow` did not expect. A denylist over the raw text cannot
+//! promise that: `OpenVPN` accepts quoted directive names, `config` includes,
+//! `setenv opt`, loadable providers, and closes an inline block on a looser
+//! match than a line comparison. Everything here is therefore parsed once,
+//! checked against a list of directives a client profile needs, and written
+//! out again in a canonical form. The bytes `OpenVPN` reads are the ones that
+//! were checked (ADR 0141).
+
+use crate::OpenVpnProfileError;
+use std::path::Path;
+
+/// `OpenVPN` refuses a line of 256 bytes and splits inline data at that size.
+/// Staying below it keeps both parsers looking at the same lines.
+const MAX_LINE_BYTES: usize = 250;
+
+/// Directives a client profile may use. Anything else is refused by name.
+const ALLOWED_DIRECTIVES: &[&str] = &[
+ "allow-compression",
+ "allow-recursive-routing",
+ "auth",
+ "auth-nocache",
+ "auth-retry",
+ "auth-user-pass",
+ "bind",
+ "ca",
+ "cert",
+ "cipher",
+ "client",
+ "comp-lzo",
+ "comp-noadapt",
+ "compress",
+ "connect-retry",
+ "connect-retry-max",
+ "connect-timeout",
+ "crl-verify",
+ "data-ciphers",
+ "data-ciphers-fallback",
+ "dev",
+ "dev-type",
+ "disable-dco",
+ "disable-occ",
+ "ecdh-curve",
+ "explicit-exit-notify",
+ "extra-certs",
+ "fast-io",
+ "float",
+ "fragment",
+ "hand-window",
+ "http-proxy",
+ "http-proxy-option",
+ "http-proxy-retry",
+ "http-proxy-timeout",
+ "ifconfig",
+ "ifconfig-ipv6",
+ "ifconfig-nowarn",
+ "inactive",
+ "keepalive",
+ "key",
+ "key-direction",
+ "key-method",
+ "keysize",
+ "link-mtu",
+ "local",
+ "lport",
+ "max-packet-size",
+ "mlock",
+ "mssfix",
+ "mtu-disc",
+ "mtu-test",
+ "multihome",
+ "mute",
+ "mute-replay-warnings",
+ "ncp-ciphers",
+ "ncp-disable",
+ "nice",
+ "nobind",
+ "ns-cert-type",
+ "passtos",
+ "peer-fingerprint",
+ "persist-key",
+ "persist-local-ip",
+ "persist-remote-ip",
+ "persist-tun",
+ "ping",
+ "ping-exit",
+ "ping-restart",
+ "ping-timer-rem",
+ "pkcs12",
+ "port",
+ "proto",
+ "proto-force",
+ "pull",
+ "rcvbuf",
+ "remap-usr1",
+ "remote",
+ "remote-cert-eku",
+ "remote-cert-ku",
+ "remote-cert-tls",
+ "remote-random",
+ "remote-random-hostname",
+ "reneg-bytes",
+ "reneg-pkts",
+ "reneg-sec",
+ "replay-window",
+ "route-delay",
+ "route-nopull",
+ "rport",
+ "secret",
+ "server-poll-timeout",
+ "session-timeout",
+ "single-session",
+ "sndbuf",
+ "socket-flags",
+ "socks-proxy",
+ "socks-proxy-retry",
+ "static-challenge",
+ "tcp-nodelay",
+ "tls-auth",
+ "tls-cert-profile",
+ "tls-cipher",
+ "tls-ciphersuites",
+ "tls-client",
+ "tls-crypt",
+ "tls-crypt-v2",
+ "tls-exit",
+ "tls-groups",
+ "tls-timeout",
+ "tls-version-max",
+ "tls-version-min",
+ "topology",
+ "tran-window",
+ "tun-ipv6",
+ "tun-mtu",
+ "tun-mtu-extra",
+ "txqueuelen",
+ "verb",
+ "verify-client-cert",
+ "verify-hash",
+ "verify-x509-name",
+ "x509-username-field",
+];
+
+/// Accepted in an import and left out of the copy `OpenVPN` runs: they would
+/// take over routes or DNS, pick an existing adapter, set script variables,
+/// write files as root, or drop to another account.
+const DROPPED_DIRECTIVES: &[&str] = &[
+ "block-ipv6",
+ "block-outside-dns",
+ "dev-node",
+ "dhcp-option",
+ "dhcp-release",
+ "dhcp-renew",
+ "group",
+ "ifconfig-noexec",
+ "ignore-unknown-option",
+ "ip-win32",
+ "machine-readable-output",
+ "max-routes",
+ "pull-filter",
+ "push-peer-info",
+ "redirect-gateway",
+ "redirect-private",
+ "register-dns",
+ "resolv-retry",
+ "route",
+ "route-gateway",
+ "route-ipv6",
+ "route-method",
+ "route-metric",
+ "route-noexec",
+ "setenv",
+ "setenv-safe",
+ "show-net-up",
+ "status",
+ "status-version",
+ "suppress-timestamps",
+ "syslog",
+ "tap-sleep",
+ "user",
+ "win-sys",
+ "windows-driver",
+ "writepid",
+];
+
+/// Directives that may carry a path the profile author wrote relative to the
+/// profile's own directory.
+const FILE_DIRECTIVES: &[&str] = &[
+ "auth-user-pass",
+ "ca",
+ "cert",
+ "crl-verify",
+ "extra-certs",
+ "key",
+ "pkcs12",
+ "secret",
+ "tls-auth",
+ "tls-crypt",
+ "tls-crypt-v2",
+];
+
+const INLINE_BLOCKS: &[&str] = &[
+ "auth-user-pass",
+ "ca",
+ "cert",
+ "crl-verify",
+ "extra-certs",
+ "http-proxy-user-pass",
+ "key",
+ "peer-fingerprint",
+ "pkcs12",
+ "secret",
+ "tls-auth",
+ "tls-crypt",
+ "tls-crypt-v2",
+ "verify-hash",
+];
+
+/// The only directives `OpenVPN` documents inside ``.
+const CONNECTION_DIRECTIVES: &[&str] = &[
+ "bind",
+ "connect-retry",
+ "connect-retry-max",
+ "connect-timeout",
+ "explicit-exit-notify",
+ "float",
+ "fragment",
+ "http-proxy",
+ "http-proxy-option",
+ "link-mtu",
+ "local",
+ "lport",
+ "mssfix",
+ "mtu-disc",
+ "nobind",
+ "port",
+ "proto",
+ "remote",
+ "rport",
+ "socks-proxy",
+ "tun-mtu",
+ "tun-mtu-extra",
+];
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Entry {
+ Directive(Vec),
+ Inline { tag: String, lines: Vec },
+ Connection(Vec>),
+}
+
+/// A profile whose every directive is on the allowlist.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CheckedProfile {
+ entries: Vec,
+}
+
+impl CheckedProfile {
+ /// Parses and checks profile text.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`OpenVpnProfileError`] for a directive or inline block outside
+ /// the allowlist, an ambiguous or oversized line, or a missing remote.
+ pub fn parse(text: &str) -> Result {
+ let text = text.strip_prefix('\u{feff}').unwrap_or(text);
+ let mut entries = Vec::new();
+ let mut lines = text.lines();
+ while let Some(raw) = lines.next() {
+ let line = checked_line(raw)?;
+ if let Some(tag) = open_tag(line) {
+ entries.push(parse_block(tag, &mut lines)?);
+ continue;
+ }
+ if let Some(entry) = parse_directive(line, ALLOWED_DIRECTIVES)? {
+ entries.push(Entry::Directive(entry));
+ }
+ }
+ let profile = Self { entries };
+ if profile.remotes().is_empty() {
+ return Err(OpenVpnProfileError::NoRemote);
+ }
+ Ok(profile)
+ }
+
+ /// Every `remote` as host and optional port, in file order.
+ pub(crate) fn remotes(&self) -> Vec<(String, Option)> {
+ let mut found = Vec::new();
+ let mut collect = |tokens: &[String]| {
+ if tokens.first().is_some_and(|name| name == "remote") {
+ if let Some(host) = tokens.get(1) {
+ let port = tokens.get(2).and_then(|port| port.parse().ok());
+ found.push((host.clone(), port));
+ }
+ }
+ };
+ for entry in &self.entries {
+ match entry {
+ Entry::Directive(tokens) => collect(tokens),
+ Entry::Connection(directives) => {
+ directives.iter().for_each(|tokens| collect(tokens));
+ }
+ Entry::Inline { .. } => {}
+ }
+ }
+ found
+ }
+
+ /// The text `OpenVPN` runs. `base` is the imported profile's directory, so
+ /// relative key files keep resolving from the copy's new location.
+ #[must_use]
+ pub fn render(&self, base: &Path, windows: bool) -> String {
+ let mut text = String::new();
+ for entry in &self.entries {
+ match entry {
+ Entry::Directive(tokens) => {
+ // A legacy Windows `ncp-ciphers` list can include CBC even
+ // when the helper sets AEAD-only `data-ciphers`. `OpenVPN`
+ // 2.7 then disables DCO (ADR 0106).
+ if windows && tokens[0] == "ncp-ciphers" {
+ continue;
+ }
+ push_directive(&mut text, tokens, base);
+ }
+ Entry::Inline { tag, lines } => {
+ text.push_str(&["<", tag, ">\n"].concat());
+ for line in lines {
+ text.push_str(line);
+ text.push('\n');
+ }
+ text.push_str(&["", tag, ">\n"].concat());
+ }
+ Entry::Connection(directives) => {
+ text.push_str("\n");
+ for tokens in directives {
+ push_directive(&mut text, tokens, base);
+ }
+ text.push_str("\n");
+ }
+ }
+ }
+ text
+ }
+}
+
+fn push_directive(text: &mut String, tokens: &[String], base: &Path) {
+ text.push_str(&tokens[0]);
+ for (index, token) in tokens.iter().enumerate().skip(1) {
+ text.push_str(" \"");
+ let resolved = if index == 1 && FILE_DIRECTIVES.contains(&tokens[0].as_str()) {
+ resolve_file(token, base)
+ } else {
+ token.clone()
+ };
+ for character in resolved.chars() {
+ if matches!(character, '"' | '\\') {
+ text.push('\\');
+ }
+ text.push(character);
+ }
+ text.push('"');
+ }
+ text.push('\n');
+}
+
+fn resolve_file(token: &str, base: &Path) -> String {
+ if token == "[inline]" || Path::new(token).is_absolute() {
+ return token.to_owned();
+ }
+ base.join(token).to_string_lossy().into_owned()
+}
+
+fn checked_line(raw: &str) -> Result<&str, OpenVpnProfileError> {
+ if raw.len() > MAX_LINE_BYTES {
+ return Err(OpenVpnProfileError::LineTooLong);
+ }
+ if raw
+ .chars()
+ .any(|character| character.is_control() && character != '\t' && character != '\r')
+ {
+ return Err(OpenVpnProfileError::Ambiguous);
+ }
+ Ok(raw.trim())
+}
+
+/// `` on a line of its own. `OpenVPN` compares tags case-sensitively.
+fn open_tag(line: &str) -> Option<&str> {
+ line.strip_prefix('<')
+ .and_then(|rest| rest.strip_suffix('>'))
+ .filter(|tag| !tag.is_empty())
+}
+
+fn parse_block<'text>(
+ tag: &str,
+ lines: &mut impl Iterator- ,
+) -> Result {
+ let connection = tag == "connection";
+ if !connection && !INLINE_BLOCKS.contains(&tag) {
+ return Err(OpenVpnProfileError::ForbiddenDirective(tag.to_owned()));
+ }
+ let close = format!("{tag}>");
+ let mut directives = Vec::new();
+ let mut content = Vec::new();
+ for raw in lines {
+ let line = checked_line(raw)?;
+ if line == close {
+ return Ok(if connection {
+ Entry::Connection(directives)
+ } else {
+ Entry::Inline {
+ tag: tag.to_owned(),
+ lines: content,
+ }
+ });
+ }
+ // `OpenVPN` ends a block on a prefix match. Key material never starts
+ // with `<`, so any such line is an attempt to disagree about the end.
+ if line.starts_with('<') {
+ return Err(OpenVpnProfileError::Ambiguous);
+ }
+ if connection {
+ if let Some(tokens) = parse_directive(line, CONNECTION_DIRECTIVES)? {
+ directives.push(tokens);
+ }
+ } else {
+ content.push(line.to_owned());
+ }
+ }
+ Err(OpenVpnProfileError::UnterminatedBlock)
+}
+
+/// `None` for a blank line, a comment, or a directive the copy leaves out.
+fn parse_directive(
+ line: &str,
+ allowed: &[&str],
+) -> Result