mirror of
https://github.com/usestrix/firewall.git
synced 2026-11-09 13:31:32 -10:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
213c48ab01 | ||
|
|
314635bf2c | ||
|
|
6cad09d32d |
No files matched your search
+1
-1
@@ -129,7 +129,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_Storage_FileSystem", "Win32_System_Com", "Win32_System_Console", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_Pipes", "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_Storage_FileSystem", "Win32_System_Com", "Win32_System_Console", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
|
||||
windows-registry = "0.6.1"
|
||||
windows-service = "0.8.0"
|
||||
|
||||
|
||||
+1
-7
@@ -25,10 +25,6 @@ pub struct BlockedPackage {
|
||||
pub version: Option<String>,
|
||||
pub filter: &'static str,
|
||||
pub reason: String,
|
||||
/// Flagged as malware, not just held back for being new.
|
||||
pub malicious: bool,
|
||||
/// Malware is never allowed, and a new package only by version. Saves each app the rule.
|
||||
pub trustable: bool,
|
||||
}
|
||||
|
||||
struct Blocks {
|
||||
@@ -100,11 +96,9 @@ fn record(
|
||||
version: pkg.version.clone(),
|
||||
filter,
|
||||
reason: reason.to_owned(),
|
||||
malicious: filter != "age",
|
||||
trustable: filter == "age" && pkg.version.is_some(),
|
||||
};
|
||||
push(&mut blocks.unsent, block.clone());
|
||||
if block.malicious {
|
||||
if filter != "age" {
|
||||
return None;
|
||||
}
|
||||
let (wake, allowed) = watch::channel(false);
|
||||
|
||||
+54
-10
@@ -1,24 +1,32 @@
|
||||
//! How the tray asks the service what it blocked, as the macOS app messages its extension.
|
||||
//! How the tray asks the service what it blocked, and allows a new package, as the macOS app
|
||||
//! messages its extension.
|
||||
|
||||
use super::security_descriptor;
|
||||
use crate::blocks;
|
||||
use super::{config_file, security_descriptor};
|
||||
use crate::{blocks, Firewall};
|
||||
use rama::error::BoxError;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};
|
||||
use windows::Win32::Security::SECURITY_ATTRIBUTES;
|
||||
use windows::core::{Owned, PWSTR};
|
||||
use windows::Win32::Foundation::HANDLE;
|
||||
use windows::Win32::Security::*;
|
||||
use windows::Win32::System::Pipes::{GetNamedPipeClientProcessId, ImpersonateNamedPipeClient};
|
||||
use windows::Win32::System::Threading::*;
|
||||
|
||||
pub(super) const PIPE: &str = r"\\.\pipe\StrixFirewall";
|
||||
/// Signed-in users can connect, as the tray runs as them.
|
||||
const PIPE_ACL: &str = "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;IU)";
|
||||
|
||||
pub(super) async fn serve() -> Result<(), BoxError> {
|
||||
pub(super) async fn serve(firewall: Arc<Firewall>) -> Result<(), BoxError> {
|
||||
let mut server = create(true)?;
|
||||
loop {
|
||||
server.connect().await?;
|
||||
let client = std::mem::replace(&mut server, create(false)?);
|
||||
let firewall = Arc::clone(&firewall);
|
||||
tokio::spawn(async move {
|
||||
if let Err(error) = answer(client).await {
|
||||
if let Err(error) = answer(client, &firewall).await {
|
||||
tracing::debug!(%error, "could not answer the tray");
|
||||
}
|
||||
});
|
||||
@@ -40,19 +48,55 @@ fn create(first: bool) -> Result<NamedPipeServer, BoxError> {
|
||||
}
|
||||
|
||||
/// A line each way.
|
||||
async fn answer(client: NamedPipeServer) -> Result<(), BoxError> {
|
||||
async fn answer(client: NamedPipeServer, firewall: &Firewall) -> Result<(), BoxError> {
|
||||
let mut client = BufReader::new(client);
|
||||
let mut request = String::new();
|
||||
(&mut client)
|
||||
.take(64 * 1024)
|
||||
.read_line(&mut request)
|
||||
.await?;
|
||||
let reply = match request.trim_end() {
|
||||
"blocks" => serde_json::to_string(&blocks::take())?,
|
||||
other => format!("error: unknown request {other}"),
|
||||
let request = request.trim_end();
|
||||
// Only the app can message the macOS extension; here any program could connect.
|
||||
let reply = if !client_is_tray(client.get_ref())? {
|
||||
"error: only the tray can ask".to_owned()
|
||||
} else if request.starts_with("allow ") && !client_is_admin(client.get_ref())? {
|
||||
"error: trusting a package takes an administrator".to_owned()
|
||||
} else {
|
||||
blocks::answer(firewall, &config_file(), request)
|
||||
};
|
||||
client.write_all(format!("{reply}\n").as_bytes()).await?;
|
||||
// Closing before the tray hangs up could discard the reply.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), client.read(&mut [0])).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn client_is_tray(client: &NamedPipeServer) -> Result<bool, BoxError> {
|
||||
let mut id = 0;
|
||||
unsafe { GetNamedPipeClientProcessId(HANDLE(client.as_raw_handle()), &mut id)? };
|
||||
let process = unsafe { Owned::new(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, id)?) };
|
||||
let mut path = [0u16; 1024];
|
||||
let mut len = path.len() as u32;
|
||||
let flags = PROCESS_NAME_WIN32;
|
||||
unsafe { QueryFullProcessImageNameW(*process, flags, PWSTR(path.as_mut_ptr()), &mut len)? };
|
||||
let path = String::from_utf16(&path[..len as usize])?;
|
||||
let tray = std::env::current_exe()?.with_file_name("firewall-tray.exe");
|
||||
// Windows paths ignore case.
|
||||
Ok(path.to_lowercase() == tray.to_string_lossy().to_lowercase())
|
||||
}
|
||||
|
||||
/// Elevated, as only an elevated token has the Administrators group enabled.
|
||||
fn client_is_admin(client: &NamedPipeServer) -> windows::core::Result<bool> {
|
||||
let mut sid = [0u32; SECURITY_MAX_SID_SIZE as usize / 4];
|
||||
let admins = PSID(sid.as_mut_ptr().cast());
|
||||
let mut size = SECURITY_MAX_SID_SIZE;
|
||||
unsafe { CreateWellKnownSid(WinBuiltinAdministratorsSid, None, Some(admins), &mut size)? };
|
||||
unsafe { ImpersonateNamedPipeClient(HANDLE(client.as_raw_handle()))? };
|
||||
let mut member = false.into();
|
||||
let checked = unsafe { CheckTokenMembership(None, admins, &mut member) };
|
||||
// Carrying on as the client would be worse than stopping.
|
||||
if unsafe { RevertToSelf() }.is_err() {
|
||||
std::process::abort();
|
||||
}
|
||||
checked?;
|
||||
Ok(member.as_bool())
|
||||
}
|
||||
@@ -155,8 +155,9 @@ async fn start_screening(status: &ServiceStatusHandle) -> Result<Vec<&'static st
|
||||
let crl = HttpServer::auto(exec.clone()).service(crl);
|
||||
tokio::spawn(listen_on(CRL_ADDRESS, 80, &exec)?.serve(crl));
|
||||
|
||||
tokio::spawn(async {
|
||||
if let Err(error) = pipe::serve().await {
|
||||
let tray_firewall = Arc::clone(&firewall);
|
||||
tokio::spawn(async move {
|
||||
if let Err(error) = pipe::serve(tray_firewall).await {
|
||||
tracing::error!(%error, "the tray cannot reach the service");
|
||||
}
|
||||
});
|
||||
|
||||
+129
-8
@@ -2,16 +2,17 @@
|
||||
|
||||
use super::pipe::PIPE;
|
||||
use super::*;
|
||||
use muda::{Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
|
||||
use muda::{IsMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
|
||||
use serde::Deserialize;
|
||||
use std::io::{BufRead, BufReader, Cursor, Write};
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::sync::mpsc::{channel, Receiver, Sender};
|
||||
use std::time::Duration;
|
||||
use tray_icon::{Icon, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
|
||||
use windows::core::{w, PCWSTR};
|
||||
use windows::Win32::Foundation::*;
|
||||
use windows::Win32::System::Pipes::GetNamedPipeServerProcessId;
|
||||
use windows::Win32::System::Threading::CreateMutexW;
|
||||
use windows::Win32::System::Threading::*;
|
||||
use windows::Win32::UI::Shell::*;
|
||||
use windows::Win32::UI::WindowsAndMessaging::*;
|
||||
use windows_registry::CURRENT_USER;
|
||||
@@ -22,6 +23,9 @@ const MENU_PAUSE: &str = "pause";
|
||||
const MENU_RESTART: &str = "restart";
|
||||
const MENU_LOG: &str = "log";
|
||||
const MENU_QUIT: &str = "quit";
|
||||
/// Also the service's requests, and `allow` the elevated `firewall-tray` command.
|
||||
const ALLOW: &str = "allow";
|
||||
const ALLOW_ONCE: &str = "allow-once";
|
||||
const LOGO: &[u8] = include_bytes!("tray.png");
|
||||
/// Where blocked packages are listed, below Open logs.
|
||||
const BLOCKED_AT: usize = 5;
|
||||
@@ -29,6 +33,19 @@ const BLOCKED_KEPT: usize = 10;
|
||||
|
||||
/// Runs until Quit, once per session.
|
||||
pub fn run() -> Result<(), BoxError> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if let [verb, id, label @ ..] = &args[..] {
|
||||
if verb == ALLOW {
|
||||
// Run by `run_elevated`, so the service can tell an admin asked.
|
||||
let trusted = ask_service(&format!("{ALLOW} {id}"))
|
||||
.and_then(|reply| answered(&format!("Trusted {}", label.join(" ")), &reply));
|
||||
if let Err(error) = trusted {
|
||||
show_error(error);
|
||||
std::process::exit(1);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
// Held until we exit.
|
||||
let _mutex = unsafe { CreateMutexW(None, false, w!(r"Local\StrixFirewallTray"))? };
|
||||
if unsafe { GetLastError() } == ERROR_ALREADY_EXISTS {
|
||||
@@ -62,9 +79,11 @@ pub fn run() -> Result<(), BoxError> {
|
||||
menu,
|
||||
blocked_separator,
|
||||
blocked: Vec::new(),
|
||||
allowed: channel(),
|
||||
};
|
||||
tray.update();
|
||||
unsafe { SetTimer(None, 0, 2000, None) };
|
||||
// The service holds a new package's download only while it is asked this often.
|
||||
unsafe { SetTimer(None, 0, 500, None) };
|
||||
let mut message = MSG::default();
|
||||
while unsafe { GetMessageW(&mut message, None, 0, 0) }.0 > 0 {
|
||||
unsafe { DispatchMessageW(&message) };
|
||||
@@ -112,10 +131,13 @@ struct Tray {
|
||||
blocked_separator: PredefinedMenuItem,
|
||||
/// The most recent, as the menu lists them.
|
||||
blocked: Vec<BlockedPackage>,
|
||||
/// Allowed from another thread, so no longer listed.
|
||||
allowed: (Sender<BlockedPackage>, Receiver<BlockedPackage>),
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Deserialize)]
|
||||
struct BlockedPackage {
|
||||
id: u64,
|
||||
eco: String,
|
||||
name: String,
|
||||
version: Option<String>,
|
||||
@@ -136,6 +158,11 @@ impl BlockedPackage {
|
||||
fn malicious(&self) -> bool {
|
||||
self.filter != "age"
|
||||
}
|
||||
|
||||
/// Malware is never allowed, and a new package only by version.
|
||||
fn trustable(&self) -> bool {
|
||||
!self.malicious() && self.version.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
impl Tray {
|
||||
@@ -161,6 +188,11 @@ impl Tray {
|
||||
|
||||
/// The service hands each block over once, so whichever tray asks first shows it.
|
||||
fn collect_blocks(&mut self) {
|
||||
let allowed: Vec<_> = self.allowed.1.try_iter().collect();
|
||||
if !allowed.is_empty() {
|
||||
self.blocked.retain(|blocked| !allowed.contains(blocked));
|
||||
self.list_blocked();
|
||||
}
|
||||
if self.state != Some(ServiceState::Running) {
|
||||
return;
|
||||
}
|
||||
@@ -184,7 +216,14 @@ impl Tray {
|
||||
self.blocked.drain(..excess);
|
||||
self.list_blocked();
|
||||
// Off the UI thread, so the menu keeps working while they are open.
|
||||
std::thread::spawn(move || new.iter().for_each(alert));
|
||||
let allowed = self.allowed.0.clone();
|
||||
std::thread::spawn(move || {
|
||||
for package in new {
|
||||
if alert(&package) {
|
||||
allow(package, false, &allowed);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn list_blocked(&self) {
|
||||
@@ -204,14 +243,31 @@ impl Tray {
|
||||
package.reason.clone()
|
||||
};
|
||||
let reason = MenuItem::new(reason, false, None);
|
||||
let trustable = package.trustable();
|
||||
let once = MenuItem::with_id(format!("{ALLOW_ONCE}:{i}"), "Allow Once", trustable, None);
|
||||
let always = MenuItem::with_id(format!("{ALLOW}:{i}"), "Trust this version", trustable, None);
|
||||
let items: &[&dyn IsMenuItem] = if package.malicious() {
|
||||
&[&reason]
|
||||
} else {
|
||||
&[&reason, &once, &always]
|
||||
};
|
||||
let label = format!("{verb} {}", package.label());
|
||||
if let Ok(item) = Submenu::with_items(label, true, &[&reason]) {
|
||||
if let Ok(item) = Submenu::with_items(label, true, items) {
|
||||
let _ = self.menu.insert(&item, BLOCKED_AT + 1 + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_menu(&self, id: &str) {
|
||||
if let Some((verb @ (ALLOW | ALLOW_ONCE), i)) = id.split_once(':') {
|
||||
let trust = verb == ALLOW;
|
||||
let package = i.parse().ok().and_then(|i: usize| self.blocked.get(i));
|
||||
if let Some(package) = package.cloned() {
|
||||
let allowed = self.allowed.0.clone();
|
||||
std::thread::spawn(move || allow(package, trust, &allowed));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let state = self.state;
|
||||
let screening = state == Some(ServiceState::Running);
|
||||
let action: fn() -> Result<(), BoxError> = match id {
|
||||
@@ -237,7 +293,8 @@ impl Tray {
|
||||
}
|
||||
}
|
||||
|
||||
fn alert(package: &BlockedPackage) {
|
||||
/// Whether the user chose to allow it once.
|
||||
fn alert(package: &BlockedPackage) -> bool {
|
||||
let text = format!("{} {}.", package.label(), package.reason);
|
||||
let (title, text, style) = if package.malicious() {
|
||||
let title = format!("Blocked malware: {}", package.label());
|
||||
@@ -245,11 +302,75 @@ fn alert(package: &BlockedPackage) {
|
||||
+ "\n\nIt 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.";
|
||||
(title, text, MB_ICONERROR)
|
||||
} else {
|
||||
} else if !package.trustable() {
|
||||
("Held back a new package".to_owned(), text, MB_ICONINFORMATION)
|
||||
} else {
|
||||
let text = text + "\n\nAllow it once? To trust this version, use the notification-area icon.";
|
||||
("Held back a new package".to_owned(), text, MB_YESNO | MB_ICONINFORMATION)
|
||||
};
|
||||
let (title, text) = (HSTRING::from(title), HSTRING::from(text));
|
||||
unsafe { MessageBoxW(None, &text, &title, style | MB_SETFOREGROUND) };
|
||||
unsafe { MessageBoxW(None, &text, &title, style | MB_SETFOREGROUND) == IDYES }
|
||||
}
|
||||
|
||||
/// Trusting writes the config for every user, so it goes through a UAC prompt.
|
||||
/// The elevated process shows its own errors and late replies.
|
||||
fn allow(package: BlockedPackage, trust: bool, allowed: &Sender<BlockedPackage>) {
|
||||
let allowed_it = if trust {
|
||||
run_elevated(&[ALLOW, &package.id.to_string(), &package.label()])
|
||||
.map(|code| code == Some(0))
|
||||
} else {
|
||||
let title = format!("Allowed {} for the next minute", package.label());
|
||||
ask_service(&format!("{ALLOW_ONCE} {}", package.id))
|
||||
.and_then(|reply| answered(&title, &reply))
|
||||
.map(|()| true)
|
||||
};
|
||||
match allowed_it {
|
||||
Ok(true) => {
|
||||
let _ = allowed.send(package);
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(error) => show_error(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tells the user, under `title`, when the install had already stopped waiting.
|
||||
fn answered(title: &str, reply: &str) -> Result<(), BoxError> {
|
||||
match reply {
|
||||
"ok" => Ok(()),
|
||||
"late" => {
|
||||
let text = "The install had already stopped waiting for it. Run it again to finish.";
|
||||
let (title, text) = (HSTRING::from(title), HSTRING::from(text));
|
||||
unsafe { MessageBoxW(None, &text, &title, MB_ICONINFORMATION | MB_SETFOREGROUND) };
|
||||
Ok(())
|
||||
}
|
||||
other => Err(other.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// This program as an admin, waiting for its exit code; `None` if the user said no.
|
||||
fn run_elevated(args: &[&str]) -> Result<Option<u32>, BoxError> {
|
||||
let exe = HSTRING::from(std::env::current_exe()?.as_path());
|
||||
let parameters = HSTRING::from(args.join(" "));
|
||||
let mut info = SHELLEXECUTEINFOW {
|
||||
cbSize: size_of::<SHELLEXECUTEINFOW>() as u32,
|
||||
fMask: SEE_MASK_NOCLOSEPROCESS,
|
||||
lpVerb: w!("runas"),
|
||||
lpFile: PCWSTR(exe.as_ptr()),
|
||||
lpParameters: PCWSTR(parameters.as_ptr()),
|
||||
nShow: SW_HIDE.0,
|
||||
..Default::default()
|
||||
};
|
||||
if let Err(error) = unsafe { ShellExecuteExW(&mut info) } {
|
||||
if error.code() == ERROR_CANCELLED.to_hresult() {
|
||||
return Ok(None);
|
||||
}
|
||||
return Err(error.into());
|
||||
}
|
||||
let process = unsafe { Owned::new(info.hProcess) };
|
||||
unsafe { WaitForSingleObject(*process, INFINITE) };
|
||||
let mut code = 1;
|
||||
unsafe { GetExitCodeProcess(*process, &mut code)? };
|
||||
Ok(Some(code))
|
||||
}
|
||||
|
||||
/// One request per connection, as the service answers.
|
||||
|
||||
@@ -16,8 +16,6 @@ async fn allowing_once_releases_the_held_download() {
|
||||
let id = loop {
|
||||
let blocks: serde_json::Value = serde_json::from_str(&answer(&firewall, config, "blocks")).unwrap();
|
||||
if let Some(id) = blocks[0]["id"].as_u64() {
|
||||
assert_eq!(blocks[0]["malicious"], false);
|
||||
assert_eq!(blocks[0]["trustable"], true);
|
||||
break id;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
|
||||
@@ -30,12 +30,12 @@ enum BlockAlert {
|
||||
if package.malicious {
|
||||
alert.alertStyle = .critical
|
||||
alert.messageText = "Blocked malware: \(package.label) (\(package.eco))"
|
||||
alert.informativeText = "\(package.label) \(package.reason).\n\n"
|
||||
setText(alert, "\(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."
|
||||
+ "If you didn't expect this package, a dependency may be compromised; tell your security team.")
|
||||
} else {
|
||||
alert.messageText = "Held back a new package"
|
||||
alert.informativeText = "\(package.label) (\(package.eco)) \(package.reason)."
|
||||
setText(alert, "\(package.label) (\(package.eco)) \(package.reason).")
|
||||
if package.trustable {
|
||||
alert.addButton(withTitle: "Allow Once")
|
||||
alert.addButton(withTitle: "Trust this version")
|
||||
@@ -56,6 +56,22 @@ enum BlockAlert {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
alert.runModal()
|
||||
}
|
||||
|
||||
/// An alert's own text is plain, so this text goes in a selectable field, where its links open on click.
|
||||
private static func setText(_ alert: NSAlert, _ text: String) {
|
||||
let linked = NSMutableAttributedString(string: text, attributes: [.font: NSFont.systemFont(ofSize: NSFont.smallSystemFontSize)])
|
||||
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
|
||||
for match in detector.matches(in: text, range: NSRange(text.startIndex..., in: text)) {
|
||||
if let url = match.url { linked.addAttribute(.link, value: url, range: match.range) }
|
||||
}
|
||||
let field = NSTextField(wrappingLabelWithString: "")
|
||||
field.allowsEditingTextAttributes = true
|
||||
field.isSelectable = true
|
||||
field.attributedStringValue = linked
|
||||
field.preferredMaxLayoutWidth = 300
|
||||
field.frame.size = field.fittingSize
|
||||
alert.accessoryView = field
|
||||
}
|
||||
}
|
||||
|
||||
enum AdminAuthorization {
|
||||
|
||||
Reference in new issue
Block a user