mirror of
https://github.com/usestrix/firewall.git
synced 2026-11-09 05:19:35 -10:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5eafaa5cf | ||
|
|
fc02226cd6 | ||
|
|
5068b3578d | ||
|
|
8d781f3f98 | ||
|
|
e521cbdefa |
No files matched your search
@@ -38,14 +38,17 @@ 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"
|
||||
@@ -87,6 +90,10 @@ 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"
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
use crate::policies::Package;
|
||||
use serde::Serialize;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Bounded, so blocks pile up harmlessly while nothing collects them.
|
||||
const KEPT: usize = 50;
|
||||
|
||||
static RECENT: Mutex<Vec<BlockedPackage>> = Mutex::new(Vec::new());
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct BlockedPackage {
|
||||
pub eco: &'static str,
|
||||
pub name: String,
|
||||
pub version: Option<String>,
|
||||
pub filter: &'static str,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
pub fn record(eco: &'static str, pkg: &Package, filter: &'static str, reason: &str) {
|
||||
let mut recent = RECENT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if recent.len() == KEPT {
|
||||
recent.remove(0);
|
||||
}
|
||||
recent.push(BlockedPackage {
|
||||
eco,
|
||||
name: pkg.name.clone(),
|
||||
version: pkg.version.clone(),
|
||||
filter,
|
||||
reason: reason.to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
/// Hands each block over once.
|
||||
pub fn take() -> Vec<BlockedPackage> {
|
||||
std::mem::take(&mut *RECENT.lock().unwrap_or_else(|e| e.into_inner()))
|
||||
}
|
||||
+24
-54
@@ -1,11 +1,9 @@
|
||||
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::{Map, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::num::{NonZeroU16, NonZeroU64};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub const DEFAULT_PORT: u16 = 8080;
|
||||
@@ -13,7 +11,7 @@ pub const DEFAULT_PORT: u16 = 8080;
|
||||
#[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.
|
||||
@@ -22,8 +20,9 @@ pub struct FirewallConfig {
|
||||
/// 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, Deserialize)]
|
||||
@@ -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: 0,
|
||||
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,43 +129,3 @@ fn merge(base: &mut Map<String, Value>, top: Map<String, Value>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod aliasing;
|
||||
pub mod blocks;
|
||||
pub mod config;
|
||||
pub mod firewall;
|
||||
pub mod http;
|
||||
|
||||
@@ -5,7 +5,7 @@ mod uninstall;
|
||||
pub use uninstall::uninstall;
|
||||
|
||||
use crate::config::FirewallConfig;
|
||||
use crate::{mitm, telemetry};
|
||||
use crate::{blocks, mitm, telemetry};
|
||||
use crate::Firewall;
|
||||
use rama::bytes::Bytes;
|
||||
use rama::error::BoxError;
|
||||
@@ -58,6 +58,7 @@ impl TransparentProxyHandler for Handler {
|
||||
let message = String::from_utf8_lossy(&message).into_owned();
|
||||
Some(Bytes::from(match message.as_str() {
|
||||
"ca" => self.ca.pem.clone(),
|
||||
"blocks" => serde_json::to_string(&blocks::take()).expect("blocks serialize"),
|
||||
other => format!("error: unknown message {other}"),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tracing_appender::rolling::{RollingFileAppender, Rotation};
|
||||
use windows::Win32::Foundation::ERROR_GEN_FAILURE;
|
||||
use windows_service::service::*;
|
||||
use windows_service::service_control_handler::{
|
||||
self, ServiceControlHandlerResult, ServiceStatusHandle,
|
||||
@@ -73,8 +74,12 @@ fn run_until_stopped() -> Result<(), BoxError> {
|
||||
| ServiceControl::Shutdown
|
||||
| ServiceControl::Pause
|
||||
| ServiceControl::Continue => {
|
||||
let _ = control_sender.send(control);
|
||||
ServiceControlHandlerResult::NoError
|
||||
// Answered once handled, so a failed pause fails the caller's ControlService.
|
||||
let (reply, handled) = tokio::sync::oneshot::channel();
|
||||
let _ = control_sender.send((control, reply));
|
||||
handled
|
||||
.blocking_recv()
|
||||
.unwrap_or(ServiceControlHandlerResult::NoError)
|
||||
}
|
||||
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
|
||||
_ => ServiceControlHandlerResult::NotImplemented,
|
||||
@@ -89,16 +94,26 @@ fn run_until_stopped() -> Result<(), BoxError> {
|
||||
}
|
||||
};
|
||||
// Only pausing removes our hosts entries; a stop or crash keeps them, failing closed.
|
||||
while let Some(control) = control_receiver.recv().await {
|
||||
while let Some((control, reply)) = control_receiver.recv().await {
|
||||
let (hosts, state) = match control {
|
||||
ServiceControl::Pause => (&[][..], ServiceState::Paused),
|
||||
ServiceControl::Continue => (&hosts[..], ServiceState::Running),
|
||||
_ => break,
|
||||
};
|
||||
match write_hosts_entries(hosts) {
|
||||
Ok(()) => set_status(&status, state, false)?,
|
||||
Err(error) => tracing::error!(%error, "could not rewrite the hosts file"),
|
||||
}
|
||||
let result = match write_hosts_entries(hosts) {
|
||||
Ok(()) => {
|
||||
set_status(&status, state, false)?;
|
||||
ServiceControlHandlerResult::NoError
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(%error, "could not rewrite the hosts file");
|
||||
let code = error
|
||||
.raw_os_error()
|
||||
.map_or(ERROR_GEN_FAILURE.0, |code| code as u32);
|
||||
ServiceControlHandlerResult::Other(code)
|
||||
}
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
Ok::<_, BoxError>(())
|
||||
});
|
||||
@@ -147,7 +162,7 @@ async fn start_screening(status: &ServiceStatusHandle) -> Result<Vec<&'static st
|
||||
resolver: resolver.clone(),
|
||||
service: service.clone(),
|
||||
};
|
||||
let upstream = ConsumeErrLayer::trace_as_debug().into_layer(upstream);
|
||||
let upstream = ConsumeErrLayer::trace_as_warning().into_layer(upstream);
|
||||
tokio::spawn(listen_on(address, port, &exec)?.serve(upstream));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +144,11 @@ impl Tray {
|
||||
}
|
||||
|
||||
fn show_error(error: BoxError) {
|
||||
let text = HSTRING::from(error.to_string());
|
||||
let text = match error.source() {
|
||||
Some(source) => format!("{error}: {source}"),
|
||||
None => error.to_string(),
|
||||
};
|
||||
let text = HSTRING::from(text);
|
||||
unsafe { MessageBoxW(None, &text, w!("Strix Firewall"), MB_ICONERROR) };
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -69,7 +69,8 @@ pub async fn screen(url: &str, firewall: &Firewall) -> Option<String> {
|
||||
};
|
||||
info!(eco = registry.eco, pkg = %pkg.label(), %url, "screening");
|
||||
match consult(firewall, registry, &pkg).await {
|
||||
Some((_, Verdict::Deny(reason))) => {
|
||||
Some((filter, Verdict::Deny(reason))) => {
|
||||
crate::blocks::record(registry.eco, &pkg, filter, &reason);
|
||||
Some(format!("{} {reason}", pkg.label()))
|
||||
}
|
||||
Some((filter, Verdict::Unknown(e))) if !firewall.config.fail_open => {
|
||||
|
||||
@@ -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));
|
||||
|
||||
+1
-38
@@ -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");
|
||||
@@ -60,21 +38,6 @@ fn a_later_file_wins_and_allow_lists_add_up() {
|
||||
assert_eq!(names, ["a", "b"]);
|
||||
}
|
||||
|
||||
#[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_skips_the_filters() {
|
||||
// An unreachable denylist would otherwise leave the package unchecked.
|
||||
|
||||
@@ -7,6 +7,7 @@ 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,66 +0,0 @@
|
||||
# Platforms
|
||||
|
||||
## Requirements
|
||||
|
||||
| | Command prefix | Machine-wide |
|
||||
|---|---|---|
|
||||
| macOS | 13+, Apple silicon or Intel | Apple silicon, or an Intel Mac with a T2 chip |
|
||||
| Windows | 10 or 11, x86-64 | A TPM 2.0, and an admin to install |
|
||||
| Linux | glibc, x86-64 or arm64 | Not supported |
|
||||
|
||||
There are no musl, 32-bit or Windows on Arm builds.
|
||||
|
||||
`cargo install strix-firewall` installs only `firewall`. Add `--features machine-wide` for the
|
||||
machine-wide binaries, which otherwise come with the macOS app and the Windows MSI.
|
||||
|
||||
## What is screened
|
||||
|
||||
npm, pnpm, bun, pip, pip3, pipenv, pdm, uv, cargo, go and gem, downloading from:
|
||||
|
||||
| Ecosystem | Hosts |
|
||||
|---|---|
|
||||
| npm | registry.npmjs.org |
|
||||
| PyPI | pypi.org, files.pythonhosted.org |
|
||||
| crates.io | index.crates.io, static.crates.io, crates.io |
|
||||
| RubyGems | rubygems.org |
|
||||
| Go | proxy.golang.org |
|
||||
|
||||
Machine-wide screening also covers mirrors listed in the config file, under the registry they
|
||||
copy (`npm`, `pypi`, `pypi-files`, `cargo/index`, `cargo-dl`, `crates-api`, `gem` or `go`):
|
||||
`"registries": {"npm": ["https://npm.example.com/"]}`. A mirror must lay out its paths like that
|
||||
registry. `firewall <manager>` still sends managers to the public registries.
|
||||
|
||||
## How machine-wide screening works
|
||||
|
||||
Traffic to the hosts above is decrypted with a local CA that can only sign for those hosts. Its
|
||||
private key never leaves the Secure Enclave (macOS) or the TPM (Windows).
|
||||
|
||||
- **macOS:** a system extension, which you approve in System Settings.
|
||||
- **Windows:** a service, with a hosts-file entry pointing each registry host at it.
|
||||
- Without a TPM, the service can't start, so the install fails.
|
||||
- Any signed-in user can pause screening from the notification-area icon, until they resume
|
||||
it or the service restarts.
|
||||
- Clients that use an HTTP proxy or their own DNS skip the hosts file and aren't screened.
|
||||
Nor is WSL.
|
||||
- Each client has to trust the CA:
|
||||
|
||||
| Client | Trusts it through |
|
||||
|---|---|
|
||||
| npm, pnpm, bun | `NODE_EXTRA_CA_CERTS`, set to `%ProgramData%\Strix Firewall\ca.pem` |
|
||||
| uv | `UV_SYSTEM_CERTS`, which uses the Windows certificate store |
|
||||
| pip, cargo | The Windows certificate store |
|
||||
| gem, go | Untested |
|
||||
|
||||
Tested on Windows 11 and Apple silicon only.
|
||||
|
||||
## Changing settings
|
||||
|
||||
Machine-wide screening reads an admin-only JSON file when it starts. After editing it, restart
|
||||
screening. An invalid file stops screening from starting.
|
||||
|
||||
| OS | File | Restart from |
|
||||
|---|---|---|
|
||||
| macOS | `/Library/Application Support/Firewall/config.json` | The menu bar's Restart |
|
||||
| Windows | `%ProgramData%\Strix Firewall\config.json` | The notification-area icon's Restart |
|
||||
|
||||
The `firewall` command reads `config.json` from the user's config folder instead.
|
||||
@@ -0,0 +1,32 @@
|
||||
import AppKit
|
||||
|
||||
struct BlockedPackage: Codable, Hashable, Identifiable {
|
||||
let eco: String
|
||||
let name: String
|
||||
let version: String?
|
||||
let filter: String
|
||||
let reason: String
|
||||
|
||||
var id: String { "\(eco)/\(name)@\(version ?? "")" }
|
||||
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" }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
enum BlockAlert {
|
||||
static func show(_ package: BlockedPackage) {
|
||||
let alert = NSAlert()
|
||||
alert.addButton(withTitle: "OK")
|
||||
if package.malicious {
|
||||
alert.alertStyle = .critical
|
||||
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)."
|
||||
}
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
alert.runModal()
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import AppKit
|
||||
import NetworkExtension
|
||||
import OSLog
|
||||
import Security
|
||||
import ServiceManagement
|
||||
import SystemExtensions
|
||||
|
||||
enum StepStatus: Equatable {
|
||||
@@ -51,6 +52,7 @@ final class FirewallModel: NSObject, ObservableObject {
|
||||
@Published private(set) var completed = false
|
||||
@Published private(set) var removed = false
|
||||
@Published private(set) var screening = false
|
||||
@Published private(set) var blocked: [BlockedPackage] = []
|
||||
|
||||
private let logger = Logger(subsystem: FirewallIDs.appBundleID, category: "installer")
|
||||
private var pendingRequest: (request: OSSystemExtensionRequest, continuation: CheckedContinuation<Void, Error>)?
|
||||
@@ -72,6 +74,7 @@ final class FirewallModel: NSObject, ObservableObject {
|
||||
await refresh()
|
||||
if CommandLine.arguments.contains("--install") { await install() }
|
||||
}
|
||||
Task { await watchBlocks() }
|
||||
}
|
||||
|
||||
// MARK: - Flows
|
||||
@@ -112,6 +115,11 @@ final class FirewallModel: NSObject, ObservableObject {
|
||||
work: trustCertificateAuthority)
|
||||
else { return }
|
||||
|
||||
do {
|
||||
try SMAppService.mainApp.register()
|
||||
} catch {
|
||||
log("Could not open the app at login: \(error.localizedDescription)")
|
||||
}
|
||||
completed = true
|
||||
log("Setup complete")
|
||||
offerRestart()
|
||||
@@ -152,6 +160,7 @@ final class FirewallModel: NSObject, ObservableObject {
|
||||
await removeConfiguration()
|
||||
let strandedKey = removeStoredCA()
|
||||
await deactivate()
|
||||
try? await SMAppService.mainApp.unregister()
|
||||
if let strandedKey { trustStep = .failed(strandedKey) }
|
||||
|
||||
let failed = [extensionStep, screeningStep, trustStep].contains(where: \.isFailed)
|
||||
@@ -199,6 +208,21 @@ final class FirewallModel: NSObject, ObservableObject {
|
||||
if let url = URL(string: pane) { NSWorkspace.shared.open(url) }
|
||||
}
|
||||
|
||||
/// The extension cannot message the app, so the app asks it for blocks.
|
||||
private func watchBlocks() async {
|
||||
while true {
|
||||
if screening, let reply = try? await providerMessage("blocks"),
|
||||
let packages = try? JSONDecoder().decode([BlockedPackage].self, from: Data(reply.utf8)) {
|
||||
for package in packages where !blocked.contains(package) {
|
||||
blocked.append(package)
|
||||
BlockAlert.show(package)
|
||||
}
|
||||
blocked = Array(blocked.suffix(10))
|
||||
}
|
||||
try? await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
}
|
||||
}
|
||||
|
||||
private func stage(_ step: ReferenceWritableKeyPath<FirewallModel, StepStatus>,
|
||||
running: String,
|
||||
work: @MainActor () async throws -> String) async -> Bool {
|
||||
|
||||
@@ -22,5 +22,20 @@ struct MenuBarView: View {
|
||||
Task { await model.restart() }
|
||||
}
|
||||
.disabled(model.busy)
|
||||
|
||||
if !model.blocked.isEmpty {
|
||||
Divider()
|
||||
ForEach(model.blocked) { package in
|
||||
if !package.malicious {
|
||||
Menu("Held back \(package.label) (\(package.eco))") {
|
||||
Text(package.reason)
|
||||
}
|
||||
} else {
|
||||
Menu("Blocked \(package.label) (\(package.eco))") {
|
||||
Text("Malicious: \(package.reason)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+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 --target $triple $([ "$CONFIGURATION" = Debug ] || echo --release)
|
||||
cargo build --bin firewall-uninstall --features machine-wide --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