mirror of
https://github.com/usestrix/firewall.git
synced 2026-11-09 05:19:35 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
caed7b374f |
No files matched your search
+1
-8
@@ -38,17 +38,14 @@ path = "src/main.rs"
|
||||
[[bin]]
|
||||
name = "firewall-service"
|
||||
path = "src/bin/firewall-service.rs"
|
||||
required-features = ["machine-wide"]
|
||||
|
||||
[[bin]]
|
||||
name = "firewall-tray"
|
||||
path = "src/bin/firewall-tray.rs"
|
||||
required-features = ["machine-wide"]
|
||||
|
||||
[[bin]]
|
||||
name = "firewall-uninstall"
|
||||
path = "src/bin/firewall-uninstall.rs"
|
||||
required-features = ["machine-wide"]
|
||||
|
||||
[[example]]
|
||||
name = "proxy-test"
|
||||
@@ -90,10 +87,6 @@ path = "tests/tpm.rs"
|
||||
name = "managers"
|
||||
path = "tests/managers.rs"
|
||||
|
||||
[features]
|
||||
# Builds the machine-wide binaries: the Windows service and tray, and the macOS uninstaller.
|
||||
machine-wide = []
|
||||
|
||||
[dependencies]
|
||||
clap = "4.6.6"
|
||||
directories = "6.0.0"
|
||||
@@ -125,7 +118,7 @@ schannel = "0.1.29"
|
||||
tokio = { version = "1.53.1", features = ["net"] }
|
||||
tracing-appender = "0.2.5"
|
||||
tray-icon = { version = "0.26.1", default-features = false }
|
||||
windows = { version = "0.62", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Cryptography", "Win32_System_Com", "Win32_System_Console", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
|
||||
windows = { version = "0.62", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Cryptography", "Win32_System_Com", "Win32_System_Environment", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
|
||||
windows-registry = "0.6.1"
|
||||
windows-service = "0.8.0"
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ pub static BUN: Manager = Manager {
|
||||
("https_proxy", PROXY),
|
||||
("HTTP_PROXY", PROXY),
|
||||
("HTTPS_PROXY", PROXY),
|
||||
("npm_config_registry", "http://{npm}/"),
|
||||
("npm_config_registry", "http://registry.npmjs.org/"),
|
||||
],
|
||||
args: &[],
|
||||
};
|
||||
@@ -14,7 +14,7 @@ pub static CARGO: Manager = Manager {
|
||||
"--config",
|
||||
"source.crates-io.replace-with=\"firewall\"",
|
||||
"--config",
|
||||
"source.firewall.registry=\"sparse+http://{cargo/index}/\"",
|
||||
"source.firewall.registry=\"sparse+http://index.crates.io/\"",
|
||||
],
|
||||
}],
|
||||
};
|
||||
@@ -6,6 +6,6 @@ pub static GEM: Manager = Manager {
|
||||
// gem has no variable for the source list, and gem env and gem sources reject the flags.
|
||||
args: &[Args {
|
||||
when: &["install", "update", "fetch"],
|
||||
flags: &["--clear-sources", "--source", "http://{gem}/"],
|
||||
flags: &["--clear-sources", "--source", "http://rubygems.org/"],
|
||||
}],
|
||||
};
|
||||
@@ -6,7 +6,7 @@ pub static GO: Manager = Manager {
|
||||
env: &[
|
||||
("HTTP_PROXY", PROXY),
|
||||
("http_proxy", PROXY),
|
||||
("GOPROXY", "http://{go}"),
|
||||
("GOPROXY", "http://proxy.golang.org"),
|
||||
("GOSUMDB", "off"),
|
||||
("GOFLAGS", "-mod=mod"),
|
||||
],
|
||||
|
||||
@@ -9,9 +9,6 @@ mod pipenv;
|
||||
mod pnpm;
|
||||
mod uv;
|
||||
|
||||
use crate::policies::registries::{host_of, BUILT_IN};
|
||||
use crate::FirewallConfig;
|
||||
|
||||
pub use bun::BUN;
|
||||
pub use cargo::CARGO;
|
||||
pub use gem::GEM;
|
||||
@@ -23,7 +20,7 @@ pub use pipenv::PIPENV;
|
||||
pub use pnpm::PNPM;
|
||||
pub use uv::UV;
|
||||
|
||||
pub const PYPI_SIMPLE: &str = "http://{pypi}/simple";
|
||||
pub const PYPI_SIMPLE: &str = "http://pypi.org/simple";
|
||||
|
||||
pub const PROXY: &str = "{proxy}";
|
||||
|
||||
@@ -34,9 +31,7 @@ pub struct Args {
|
||||
}
|
||||
|
||||
/// An https:// registry arrives as a CONNECT tunnel naming only the host, so each
|
||||
/// manager also overrides its registry URL to http://. `{npm}` and the like name a
|
||||
/// built-in registry, and expand to its first mirror, if any, without the scheme;
|
||||
/// `{host:npm}` to just its host.
|
||||
/// manager also overrides its registry URL to http://.
|
||||
pub struct Manager {
|
||||
pub command: &'static str,
|
||||
pub env: &'static [(&'static str, &'static str)],
|
||||
@@ -47,36 +42,23 @@ pub static MANAGERS: &[&Manager] =
|
||||
&[&NPM, &PIP, &PIP3, &CARGO, &GO, &GEM, &UV, &PDM, &PIPENV, &PNPM, &BUN];
|
||||
|
||||
/// Every manager's variables, so whichever the command starts is pointed at the firewall.
|
||||
pub fn variables(proxy: &str, config: &FirewallConfig) -> Vec<(String, String)> {
|
||||
pub fn variables(proxy: &str) -> Vec<(String, String)> {
|
||||
let env = MANAGERS.iter().flat_map(|manager| manager.env);
|
||||
env.map(|(key, value)| (key.to_string(), expand(value, proxy, config))).collect()
|
||||
env.map(|(key, value)| (key.to_string(), expand(value, proxy))).collect()
|
||||
}
|
||||
|
||||
pub fn arguments(
|
||||
proxy: &str,
|
||||
config: &FirewallConfig,
|
||||
manager: &Manager,
|
||||
typed: &[String],
|
||||
) -> Vec<String> {
|
||||
pub fn arguments(proxy: &str, manager: &Manager, typed: &[String]) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for args in manager.args {
|
||||
let wanted =
|
||||
args.when.is_empty() || typed.iter().any(|arg| args.when.contains(&arg.as_str()));
|
||||
if wanted {
|
||||
out.extend(args.flags.iter().map(|flag| expand(flag, proxy, config)));
|
||||
out.extend(args.flags.iter().map(|flag| expand(flag, proxy)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn expand(value: &str, proxy: &str, config: &FirewallConfig) -> String {
|
||||
let mut value = value.replace(PROXY, proxy);
|
||||
for registry in BUILT_IN {
|
||||
let mirror = config.registries.get(registry.name()).and_then(|mirrors| mirrors.first());
|
||||
let upstream = mirror.map_or(registry.upstream, String::as_str);
|
||||
let address = upstream.trim_start_matches("https://").trim_end_matches('/');
|
||||
value = value.replace(&format!("{{{}}}", registry.name()), address);
|
||||
value = value.replace(&format!("{{host:{}}}", registry.name()), host_of(upstream));
|
||||
}
|
||||
value
|
||||
fn expand(value: &str, proxy: &str) -> String {
|
||||
value.replace(PROXY, proxy)
|
||||
}
|
||||
@@ -5,7 +5,7 @@ pub static NPM: Manager = Manager {
|
||||
env: &[
|
||||
("npm_config_proxy", PROXY),
|
||||
("npm_config_https_proxy", PROXY),
|
||||
("npm_config_registry", "http://{npm}/"),
|
||||
("npm_config_registry", "http://registry.npmjs.org/"),
|
||||
],
|
||||
args: &[],
|
||||
};
|
||||
@@ -4,7 +4,7 @@ use super::{Manager, PROXY, PYPI_SIMPLE};
|
||||
const PIP_ENV: &[(&str, &str)] = &[
|
||||
("PIP_PROXY", PROXY),
|
||||
("PIP_INDEX_URL", PYPI_SIMPLE),
|
||||
("PIP_TRUSTED_HOST", "{host:pypi} {host:pypi-files}"),
|
||||
("PIP_TRUSTED_HOST", "pypi.org files.pythonhosted.org"),
|
||||
("PIP_DISABLE_PIP_VERSION_CHECK", "1"),
|
||||
];
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ pub static PIPENV: Manager = Manager {
|
||||
("https_proxy", PROXY),
|
||||
("PIPENV_PYPI_MIRROR", PYPI_SIMPLE),
|
||||
// pipenv installs through pip, which skips a plaintext index on a host it doesn't trust.
|
||||
("PIP_TRUSTED_HOST", "{host:pypi} {host:pypi-files}"),
|
||||
("PIP_TRUSTED_HOST", "pypi.org files.pythonhosted.org"),
|
||||
],
|
||||
args: &[],
|
||||
};
|
||||
@@ -6,7 +6,7 @@ pub static PNPM: Manager = Manager {
|
||||
env: &[
|
||||
("pnpm_config_proxy", PROXY),
|
||||
("pnpm_config_https_proxy", PROXY),
|
||||
("pnpm_config_registry", "http://{npm}/"),
|
||||
("pnpm_config_registry", "http://registry.npmjs.org/"),
|
||||
],
|
||||
args: &[],
|
||||
};
|
||||
@@ -1,12 +1,9 @@
|
||||
pub mod forward;
|
||||
pub mod managers;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
pub use forward::spawn;
|
||||
pub use managers::*;
|
||||
|
||||
use crate::FirewallConfig;
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
@@ -22,12 +19,12 @@ impl Invocation {
|
||||
}
|
||||
|
||||
/// What the program is run with: the typed arguments plus any its manager needs.
|
||||
pub fn arguments(&self, proxy: &str, config: &FirewallConfig) -> Vec<String> {
|
||||
pub fn arguments(&self, proxy: &str) -> Vec<String> {
|
||||
let mut args = self.args.clone();
|
||||
let Some(manager) = MANAGERS.iter().find(|manager| manager.command == self.program) else {
|
||||
return args;
|
||||
};
|
||||
let ours = managers::arguments(proxy, config, manager, &args);
|
||||
let ours = managers::arguments(proxy, manager, &args);
|
||||
// Anything after `--` belongs to another program, so ours go before it.
|
||||
let at = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
|
||||
args.splice(at..at, ours);
|
||||
@@ -35,28 +32,17 @@ impl Invocation {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(
|
||||
port: u16,
|
||||
config: &FirewallConfig,
|
||||
invocation: &Invocation,
|
||||
dir: Option<&Path>,
|
||||
) -> std::io::Result<i32> {
|
||||
pub fn run(port: u16, invocation: &Invocation, dir: Option<&Path>) -> std::io::Result<i32> {
|
||||
let proxy = crate::local_url(port, "");
|
||||
let program = resolve(&invocation.program)?;
|
||||
let mut command = Command::new(&program);
|
||||
command.args(invocation.arguments(&proxy, config));
|
||||
let mut command = Command::new(resolve(&invocation.program)?);
|
||||
command.args(invocation.arguments(&proxy));
|
||||
if let Some(dir) = dir {
|
||||
command.current_dir(dir);
|
||||
}
|
||||
for (key, value) in managers::variables(&proxy, config) {
|
||||
for (key, value) in managers::variables(&proxy) {
|
||||
command.env(key, value);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
windows::prepare();
|
||||
let status = command.status();
|
||||
#[cfg(windows)]
|
||||
let status = status.map_err(|error| windows::explain(error, &program));
|
||||
Ok(status?.code().unwrap_or(1))
|
||||
Ok(command.status()?.code().unwrap_or(1))
|
||||
}
|
||||
|
||||
// Command::new only finds .exe on Windows; npm, pnpm and gem are .cmd shims found via PATHEXT.
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::path::Path;
|
||||
use std::sync::Once;
|
||||
use tracing::debug;
|
||||
use windows::core::{BOOL, PCWSTR};
|
||||
use windows::Win32::System::Console::{SetConsoleCtrlHandler, CTRL_BREAK_EVENT, CTRL_C_EVENT};
|
||||
use windows::Win32::System::JobObjects::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
|
||||
SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
};
|
||||
use windows::Win32::System::Threading::GetCurrentProcess;
|
||||
|
||||
/// Called before spawning, so the manager behaves as it would run from the shell directly.
|
||||
/// Once per process: a caller may run several managers.
|
||||
pub fn prepare() {
|
||||
static PREPARED: Once = Once::new();
|
||||
PREPARED.call_once(|| {
|
||||
// The console sends Ctrl+C to the manager too. Exiting first would hand the prompt back
|
||||
// while a .cmd shim still asks "Terminate batch job (Y/N)?", so wait for its exit instead.
|
||||
// A handler, unlike ignoring the signal outright, is not inherited by the manager.
|
||||
let _ = unsafe { SetConsoleCtrlHandler(Some(ignore_interrupt), true) };
|
||||
if let Err(error) = kill_children_on_exit() {
|
||||
debug!(%error, "the manager may outlive the firewall");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
unsafe extern "system" fn ignore_interrupt(event: u32) -> BOOL {
|
||||
(event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT).into()
|
||||
}
|
||||
|
||||
/// Joins a job that kills what is left in it once the firewall exits, even if killed itself.
|
||||
/// The manager inherits the job when spawned, as do its own children.
|
||||
fn kill_children_on_exit() -> windows::core::Result<()> {
|
||||
let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
|
||||
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
// Never closed: the handle closing as the firewall exits is what kills the rest.
|
||||
let job = unsafe { CreateJobObjectW(None, PCWSTR::null())? };
|
||||
unsafe {
|
||||
SetInformationJobObject(
|
||||
job,
|
||||
JobObjectExtendedLimitInformation,
|
||||
(&raw const limits).cast(),
|
||||
size_of_val(&limits) as u32,
|
||||
)?
|
||||
};
|
||||
unsafe { AssignProcessToJobObject(job, GetCurrentProcess()) }
|
||||
}
|
||||
|
||||
/// Rust refuses to pass a line break to a batch file, where it would cut the command short.
|
||||
pub fn explain(error: Error, program: &Path) -> Error {
|
||||
let batch = program
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat"));
|
||||
if !batch || error.kind() != ErrorKind::InvalidInput {
|
||||
return error;
|
||||
}
|
||||
let name = program.file_name().unwrap_or(program.as_os_str()).to_string_lossy();
|
||||
Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("{name} is a batch file, which cannot be passed an argument with a line break"),
|
||||
)
|
||||
}
|
||||
+28
-86
@@ -1,32 +1,31 @@
|
||||
use crate::policies::registries::{host_of, BUILT_IN};
|
||||
use crate::policies::registries::{Registry, BUILT_IN};
|
||||
use directories::ProjectDirs;
|
||||
use rama::net::uri::Uri;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Map, Value};
|
||||
use serde_json::{Map, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::num::{NonZeroU16, NonZeroU64};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub const DEFAULT_PORT: u16 = 8080;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct FirewallConfig {
|
||||
pub port: NonZeroU16,
|
||||
pub port: u16,
|
||||
/// Allow a package when a filter could not check it.
|
||||
pub fail_open: bool,
|
||||
/// 0 turns the age check off.
|
||||
pub min_age_hours: u64,
|
||||
pub denylist: DenylistSource,
|
||||
/// Packages exempt from the age check, by ecosystem: `{"npm": [{"name": "left-pad"}]}`.
|
||||
/// Packages never screened, by ecosystem: `{"npm": [{"name": "left-pad"}]}`.
|
||||
pub allow: HashMap<String, Vec<AllowedPackage>>,
|
||||
pub telemetry: bool,
|
||||
/// Mirrors laid out like a built-in registry, by its name: `{"npm": ["https://npm.example.com/"]}`.
|
||||
pub registries: HashMap<String, Vec<String>>,
|
||||
/// Not describable in the file yet, so this is always the built-in table.
|
||||
#[serde(skip)]
|
||||
pub registries: Vec<&'static Registry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AllowedPackage {
|
||||
pub name: String,
|
||||
@@ -41,19 +40,19 @@ pub struct DenylistSource {
|
||||
pub base: String,
|
||||
/// Polled for a new commit, which re-fetches every list in use.
|
||||
pub revision: String,
|
||||
pub poll_secs: NonZeroU64,
|
||||
pub poll_secs: u64,
|
||||
}
|
||||
|
||||
impl Default for FirewallConfig {
|
||||
fn default() -> Self {
|
||||
FirewallConfig {
|
||||
port: NonZeroU16::new(DEFAULT_PORT).unwrap(),
|
||||
port: DEFAULT_PORT,
|
||||
fail_open: true,
|
||||
min_age_hours: 24,
|
||||
denylist: DenylistSource::default(),
|
||||
allow: HashMap::new(),
|
||||
telemetry: true,
|
||||
registries: HashMap::new(),
|
||||
registries: BUILT_IN.to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,7 +63,7 @@ impl Default for DenylistSource {
|
||||
base: "https://raw.githubusercontent.com/usestrix/firewall-blocklist/main".into(),
|
||||
revision: "https://api.github.com/repos/usestrix/firewall-blocklist/commits/main"
|
||||
.into(),
|
||||
poll_secs: NonZeroU64::new(10).unwrap(),
|
||||
poll_secs: 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,8 +87,7 @@ impl FirewallConfig {
|
||||
};
|
||||
let invalid = |e| Error::new(ErrorKind::InvalidData, format!("{}: {e}", path.display()));
|
||||
let layer: Value = serde_json::from_str(&text).map_err(invalid)?;
|
||||
let config = FirewallConfig::deserialize(&layer).map_err(invalid)?;
|
||||
check(&config).map_err(|e| Error::new(ErrorKind::InvalidData, format!("{}: {e}", path.display())))?;
|
||||
FirewallConfig::deserialize(&layer).map_err(invalid)?;
|
||||
let Value::Object(layer) = layer else {
|
||||
unreachable!("a config parses only from an object");
|
||||
};
|
||||
@@ -99,7 +97,19 @@ impl FirewallConfig {
|
||||
}
|
||||
|
||||
pub fn local_url(&self, path: &str) -> String {
|
||||
crate::local_url(self.port.get(), path)
|
||||
crate::local_url(self.port, path)
|
||||
}
|
||||
|
||||
/// Without building a `Firewall`, which needs a runtime.
|
||||
pub fn hosts(&self) -> Vec<&'static str> {
|
||||
let mut hosts: Vec<&'static str> = Vec::new();
|
||||
for registry in &self.registries {
|
||||
let host = registry.host();
|
||||
if !hosts.contains(&host) {
|
||||
hosts.push(host);
|
||||
}
|
||||
}
|
||||
hosts
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,71 +129,3 @@ fn merge(base: &mut Map<String, Value>, top: Map<String, Value>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds an `allow` entry to the file, leaving the rest of it as written.
|
||||
pub fn allow(path: &Path, eco: &str, name: &str, version: Option<&str>) -> std::io::Result<()> {
|
||||
let invalid = |e: String| Error::new(ErrorKind::InvalidData, format!("{}: {e}", path.display()));
|
||||
let mut config = match std::fs::read_to_string(path) {
|
||||
Ok(text) => serde_json::from_str(&text).map_err(|e| invalid(e.to_string()))?,
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => json!({}),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if !config.is_object() {
|
||||
return Err(invalid("not an object".into()));
|
||||
}
|
||||
let entry = json!({ "name": name, "version": version });
|
||||
let entries = &mut config["allow"][eco];
|
||||
if entries.is_null() {
|
||||
*entries = Value::Array(Vec::new());
|
||||
}
|
||||
let Some(entries) = entries.as_array_mut() else {
|
||||
return Err(invalid(format!("allow.{eco} is not a list")));
|
||||
};
|
||||
if !entries.contains(&entry) {
|
||||
entries.push(entry);
|
||||
}
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
std::fs::write(path, serde_json::to_string_pretty(&config)?)
|
||||
}
|
||||
|
||||
/// What serde's types cannot say.
|
||||
fn check(config: &FirewallConfig) -> Result<(), String> {
|
||||
// `Duration::hours` panics past this.
|
||||
if config.min_age_hours > time::Duration::MAX.whole_hours() as u64 {
|
||||
return Err(format!("{} hours is too long", config.min_age_hours));
|
||||
}
|
||||
for eco in config.allow.keys() {
|
||||
if !BUILT_IN.iter().any(|r| r.eco == eco) {
|
||||
return Err(format!("unknown ecosystem {eco:?} in allow"));
|
||||
}
|
||||
}
|
||||
for url in [&config.denylist.base, &config.denylist.revision] {
|
||||
if parse_url(url, &["http", "https"]).is_none() {
|
||||
return Err(format!("{url:?} is not an http(s) URL"));
|
||||
}
|
||||
}
|
||||
for (name, mirrors) in &config.registries {
|
||||
if !BUILT_IN.iter().any(|r| r.name() == name) {
|
||||
return Err(format!("no built-in registry is named {name}"));
|
||||
}
|
||||
if let Some(url) = mirrors.iter().find(|url| !is_mirror(url)) {
|
||||
return Err(format!("{url}: a mirror is an https:// URL ending in /"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// No port or userinfo, as `host_of` is what gets intercepted.
|
||||
fn is_mirror(url: &str) -> bool {
|
||||
let Some(uri) = parse_url(url, &["https"]) else { return false };
|
||||
let bare_host = uri.host_str().is_some_and(|host| host == host_of(url));
|
||||
bare_host && uri.query().is_none() && uri.fragment().is_none() && url.ends_with('/')
|
||||
}
|
||||
|
||||
fn parse_url(url: &str, schemes: &[&str]) -> Option<Uri> {
|
||||
let uri = Uri::parse(url).ok()?;
|
||||
let has_host = uri.host_str().is_some_and(|host| !host.is_empty());
|
||||
(has_host && schemes.contains(&uri.scheme_str()?)).then_some(uri)
|
||||
}
|
||||
+7
-28
@@ -9,7 +9,6 @@ use std::collections::HashMap;
|
||||
|
||||
pub struct Firewall {
|
||||
pub config: FirewallConfig,
|
||||
registries: Vec<&'static Registry>,
|
||||
patterns: HashMap<&'static str, Vec<Regex>>,
|
||||
filters: Vec<Box<dyn Filter>>,
|
||||
}
|
||||
@@ -22,19 +21,18 @@ impl Default for Firewall {
|
||||
|
||||
impl Firewall {
|
||||
pub fn new(config: FirewallConfig) -> Self {
|
||||
let registries = with_mirrors(&config.registries);
|
||||
let mut patterns = HashMap::new();
|
||||
for registry in ®istries {
|
||||
for registry in &config.registries {
|
||||
let compiled = registry.patterns.iter().map(|p| Regex::new(p.re).expect(p.re));
|
||||
patterns.insert(registry.prefix, compiled.collect());
|
||||
}
|
||||
let ecosystems = registries.iter().map(|r| r.osv_name);
|
||||
let ecosystems = config.registries.iter().map(|r| r.osv_name);
|
||||
let denylist = Denylist::new(config.denylist.clone(), ecosystems);
|
||||
let mut filters: Vec<Box<dyn Filter>> = vec![Box::new(denylist), Box::new(Osv)];
|
||||
if config.min_age_hours > 0 {
|
||||
filters.push(Box::new(Age::new(config.min_age_hours)));
|
||||
}
|
||||
Firewall { config, registries, patterns, filters }
|
||||
Firewall { config, patterns, filters }
|
||||
}
|
||||
|
||||
pub fn match_on<'a>(
|
||||
@@ -42,27 +40,20 @@ impl Firewall {
|
||||
url: &'a str,
|
||||
key: fn(&Registry) -> &'static str,
|
||||
) -> Option<(&'static Registry, &'a str)> {
|
||||
self.registries.iter().find_map(|r| url.strip_prefix(key(r)).map(|rest| (*r, rest)))
|
||||
self.config.registries.iter().find_map(|r| url.strip_prefix(key(r)).map(|rest| (*r, rest)))
|
||||
}
|
||||
|
||||
pub fn hosts(&self) -> Vec<&'static str> {
|
||||
let mut hosts: Vec<&'static str> = Vec::new();
|
||||
for registry in &self.registries {
|
||||
let host = registry.host();
|
||||
if !hosts.contains(&host) {
|
||||
hosts.push(host);
|
||||
}
|
||||
}
|
||||
hosts
|
||||
self.config.hosts()
|
||||
}
|
||||
|
||||
pub fn is_https_url(&self, url: &str) -> bool {
|
||||
let host = host_of(url);
|
||||
self.registries.iter().any(|r| r.upstream.starts_with("https://") && r.host() == host)
|
||||
self.config.registries.iter().any(|r| r.upstream.starts_with("https://") && r.host() == host)
|
||||
}
|
||||
|
||||
pub fn is_index_url(&self, url: &str) -> bool {
|
||||
self.registries.iter().any(|r| r.index && r.host() == host_of(url))
|
||||
self.config.registries.iter().any(|r| r.index && r.host() == host_of(url))
|
||||
}
|
||||
|
||||
pub fn resolve(&self, registry: &'static Registry, rest: &str) -> Resolved {
|
||||
@@ -73,15 +64,3 @@ impl Firewall {
|
||||
&self.filters
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-ins, then a copy of one per mirror. Leaked, as a `Registry` is `'static` everywhere.
|
||||
fn with_mirrors(mirrors: &HashMap<String, Vec<String>>) -> Vec<&'static Registry> {
|
||||
let mut registries = BUILT_IN.to_vec();
|
||||
for built_in in BUILT_IN {
|
||||
for upstream in mirrors.get(built_in.name()).into_iter().flatten() {
|
||||
let upstream = upstream.clone().leak();
|
||||
registries.push(Box::leak(Box::new(Registry { upstream, ..(*built_in).clone() })));
|
||||
}
|
||||
}
|
||||
registries
|
||||
}
|
||||
+2
-3
@@ -73,14 +73,13 @@ fn serve() -> ! {
|
||||
fn run(invocation: Invocation) -> ! {
|
||||
telemetry::set_mode("wrapper");
|
||||
let command = &invocation.program;
|
||||
let config = load();
|
||||
let port = match aliasing::spawn(0, config.clone()) {
|
||||
let port = match aliasing::spawn(0, load()) {
|
||||
Ok(port) => port,
|
||||
Err(e) => fail("spawn", &format!("could not start the firewall: {e}")),
|
||||
};
|
||||
info!(url = %firewall::local_url(port, ""), "firewall listening");
|
||||
|
||||
let result = aliasing::run(port, &config, &invocation, None);
|
||||
let result = aliasing::run(port, &invocation, None);
|
||||
telemetry::flush();
|
||||
match result {
|
||||
Ok(code) => exit(code),
|
||||
|
||||
@@ -4,7 +4,7 @@ mod uninstall;
|
||||
|
||||
pub use uninstall::uninstall;
|
||||
|
||||
use crate::config::{self, FirewallConfig};
|
||||
use crate::config::FirewallConfig;
|
||||
use crate::{blocks, mitm, telemetry};
|
||||
use crate::Firewall;
|
||||
use rama::bytes::Bytes;
|
||||
@@ -22,7 +22,6 @@ use rama::net::apple::networkextension::{transparent_proxy_ffi, NwTcpStream, Tcp
|
||||
use rama::rt::Executor;
|
||||
use rama::telemetry::tracing::apple::oslog::{OsLogLayer, Privacy};
|
||||
use rama::{Layer, Service};
|
||||
use serde::Deserialize;
|
||||
use std::convert::Infallible;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -60,11 +59,7 @@ impl TransparentProxyHandler for Handler {
|
||||
Some(Bytes::from(match message.as_str() {
|
||||
"ca" => self.ca.pem.clone(),
|
||||
"blocks" => serde_json::to_string(&blocks::take()).expect("blocks serialize"),
|
||||
other => match other.strip_prefix("allow ").map(allow) {
|
||||
Some(Ok(())) => "ok".to_owned(),
|
||||
Some(Err(error)) => format!("error: {error}"),
|
||||
None => format!("error: unknown message {other}"),
|
||||
},
|
||||
other => format!("error: unknown message {other}"),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -123,20 +118,6 @@ fn handler(exec: Executor) -> Result<Handler, BoxError> {
|
||||
Ok(Handler { ca, hosts, service })
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AllowRequest {
|
||||
eco: String,
|
||||
name: String,
|
||||
version: Option<String>,
|
||||
}
|
||||
|
||||
/// Takes effect when the provider restarts, which rebuilds it from the config.
|
||||
fn allow(request: &str) -> Result<(), BoxError> {
|
||||
let request: AllowRequest = serde_json::from_str(request)?;
|
||||
config::allow(CONFIG_FILE.as_ref(), &request.eco, &request.name, request.version.as_deref())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// stderr is invisible in a system extension, so events go to the unified log:
|
||||
/// `log stream --predicate 'subsystem == "com.usestrix.firewall"'`.
|
||||
fn init(_config: Option<&TransparentProxyInitConfig>) -> bool {
|
||||
|
||||
@@ -143,7 +143,7 @@ pub fn describe(advisories: &[&Advisory]) -> String {
|
||||
|
||||
/// A failed fetch leaves the last good list in place; a list that never loaded is retried every tick.
|
||||
async fn watch(source: DenylistSource, lists: Arc<Lists>) {
|
||||
let period = Duration::from_secs(source.poll_secs.get());
|
||||
let period = Duration::from_secs(source.poll_secs);
|
||||
let mut seen = revision(&source, None).await;
|
||||
loop {
|
||||
tokio::time::sleep(period).await;
|
||||
|
||||
@@ -25,18 +25,16 @@ pub trait Filter: Send + Sync {
|
||||
}
|
||||
|
||||
/// Asks every filter. A `Deny` wins; failing that, the first filter that could not tell.
|
||||
/// An allowed package skips only the age check, so malware is never let through.
|
||||
pub async fn consult(
|
||||
firewall: &Firewall,
|
||||
registry: &'static Registry,
|
||||
pkg: &Package,
|
||||
) -> Option<(&'static str, Verdict)> {
|
||||
let allowed = allowed(firewall, registry, pkg);
|
||||
if allowed(firewall, registry, pkg) {
|
||||
return None;
|
||||
}
|
||||
let mut unsure = None;
|
||||
for filter in firewall.filters() {
|
||||
if allowed && filter.name() == "age" {
|
||||
continue;
|
||||
}
|
||||
match filter.check(registry, pkg).await {
|
||||
Verdict::Allow => continue,
|
||||
Verdict::Deny(reason) => return Some((filter.name(), Verdict::Deny(reason))),
|
||||
|
||||
@@ -36,7 +36,7 @@ pub struct Pattern {
|
||||
}
|
||||
|
||||
/// Requests to the local server match on `prefix`; intercepted URLs match on `upstream`.
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug)]
|
||||
pub struct Registry {
|
||||
pub prefix: &'static str,
|
||||
pub eco: &'static str,
|
||||
@@ -52,7 +52,7 @@ pub struct Registry {
|
||||
}
|
||||
|
||||
/// A URL to fetch and a JSON pointer to the timestamp in its reply.
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug)]
|
||||
pub struct Published {
|
||||
pub url: &'static str,
|
||||
pub pointer: &'static str,
|
||||
@@ -63,11 +63,6 @@ impl Registry {
|
||||
pub fn host(&self) -> &'static str {
|
||||
host_of(self.upstream)
|
||||
}
|
||||
|
||||
/// What the config file calls it.
|
||||
pub fn name(&self) -> &'static str {
|
||||
self.prefix.trim_matches('/')
|
||||
}
|
||||
}
|
||||
|
||||
/// The host of an https:// URL, with the path dropped.
|
||||
|
||||
@@ -15,7 +15,7 @@ use std::sync::Arc;
|
||||
use tracing::{info, info_span, warn, Instrument};
|
||||
|
||||
pub fn serve(config: FirewallConfig) -> std::io::Result<()> {
|
||||
let bound = std::net::TcpListener::bind(("127.0.0.1", config.port.get()))?;
|
||||
let bound = std::net::TcpListener::bind(("127.0.0.1", config.port))?;
|
||||
bound.set_nonblocking(true)?;
|
||||
crate::runtime()?.block_on(async move {
|
||||
let firewall = Arc::new(Firewall::new(config));
|
||||
|
||||
+6
-58
@@ -7,7 +7,7 @@ use firewall::{Firewall, FirewallConfig};
|
||||
fn a_file_only_has_to_set_what_it_changes() {
|
||||
let config: FirewallConfig = serde_json::from_str(r#"{"fail_open": false}"#).expect("parses");
|
||||
assert!(!config.fail_open);
|
||||
assert_eq!(config.port.get(), firewall::DEFAULT_PORT);
|
||||
assert_eq!(config.port, firewall::DEFAULT_PORT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -15,28 +15,6 @@ fn a_misspelled_setting_is_an_error() {
|
||||
assert!(serde_json::from_str::<FirewallConfig>(r#"{"fail-open": false}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonsense_values_are_errors() {
|
||||
let file = std::env::temp_dir().join(format!("firewall-nonsense-{}.json", std::process::id()));
|
||||
for bad in [
|
||||
r#"{"allow": {"nmp": [{"name": "left-pad"}]}}"#,
|
||||
r#"{"denylist": {"poll_secs": 0}}"#,
|
||||
r#"{"denylist": {"base": "raw.githubusercontent.com/usestrix"}}"#,
|
||||
r#"{"denylist": {"revision": "https://"}}"#,
|
||||
r#"{"port": 0}"#,
|
||||
r#"{"min_age_hours": 18446744073709551615}"#,
|
||||
r#"{"registries": {"npm": ["http://npm.example.com/"]}}"#,
|
||||
r#"{"registries": {"npm": ["https://npm.example.com"]}}"#,
|
||||
r#"{"registries": {"npm": ["https://npm.example.com:8443/"]}}"#,
|
||||
r#"{"registries": {"npm": ["https://[email protected]/"]}}"#,
|
||||
r#"{"registries": {"npm": ["https://npm.example.com/?a=/"]}}"#,
|
||||
] {
|
||||
std::fs::write(&file, bad).expect("write");
|
||||
assert!(FirewallConfig::load_from(std::slice::from_ref(&file)).is_err(), "{bad}");
|
||||
}
|
||||
std::fs::remove_file(&file).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_config_lives_under_the_config_directory() {
|
||||
let path = path().expect("a home directory");
|
||||
@@ -61,29 +39,14 @@ fn a_later_file_wins_and_allow_lists_add_up() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_mirror_is_screened_like_the_registry_it_copies() {
|
||||
let config = r#"{"registries": {"npm": ["https://npm.example.com/"]}}"#;
|
||||
let firewall = Firewall::new(serde_json::from_str(config).expect("parses"));
|
||||
assert!(firewall.hosts().contains(&"npm.example.com"));
|
||||
let url = "https://npm.example.com/left-pad/-/left-pad-1.3.0.tgz";
|
||||
let (registry, rest) = firewall.match_on(url, |r| r.upstream).expect("the mirror");
|
||||
assert_eq!(firewall.resolve(registry, rest).pkg.map(|p| p.label()), Some("[email protected]".into()));
|
||||
let unknown = std::env::temp_dir().join(format!("firewall-mirror-{}.json", std::process::id()));
|
||||
std::fs::write(&unknown, r#"{"registries": {"nmp": ["https://npm.example.com/"]}}"#).expect("write");
|
||||
let loaded = FirewallConfig::load_from(std::slice::from_ref(&unknown));
|
||||
std::fs::remove_file(&unknown).ok();
|
||||
assert!(loaded.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_allowed_version_is_still_checked_for_malware() {
|
||||
// The unreachable denylist shows that it still runs.
|
||||
async fn an_allowed_version_skips_the_filters() {
|
||||
// An unreachable denylist would otherwise leave the package unchecked.
|
||||
let config = r#"{"allow": {"go": [{"name": "golang.org/x/net", "version": "v0.20.0"}]}, "denylist": {"base": "http://127.0.0.1:1"}}"#;
|
||||
let firewall = Firewall::new(serde_json::from_str(config).expect("parses"));
|
||||
let (registry, _) = firewall.match_on("/go/golang.org/x/net/@v/list", |r| r.prefix).expect("go");
|
||||
let pkg = Package { name: "golang.org/x/net".into(), version: Some("0.20.0".into()) };
|
||||
let verdict = consult(&firewall, registry, &pkg).await;
|
||||
assert_eq!(verdict.map(|(filter, _)| filter), Some("denylist"));
|
||||
let pkg = |version: &str| Package { name: "golang.org/x/net".into(), version: Some(version.into()) };
|
||||
assert!(consult(&firewall, registry, &pkg("0.20.0")).await.is_none());
|
||||
assert!(consult(&firewall, registry, &pkg("0.21.0")).await.is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -94,18 +57,3 @@ async fn failing_closed_blocks_what_could_not_be_checked() {
|
||||
let blocked = screen(url, &firewall).await.unwrap_or_default();
|
||||
assert!(blocked.contains("could not be checked"), "{blocked:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowing_keeps_the_rest_of_the_file() {
|
||||
let path = std::env::temp_dir().join(format!("firewall-allow-{}.json", std::process::id()));
|
||||
std::fs::write(&path, r#"{"fail_open": false}"#).expect("write");
|
||||
for _ in 0..2 {
|
||||
firewall::config::allow(&path, "npm", "left-pad", Some("1.3.0")).expect("allow");
|
||||
}
|
||||
let text = std::fs::read_to_string(&path).expect("read");
|
||||
std::fs::remove_file(&path).ok();
|
||||
let config: FirewallConfig = serde_json::from_str(&text).expect("parses");
|
||||
assert!(!config.fail_open);
|
||||
assert_eq!(config.allow["npm"].len(), 1);
|
||||
assert_eq!(config.allow["npm"][0].version.as_deref(), Some("1.3.0"));
|
||||
}
|
||||
+13
-26
@@ -1,11 +1,11 @@
|
||||
use firewall::aliasing::managers::*;
|
||||
use firewall::aliasing::Invocation;
|
||||
use firewall::{Firewall, FirewallConfig};
|
||||
use firewall::Firewall;
|
||||
|
||||
#[test]
|
||||
fn arguments_after_a_double_dash_reach_the_program() {
|
||||
let typed = ["run", "--", "--release"].map(String::from).to_vec();
|
||||
let args = Invocation::new("cargo".into(), typed).arguments("http://127.0.0.1:9000", &FirewallConfig::default());
|
||||
let args = Invocation::new("cargo".into(), typed).arguments("http://127.0.0.1:9000");
|
||||
assert_eq!(args.first().map(String::as_str), Some("run"));
|
||||
assert_eq!(args[args.len() - 2..], ["--", "--release"]);
|
||||
}
|
||||
@@ -13,23 +13,12 @@ fn arguments_after_a_double_dash_reach_the_program() {
|
||||
#[test]
|
||||
fn recipes_expand_into_the_environment() {
|
||||
let var = |name: &str, value: &str| (name.to_string(), value.to_string());
|
||||
let config = FirewallConfig::default();
|
||||
let npm = variables("http://127.0.0.1:9000", &config);
|
||||
let npm = variables("http://127.0.0.1:9000");
|
||||
assert!(npm.contains(&var("npm_config_proxy", "http://127.0.0.1:9000")));
|
||||
assert!(npm.contains(&var("npm_config_registry", "http://registry.npmjs.org/")));
|
||||
let gem = arguments("http://127.0.0.1:9000", &config, &GEM, &["install".to_string()]);
|
||||
let gem = arguments("http://127.0.0.1:9000", &GEM, &["install".to_string()]);
|
||||
assert_eq!(gem, ["--clear-sources", "--source", "http://rubygems.org/"]);
|
||||
assert!(arguments("http://127.0.0.1:9000", &config, &GEM, &["sources".to_string()]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mirror_replaces_the_registry_it_copies() {
|
||||
let var = |name: &str, value: &str| (name.to_string(), value.to_string());
|
||||
let config = r#"{"registries": {"npm": ["https://npm.example.com/"], "pypi": ["https://art.example.com/pypi/"]}}"#;
|
||||
let env = variables("http://127.0.0.1:9000", &serde_json::from_str(config).expect("parses"));
|
||||
assert!(env.contains(&var("npm_config_registry", "http://npm.example.com/")));
|
||||
assert!(env.contains(&var("PIP_INDEX_URL", "http://art.example.com/pypi/simple")));
|
||||
assert!(env.contains(&var("PIP_TRUSTED_HOST", "art.example.com files.pythonhosted.org")));
|
||||
assert!(arguments("http://127.0.0.1:9000", &GEM, &["sources".to_string()]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -45,17 +34,15 @@ fn no_two_managers_set_a_variable_differently() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_overridden_registry_is_known() {
|
||||
let config = FirewallConfig::default();
|
||||
let hosts = Firewall::default().hosts();
|
||||
let values = variables("", &config).into_iter().map(|(_, value)| value);
|
||||
let flags = MANAGERS.iter().flat_map(|manager| {
|
||||
let typed: Vec<String> = manager.args.iter().flat_map(|args| args.when).map(|arg| arg.to_string()).collect();
|
||||
arguments("", &config, manager, &typed)
|
||||
});
|
||||
for value in values.chain(flags) {
|
||||
for (_, after) in value.match_indices("http://").map(|(i, _)| value.split_at(i + 7)) {
|
||||
let host = after.split(['/', '"']).next().unwrap_or(after);
|
||||
assert!(hosts.contains(&host), "{value} points at {host}");
|
||||
for manager in MANAGERS {
|
||||
let values = manager.env.iter().map(|(_, value)| *value);
|
||||
let flags = manager.args.iter().flat_map(|args| args.flags.iter().copied());
|
||||
for value in values.chain(flags) {
|
||||
for (_, after) in value.match_indices("http://").map(|(i, _)| value.split_at(i + 7)) {
|
||||
let host = after.split(['/', '"']).next().unwrap_or(after);
|
||||
assert!(hosts.contains(&host), "{} points at {host}", manager.command);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,10 @@ use probe::Outcome;
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
firewall::init_logging("info");
|
||||
let config = FirewallConfig::load()?;
|
||||
let port = aliasing::spawn(0, config.clone())?;
|
||||
let port = aliasing::spawn(0, FirewallConfig::load()?)?;
|
||||
println!("firewall proxy on {}\n", firewall::local_url(port, ""));
|
||||
|
||||
let results = probe::all(port, &config);
|
||||
let results = probe::all(port);
|
||||
println!();
|
||||
let mut failed = 0;
|
||||
for (name, outcome) in &results {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use firewall::aliasing::{self, Invocation, Manager, CARGO, GEM, GO, NPM, PIP, PIP3, UV};
|
||||
use firewall::FirewallConfig;
|
||||
use std::path::PathBuf;
|
||||
|
||||
struct Probe {
|
||||
@@ -30,14 +29,14 @@ static PROBES: &[Probe] = &[
|
||||
},
|
||||
];
|
||||
|
||||
pub fn all(port: u16, config: &FirewallConfig) -> Vec<(&'static str, Outcome)> {
|
||||
PROBES.iter().map(|probe| (probe.manager.command, run(probe, port, config))).collect()
|
||||
pub fn all(port: u16) -> Vec<(&'static str, Outcome)> {
|
||||
PROBES.iter().map(|probe| (probe.manager.command, run(probe, port))).collect()
|
||||
}
|
||||
|
||||
fn run(probe: &Probe, port: u16, config: &FirewallConfig) -> Outcome {
|
||||
fn run(probe: &Probe, port: u16) -> Outcome {
|
||||
let args = probe.args.iter().map(|arg| arg.to_string()).collect();
|
||||
let dir = probe.setup.and_then(|prepare| prepare());
|
||||
match aliasing::run(port, config, &Invocation::new(probe.manager.command.into(), args), dir.as_deref()) {
|
||||
match aliasing::run(port, &Invocation::new(probe.manager.command.into(), args), dir.as_deref()) {
|
||||
Ok(0) => Outcome::Ok,
|
||||
Ok(_) => Outcome::Failed,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Outcome::Absent,
|
||||
|
||||
@@ -7,7 +7,6 @@ ci = "github"
|
||||
installers = ["shell", "powershell", "homebrew", "msi"]
|
||||
# core/wix/main.wxs is edited to install the service.
|
||||
allow-dirty = ["msi"]
|
||||
features = ["machine-wide"]
|
||||
tap = "usestrix/homebrew-tap"
|
||||
publish-jobs = ["homebrew", "./publish-crates"]
|
||||
targets = ["aarch64-apple-darwin", "x86_64-apple-darwin", "aarch64-unknown-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"]
|
||||
@@ -1,5 +1,4 @@
|
||||
import AppKit
|
||||
import Security
|
||||
|
||||
struct BlockedPackage: Codable, Hashable, Identifiable {
|
||||
let eco: String
|
||||
@@ -12,46 +11,22 @@ struct BlockedPackage: Codable, Hashable, Identifiable {
|
||||
var label: String { version.map { "\(name) \($0)" } ?? name }
|
||||
/// The denylist and OSV only flag packages known to be malicious; the age check only holds back new ones.
|
||||
var malicious: Bool { filter != "age" }
|
||||
/// Malware is never allowed, and a new package only by version.
|
||||
var trustable: Bool { !malicious && version != nil }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
enum BlockAlert {
|
||||
/// Returns whether the user chose to trust the package.
|
||||
static func show(_ package: BlockedPackage) -> Bool {
|
||||
static func show(_ package: BlockedPackage) {
|
||||
let alert = NSAlert()
|
||||
alert.addButton(withTitle: "OK")
|
||||
if package.malicious {
|
||||
alert.alertStyle = .critical
|
||||
alert.messageText = "Blocked malware: \(package.label) (\(package.eco))"
|
||||
alert.informativeText = "\(package.label) \(package.reason).\n\n"
|
||||
+ "It was not installed. Don't install it from another source. "
|
||||
+ "If you didn't expect this package, a dependency may be compromised; tell your security team."
|
||||
alert.messageText = "Blocked a malicious package"
|
||||
alert.informativeText = "\(package.label) (\(package.eco)) \(package.reason). Do not install it."
|
||||
} else {
|
||||
alert.messageText = "Held back a new package"
|
||||
alert.informativeText = "\(package.label) (\(package.eco)) \(package.reason)."
|
||||
if package.trustable { alert.addButton(withTitle: "Trust this version") }
|
||||
}
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
return alert.runModal() == .alertSecondButtonReturn
|
||||
}
|
||||
}
|
||||
|
||||
enum AdminAuthorization {
|
||||
/// The allowlist applies to every user of the Mac, so changing it takes an admin, as `sudo` would.
|
||||
static func confirm() -> Bool {
|
||||
var authorization: AuthorizationRef?
|
||||
guard AuthorizationCreate(nil, nil, [], &authorization) == errAuthorizationSuccess,
|
||||
let authorization else { return false }
|
||||
defer { AuthorizationFree(authorization, []) }
|
||||
return "system.preferences".withCString { name in
|
||||
var item = AuthorizationItem(name: name, valueLength: 0, value: nil, flags: 0)
|
||||
return withUnsafeMutablePointer(to: &item) { item in
|
||||
var rights = AuthorizationRights(count: 1, items: item)
|
||||
let flags: AuthorizationFlags = [.interactionAllowed, .extendRights]
|
||||
return AuthorizationCopyRights(authorization, &rights, nil, flags, nil) == errAuthorizationSuccess
|
||||
}
|
||||
}
|
||||
alert.runModal()
|
||||
}
|
||||
}
|
||||
@@ -29,13 +29,11 @@ enum FirewallError: Error, LocalizedError {
|
||||
case extensionUnavailable
|
||||
case screeningDidNotStart(NEVPNStatus)
|
||||
case extensionStopped(String)
|
||||
case extensionRefused(String)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .extensionUnavailable: return "The extension is not running"
|
||||
case let .screeningDidNotStart(status): return "Screening did not start (\(status.label))"
|
||||
case let .extensionRefused(reply): return "The extension replied \(reply)"
|
||||
case let .extensionStopped(reason):
|
||||
return "The extension stopped: \(reason). Its log: log show --last 5m --predicate 'subsystem BEGINSWITH \"\(FirewallIDs.appBundleID)\"'"
|
||||
}
|
||||
@@ -203,28 +201,6 @@ final class FirewallModel: NSObject, ObservableObject {
|
||||
if let url = URL(string: pane) { NSWorkspace.shared.open(url) }
|
||||
}
|
||||
|
||||
/// Allowing a version writes it into the extension's config, which a restart then loads.
|
||||
func trust(_ package: BlockedPackage) async {
|
||||
guard package.trustable else { return }
|
||||
guard AdminAuthorization.confirm() else {
|
||||
log("Trust cancelled for \(package.label)")
|
||||
return
|
||||
}
|
||||
do {
|
||||
var request = ["eco": package.eco, "name": package.name]
|
||||
request["version"] = package.version
|
||||
let json = String(decoding: try JSONSerialization.data(withJSONObject: request), as: UTF8.self)
|
||||
let reply = try await providerMessage("allow \(json)")
|
||||
guard reply == "ok" else { throw FirewallError.extensionRefused(reply) }
|
||||
blocked.removeAll { $0 == package }
|
||||
log("Trusted \(package.label) (\(package.eco))")
|
||||
} catch {
|
||||
log("Could not trust \(package.label): \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
await restart()
|
||||
}
|
||||
|
||||
/// The extension cannot message the app, so the app asks it for blocks.
|
||||
private func watchBlocks() async {
|
||||
while true {
|
||||
@@ -232,7 +208,7 @@ final class FirewallModel: NSObject, ObservableObject {
|
||||
let packages = try? JSONDecoder().decode([BlockedPackage].self, from: Data(reply.utf8)) {
|
||||
for package in packages where !blocked.contains(package) {
|
||||
blocked.append(package)
|
||||
if BlockAlert.show(package) { await trust(package) }
|
||||
BlockAlert.show(package)
|
||||
}
|
||||
blocked = Array(blocked.suffix(10))
|
||||
}
|
||||
|
||||
@@ -29,10 +29,6 @@ struct MenuBarView: View {
|
||||
if !package.malicious {
|
||||
Menu("Held back \(package.label) (\(package.eco))") {
|
||||
Text(package.reason)
|
||||
Button("Trust this version") {
|
||||
Task { await model.trust(package) }
|
||||
}
|
||||
.disabled(model.busy || !package.trustable)
|
||||
}
|
||||
} else {
|
||||
Menu("Blocked \(package.label) (\(package.eco))") {
|
||||
|
||||
+1
-1
@@ -133,7 +133,7 @@ targets:
|
||||
arm64|arm64e) triple=aarch64-apple-darwin ;;
|
||||
x86_64) triple=x86_64-apple-darwin ;;
|
||||
esac
|
||||
cargo build --bin firewall-uninstall --features machine-wide --target $triple $([ "$CONFIGURATION" = Debug ] || echo --release)
|
||||
cargo build --bin firewall-uninstall --target $triple $([ "$CONFIGURATION" = Debug ] || echo --release)
|
||||
bins="$bins target/$triple/$CARGO_PROFILE/firewall-uninstall"
|
||||
done
|
||||
lipo -create $bins -output "$TARGET_BUILD_DIR/$EXECUTABLE_FOLDER_PATH/firewall-uninstall"
|
||||
Reference in new issue
Block a user