2bb6ce63ae
上一版我说"两个页面都加了",但用户在 v0.4.9 上依然看不到。这次不猜了, 把程序真跑起来截图,看到面板确实没画出来,才找到原因: pc_to_phone_ui 在 running 时于函数中段就 return 进了 resizable/focus 分支, 我加的那 37 行写在函数尾部,永远执行不到——代码在、grep 得到、但一个像素 都不会画。前两次自查只 grep 了"firewall_panel 在不在",没确认它在不在活的 分支上。面板已移到 pc_to_phone_running_controls(真正渲染的运行态控制区)。 为防同类缺陷复发,加了两个**真渲染**测试:在无窗口 egui 上下文里跑一帧, 把 galley 里的文字抓出来断言。grep 源码挡不住死代码,只有画一遍才行。 另外把 pc_receive_ui 里内联复制的第三份面板也收敛到 firewall_panel。 Windows 防火墙检测重做(这才是"点了放行还是连不上"的根因方向): 1. 改用 PowerShell 而非 netsh。netsh 输出的**值**会本地化(中文系统上是 「允许/阻止/任何/是」),原先按 "Any"/"Yes" 匹配在中文 Windows 上必然 误判;Get-NetFirewallRule 返回的枚举在任何语言下都是 Allow/Block/Any。 2. 按**程序路径**查询,不再只按规则显示名。用户在「安全警报」弹窗上点了 取消时,Windows 会自建一条针对该 exe 的阻止规则,名字是程序名而不是 QFT Desktop。只按显示名查完全看不见它,而 Block 在 Windows 里永远压过 Allow——症状正是"点了放行、界面显示已放行、手机依然连不上"。 grant() 现在会先清掉这类阻止规则再重建放行规则。 3. 检测「阻止所有传入连接,包括位于允许应用列表中的应用」 (AllowInboundRules=False)。这项打开时加多少规则都没用,单独报为 BlockedByPolicy,按钮相应置灰并说明要去哪里关——它属于用户的安全设置, 程序不代劳。 4. manual_instructions 里的 -Profile Private,Domain 是个真 bug,与本模块 自己的注释矛盾:照抄的用户会重建出一条在 Direct AP 虚拟网卡(被判为 公用网络)上根本不适用的规则。改为 -Profile Any 并补上排查步骤。 5. grant() 成功后不再直接断言"已放行",改为触发复检——规则加上了不等于 入站真的通了。 检测要起 PowerShell 进程(1~2 秒),移到后台线程,避免在"启动接收"的瞬间 卡住界面。解析逻辑抽成纯函数 classify_probe,配 10 个用例覆盖中文系统、 自动阻止规则、系统级封禁、防火墙整体关闭等场景——Windows 专有代码最容易 烂在没人跑的地方。已用 cargo check --target x86_64-pc-windows-gnu 验证 Windows 分支能编过。 版本号 0.4.9 → 0.4.10,便于确认拿到的是新构建。
605 lines
26 KiB
Rust
605 lines
26 KiB
Rust
//! 系统防火墙放行。
|
||
//!
|
||
//! 接收端要监听入站 TCP,而 Windows 防火墙默认拦截未授权程序的入站连接,
|
||
//! 表现是「对方能解析连接码,但连接一直超时」——这类问题用户几乎不可能
|
||
//! 自己联想到防火墙。所以由程序主动检测并申请放行。
|
||
//!
|
||
//! 三条设计约束:
|
||
//! 1. **只在确实缺规则时申请**。每次启动都弹 UAC 是骚扰。
|
||
//! 2. **被拒绝就记住**。写一个标记文件,之后只在界面上留一个手动按钮,
|
||
//! 不再自动弹窗。
|
||
//! 3. **规则尽量窄**。只放行本程序这一个可执行文件,绝不整体关闭防火墙。
|
||
//! 但**不能按网络配置文件收窄**——见下方 `grant()` 里的说明。
|
||
//!
|
||
//! 提权本身由操作系统的标准机制完成(Windows 的 UAC、macOS 的
|
||
//! 授权对话框),程序不接触也不存储任何凭据。
|
||
|
||
use anyhow::{bail, Context, Result};
|
||
use std::path::PathBuf;
|
||
|
||
/// 规则显示名。检测与添加都用它,改名会导致旧规则失效。
|
||
// 仅 Windows 分支使用;其余平台整段被 cfg 编译掉
|
||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||
pub const RULE_NAME: &str = "QFT Desktop";
|
||
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
pub enum FirewallStatus {
|
||
/// 已放行,或系统防火墙未开启,总之入站不会被拦
|
||
Allowed,
|
||
/// 缺少放行规则,入站很可能被拦
|
||
Missing,
|
||
/// 规则本身没问题,但系统层面的策略让任何放行规则都不生效。
|
||
///
|
||
/// 对应 Windows 的「阻止所有传入连接,包括位于允许应用列表中的应用」
|
||
/// (`BlockInboundAlways`)。这一项打开时,用户点多少次「放行防火墙」
|
||
/// 都不会有任何变化——必须先把它关掉,所以要单独报出来。
|
||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||
BlockedByPolicy(String),
|
||
/// 存在针对本程序的「阻止」入站规则,压过了我们的放行规则。
|
||
///
|
||
/// 通常是用户在 Windows「安全警报」弹窗上点了取消后系统自动建的,
|
||
/// 规则名是程序名而非 `QFT Desktop`。这一类提权后可以自动清掉,
|
||
/// 所以和 [`BlockedByPolicy`](Self::BlockedByPolicy) 分开表示。
|
||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||
BlockedByRule(String),
|
||
/// 查不出来(命令不可用、输出无法解析等),不要据此吓唬用户
|
||
Unknown(String),
|
||
/// 本平台不做自动放行(目前只有 Linux 会返回)
|
||
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
|
||
Unsupported(&'static str),
|
||
}
|
||
|
||
impl FirewallStatus {
|
||
pub fn needs_action(&self) -> bool {
|
||
matches!(
|
||
self,
|
||
Self::Missing | Self::BlockedByPolicy(_) | Self::BlockedByRule(_)
|
||
)
|
||
}
|
||
|
||
/// 提权后加/删规则能否解决。
|
||
///
|
||
/// `BlockedByPolicy` 是系统级开关,我们不去动它——那属于用户的安全设置,
|
||
/// 只做提示,由用户自己决定是否关闭。
|
||
pub fn fixable_by_grant(&self) -> bool {
|
||
matches!(self, Self::Missing | Self::BlockedByRule(_))
|
||
}
|
||
|
||
/// 给界面用的一句话说明。
|
||
pub fn detail(&self) -> String {
|
||
match self {
|
||
Self::Allowed => "入站已放行".into(),
|
||
Self::Missing => "缺少放行规则,手机可能连不上".into(),
|
||
Self::BlockedByPolicy(reason) | Self::Unknown(reason) => reason.clone(),
|
||
Self::BlockedByRule(names) => format!(
|
||
"存在阻止本程序入站的规则({names}),它的优先级高于放行规则。\
|
||
点「放行防火墙」会连同这些阻止规则一起清掉。"
|
||
),
|
||
Self::Unsupported(reason) => (*reason).to_owned(),
|
||
}
|
||
}
|
||
}
|
||
|
||
fn current_exe() -> Result<PathBuf> {
|
||
std::env::current_exe().context("无法获取本程序路径")
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Windows
|
||
|
||
/// 探测脚本。刻意用 PowerShell 而不是 netsh:
|
||
///
|
||
/// `netsh advfirewall show` 的**值**也会跟随系统语言本地化(中文 Windows 上
|
||
/// 是「允许 / 阻止 / 任何 / 是」),按英文关键字匹配在中文系统上必然误判;
|
||
/// 而 `Get-NetFirewallRule` 返回的是枚举,`Allow`/`Block`/`Any`/`True`
|
||
/// 在任何语言下都是这几个字面量。
|
||
///
|
||
/// 输出被压成一行一条的管道分隔记录,便于用纯函数解析、也便于在非 Windows
|
||
/// 上对解析逻辑写测试。
|
||
/// 注意查询是**按程序路径**做的,不是只按规则显示名。
|
||
///
|
||
/// 用户在 Windows 弹出「安全警报」时点了「取消」,系统会自己建一条针对该
|
||
/// 可执行文件的**阻止**规则,名字是程序名而不是我们的 `QFT Desktop`。
|
||
/// 只按显示名查完全看不到它,却又是它压着我们的放行规则——
|
||
/// 表现就是「点了放行、界面显示已放行,手机依然连不上」。
|
||
#[cfg(target_os = "windows")]
|
||
fn probe_script(exe: &str) -> String {
|
||
format!(
|
||
r#"
|
||
$ErrorActionPreference='SilentlyContinue'
|
||
$exe = '{exe}'
|
||
Get-NetFirewallProfile | ForEach-Object {{
|
||
"PROFILE|$($_.Name)|$($_.Enabled)|$($_.DefaultInboundAction)|$($_.AllowInboundRules)"
|
||
}}
|
||
$byName = Get-NetFirewallRule -DisplayName '{RULE_NAME}'
|
||
$byPath = Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule
|
||
@($byName) + @($byPath) | Where-Object {{ $_ }} | Sort-Object -Property Name -Unique | ForEach-Object {{
|
||
"RULE|$($_.Enabled)|$($_.Direction)|$($_.Action)|$($_.Profile)|$($_.DisplayName)"
|
||
}}
|
||
"#,
|
||
// PowerShell 单引号字符串里只需把单引号写成两个,反斜杠不转义,
|
||
// 正好适合 Windows 路径
|
||
exe = exe.replace('\'', "''"),
|
||
)
|
||
}
|
||
|
||
/// 解析 [`PROBE_SCRIPT`] 的输出。放在这里而不是内联,是为了能在任意平台
|
||
/// 上用真实样本做测试——Windows 专有逻辑最容易腐烂在没人跑的地方。
|
||
///
|
||
/// 判定顺序是有讲究的:
|
||
/// 1. **先看系统级策略**。`AllowInboundRules=False` 对应「阻止所有传入连接,
|
||
/// 包括位于允许应用列表中的应用」。这项打开时用户点多少次放行都没有
|
||
/// 任何变化,必须先报出来,否则会得出「规则已就绪」的错误结论。
|
||
/// 2. **再看有没有阻止规则**。Windows 里 Block 永远压过 Allow,旧版本残留
|
||
/// 的阻止规则会让新加的放行规则彻底失效,而界面上两条都显示「已启用」。
|
||
/// 3. **最后才看放行规则**,且必须是 `Any` profile——手机连的那块 Direct AP
|
||
/// 虚拟网卡会被判为「公用网络」,只覆盖专用/域的规则在它上面不适用。
|
||
pub fn classify_probe(probe_output: &str) -> FirewallStatus {
|
||
let mut any_firewall_on = false;
|
||
let mut blanket_block: Vec<&str> = Vec::new();
|
||
let mut has_block_rule = false;
|
||
let mut blocking_rules: Vec<&str> = Vec::new();
|
||
let mut has_usable_allow = false;
|
||
|
||
for line in probe_output.lines() {
|
||
let fields: Vec<&str> = line.trim().split('|').collect();
|
||
match fields.as_slice() {
|
||
["PROFILE", name, enabled, _default_inbound, allow_inbound] => {
|
||
let on = enabled.eq_ignore_ascii_case("true");
|
||
any_firewall_on |= on;
|
||
// AllowInboundRules 还可能是 NotConfigured,那不算封禁
|
||
if on && allow_inbound.eq_ignore_ascii_case("false") {
|
||
blanket_block.push(name);
|
||
}
|
||
}
|
||
["RULE", enabled, direction, action, profile, display_name] => {
|
||
if !direction.eq_ignore_ascii_case("inbound") {
|
||
continue;
|
||
}
|
||
// 只有启用中的阻止规则才真正生效
|
||
if action.eq_ignore_ascii_case("block") && enabled.eq_ignore_ascii_case("true") {
|
||
has_block_rule = true;
|
||
blocking_rules.push(*display_name);
|
||
} else if enabled.eq_ignore_ascii_case("true")
|
||
&& action.eq_ignore_ascii_case("allow")
|
||
&& profile.eq_ignore_ascii_case("any")
|
||
{
|
||
has_usable_allow = true;
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
if !blanket_block.is_empty() {
|
||
return FirewallStatus::BlockedByPolicy(format!(
|
||
"{} 配置文件启用了「阻止所有传入连接,包括位于允许应用列表中的应用」。\
|
||
这一项打开时,放行规则不起任何作用,必须先在\
|
||
「Windows 安全中心 → 防火墙和网络保护」里把它关掉。",
|
||
blanket_block.join("、")
|
||
));
|
||
}
|
||
if has_block_rule {
|
||
// 这类规则多半是用户在「安全警报」弹窗上点了取消后由系统自动建的,
|
||
// 名字五花八门,所以把实际名字列出来,用户手动排查时才有的放矢。
|
||
return FirewallStatus::BlockedByRule(blocking_rules.join("、"));
|
||
}
|
||
// 防火墙整个关着时入站不会被拦,没必要要求存在规则
|
||
if !any_firewall_on || has_usable_allow {
|
||
FirewallStatus::Allowed
|
||
} else {
|
||
FirewallStatus::Missing
|
||
}
|
||
}
|
||
|
||
#[cfg(target_os = "windows")]
|
||
fn run_powershell(script: &str) -> std::io::Result<std::process::Output> {
|
||
use std::os::windows::process::CommandExt;
|
||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||
std::process::Command::new("powershell")
|
||
.args(["-NoProfile", "-NonInteractive", "-Command", script])
|
||
.creation_flags(CREATE_NO_WINDOW)
|
||
.output()
|
||
}
|
||
|
||
#[cfg(target_os = "windows")]
|
||
pub fn status() -> FirewallStatus {
|
||
let exe = match current_exe() {
|
||
Ok(path) => path.display().to_string(),
|
||
Err(e) => return FirewallStatus::Unknown(format!("{e}")),
|
||
};
|
||
match run_powershell(&probe_script(&exe)) {
|
||
Ok(out) => {
|
||
let text = String::from_utf8_lossy(&out.stdout);
|
||
if text.trim().is_empty() {
|
||
return FirewallStatus::Unknown(
|
||
"防火墙查询没有返回任何内容,可能是 PowerShell 执行策略受限".into(),
|
||
);
|
||
}
|
||
classify_probe(&text)
|
||
}
|
||
Err(e) => FirewallStatus::Unknown(format!("无法执行 PowerShell:{e}")),
|
||
}
|
||
}
|
||
|
||
/// 触发 UAC 并添加入站放行规则。
|
||
///
|
||
/// 用临时批处理承载命令,而不是把参数塞进 PowerShell 的 `-ArgumentList`:
|
||
/// 程序路径里带空格时,经过 PowerShell 再到 netsh 会被重新分词,
|
||
/// 引号层层嵌套极易出错。批处理文件由我们自己写死引号,不再被二次解析。
|
||
///
|
||
/// `profile=any` 是刻意的,早先写成 `private,domain` 是个真实的 bug:
|
||
/// Windows 对没见过的 Wi-Fi 默认归类为**公用网络**,此时 private 规则
|
||
/// 根本不适用——规则建了、也显示已启用,但连接照样被拦,极难排查。
|
||
/// 收窄到某个 profile 并不能带来实际安全收益:QFT 的入站真正靠的是
|
||
/// 连接码里的秘密加失败计数,没有秘密的连接一律被拒。
|
||
#[cfg(target_os = "windows")]
|
||
pub fn grant() -> Result<()> {
|
||
use std::os::windows::process::CommandExt;
|
||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||
|
||
let exe = current_exe()?;
|
||
let exe_literal = exe.display().to_string().replace('\'', "''");
|
||
let script = std::env::temp_dir().join(format!("qft-firewall-{}.ps1", std::process::id()));
|
||
// 写成 .ps1 文件而不是把命令塞进 -ArgumentList:程序路径里带空格时,
|
||
// 经过 PowerShell 再到子进程会被重新分词,引号层层嵌套极易出错。
|
||
// 脚本文件里的单引号字符串不会被二次解析。
|
||
let content = format!(
|
||
"$ErrorActionPreference='Stop'\r\n\
|
||
$exe = '{exe_literal}'\r\n\
|
||
# 先清掉一切针对本程序的入站阻止规则。Windows 在用户点掉「安全警报」\r\n\
|
||
# 弹窗时会自动建这种规则,名字是程序名,且优先级高于任何放行规则。\r\n\
|
||
Get-NetFirewallApplicationFilter -Program $exe -ErrorAction SilentlyContinue |\r\n\
|
||
\x20 Get-NetFirewallRule -ErrorAction SilentlyContinue |\r\n\
|
||
\x20 Where-Object {{ $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }} |\r\n\
|
||
\x20 Remove-NetFirewallRule -ErrorAction SilentlyContinue\r\n\
|
||
# 重建放行规则。profile=any 是刻意的:Windows 把没见过的网络\r\n\
|
||
# (尤其是 Direct AP 虚拟网卡)默认归为公用网络。\r\n\
|
||
Remove-NetFirewallRule -DisplayName '{RULE_NAME}' -ErrorAction SilentlyContinue\r\n\
|
||
New-NetFirewallRule -DisplayName '{RULE_NAME}' -Direction Inbound -Program $exe \\\r\n\
|
||
\x20 -Action Allow -Profile Any -Enabled True | Out-Null\r\n"
|
||
);
|
||
std::fs::write(&script, content).context("写入临时放行脚本失败")?;
|
||
|
||
let status = std::process::Command::new("powershell")
|
||
.args([
|
||
"-NoProfile",
|
||
"-WindowStyle",
|
||
"Hidden",
|
||
"-Command",
|
||
&format!(
|
||
"Start-Process -FilePath powershell -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File','\"{}\"' -Verb RunAs -WindowStyle Hidden -Wait",
|
||
script.display()
|
||
),
|
||
])
|
||
.creation_flags(CREATE_NO_WINDOW)
|
||
.status();
|
||
|
||
let _ = std::fs::remove_file(&script);
|
||
match status {
|
||
// 用户在 UAC 上点了「否」时 Start-Process 会失败,退出码非 0
|
||
Ok(s) if s.success() => Ok(()),
|
||
Ok(_) => bail!("未获得管理员授权,防火墙规则没有添加"),
|
||
Err(e) => bail!("调用提权失败:{e}"),
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------- macOS
|
||
|
||
#[cfg(target_os = "macos")]
|
||
pub fn status() -> FirewallStatus {
|
||
const TOOL: &str = "/usr/libexec/ApplicationFirewall/socketfilterfw";
|
||
if !std::path::Path::new(TOOL).exists() {
|
||
return FirewallStatus::Unknown("系统上没有 socketfilterfw".into());
|
||
}
|
||
|
||
// 应用层防火墙没开时,入站根本不会被拦,不需要做任何事
|
||
match std::process::Command::new(TOOL).arg("--getglobalstate").output() {
|
||
Ok(out) => {
|
||
let text = String::from_utf8_lossy(&out.stdout);
|
||
if text.contains("disabled") {
|
||
return FirewallStatus::Allowed;
|
||
}
|
||
}
|
||
Err(e) => return FirewallStatus::Unknown(format!("无法执行 socketfilterfw:{e}")),
|
||
}
|
||
|
||
let Ok(exe) = current_exe() else {
|
||
return FirewallStatus::Unknown("无法获取本程序路径".into());
|
||
};
|
||
match std::process::Command::new(TOOL)
|
||
.args(["--getappblocked", &exe.display().to_string()])
|
||
.output()
|
||
{
|
||
Ok(out) => {
|
||
let text = String::from_utf8_lossy(&out.stdout).to_lowercase();
|
||
if text.contains("blocked") && !text.contains("not blocked") {
|
||
FirewallStatus::Missing
|
||
} else {
|
||
FirewallStatus::Allowed
|
||
}
|
||
}
|
||
Err(e) => FirewallStatus::Unknown(format!("查询失败:{e}")),
|
||
}
|
||
}
|
||
|
||
/// 通过系统授权对话框把本程序加入放行列表。
|
||
///
|
||
/// macOS 通常会在首次监听时自己弹「是否允许接受传入网络连接」,
|
||
/// 那一步就够了;这里只处理用户当时点了「拒绝」的情况。
|
||
#[cfg(target_os = "macos")]
|
||
pub fn grant() -> Result<()> {
|
||
let exe = current_exe()?;
|
||
let path = exe.display().to_string();
|
||
if path.contains('"') || path.contains('\\') {
|
||
bail!("程序路径包含无法安全转义的字符,请手动在「系统设置 → 网络 → 防火墙」里放行")
|
||
}
|
||
let inner = format!(
|
||
"/usr/libexec/ApplicationFirewall/socketfilterfw --add '{path}' && \
|
||
/usr/libexec/ApplicationFirewall/socketfilterfw --unblockapp '{path}'"
|
||
);
|
||
let script = format!("do shell script \"{inner}\" with administrator privileges");
|
||
|
||
let status = std::process::Command::new("osascript")
|
||
.args(["-e", &script])
|
||
.status()
|
||
.context("调用 osascript 失败")?;
|
||
if status.success() {
|
||
Ok(())
|
||
} else {
|
||
bail!("未获得授权,防火墙放行没有生效")
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Linux
|
||
|
||
#[cfg(all(unix, not(target_os = "macos")))]
|
||
pub fn status() -> FirewallStatus {
|
||
// 各发行版的防火墙前端差异过大(ufw / firewalld / 裸 iptables / nftables),
|
||
// 自动改规则风险高于收益,只做检测与提示。
|
||
FirewallStatus::Unsupported("Linux 上请按下方提示手动放行")
|
||
}
|
||
|
||
#[cfg(all(unix, not(target_os = "macos")))]
|
||
pub fn grant() -> Result<()> {
|
||
bail!("Linux 上不自动修改防火墙,请按界面提示手动执行")
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 手动说明
|
||
|
||
/// 自动放行失败或不支持时,给用户可以照抄的命令。
|
||
pub fn manual_instructions(port: u16) -> String {
|
||
let exe = current_exe()
|
||
.map(|p| p.display().to_string())
|
||
.unwrap_or_else(|_| "qft-desktop".into());
|
||
|
||
#[cfg(target_os = "windows")]
|
||
{
|
||
// 程序级规则不按端口放行,端口只在手动说明的 Linux 分支里用得上
|
||
let _ = port;
|
||
// -Profile Any 是必须的。这里早先写的是 Private,Domain,与本模块
|
||
// grant() 的注释自相矛盾,照抄的用户会重建出一条在公用网络上
|
||
// (也就是 Direct AP 虚拟网卡上)根本不适用的规则。
|
||
format!(
|
||
"以管理员身份打开 PowerShell,依次执行:\n\n\
|
||
# 1. 清掉系统自动创建的阻止规则(它优先级高于放行规则)\n\
|
||
Get-NetFirewallApplicationFilter -Program \"{exe}\" |\n\
|
||
\x20 Get-NetFirewallRule |\n\
|
||
\x20 Where-Object {{ $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }} |\n\
|
||
\x20 Remove-NetFirewallRule\n\n\
|
||
# 2. 建立覆盖所有网络类型的放行规则\n\
|
||
Remove-NetFirewallRule -DisplayName \"{RULE_NAME}\" -ErrorAction SilentlyContinue\n\
|
||
New-NetFirewallRule -DisplayName \"{RULE_NAME}\" -Direction Inbound \\\n\
|
||
\x20 -Program \"{exe}\" -Action Allow -Profile Any\n\n\
|
||
# 3. 确认没有开启「阻止所有传入连接」\n\
|
||
Get-NetFirewallProfile | Select-Object Name,Enabled,AllowInboundRules\n\n\
|
||
第 3 步里 AllowInboundRules 若为 False,需要到\n\
|
||
「Windows 安全中心 → 防火墙和网络保护 → 对应网络」里\n\
|
||
取消勾选「阻止所有传入连接」,否则前两步都不会起作用。"
|
||
)
|
||
}
|
||
#[cfg(target_os = "macos")]
|
||
{
|
||
let _ = port;
|
||
format!(
|
||
"打开「系统设置 → 网络 → 防火墙 → 选项」,把下面这个程序设为\
|
||
「允许传入连接」:\n\n{exe}\n\n\
|
||
若防火墙本身是关闭的,则无需任何操作。"
|
||
)
|
||
}
|
||
#[cfg(all(unix, not(target_os = "macos")))]
|
||
{
|
||
let _ = exe;
|
||
format!(
|
||
"按你所用的防火墙执行其一:\n\n\
|
||
ufw: sudo ufw allow {port}/tcp && sudo ufw allow {}/udp\n\
|
||
firewalld: sudo firewall-cmd --add-port={port}/tcp --add-port={}/udp --permanent && sudo firewall-cmd --reload",
|
||
port - 1,
|
||
port - 1,
|
||
)
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn status_query_never_panics_and_is_classified() {
|
||
// 只做只读查询,不改动任何系统设置
|
||
let value = status();
|
||
match &value {
|
||
FirewallStatus::Allowed
|
||
| FirewallStatus::Missing
|
||
| FirewallStatus::Unsupported(_) => {}
|
||
FirewallStatus::Unknown(reason)
|
||
| FirewallStatus::BlockedByPolicy(reason)
|
||
| FirewallStatus::BlockedByRule(reason) => {
|
||
assert!(!reason.is_empty(), "原因说明不能为空")
|
||
}
|
||
}
|
||
// Allowed / Unknown / Unsupported 都不该催促用户去点按钮
|
||
assert_eq!(
|
||
value.needs_action(),
|
||
matches!(
|
||
value,
|
||
FirewallStatus::Missing
|
||
| FirewallStatus::BlockedByPolicy(_)
|
||
| FirewallStatus::BlockedByRule(_)
|
||
)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn manual_instructions_mention_the_actual_program() {
|
||
let text = manual_instructions(39393);
|
||
assert!(!text.trim().is_empty());
|
||
// 说明里必须出现可操作的东西:程序路径或具体端口
|
||
assert!(
|
||
text.contains("qft") || text.contains("39393") || text.contains("防火墙"),
|
||
"说明应包含可操作信息:{text}"
|
||
);
|
||
}
|
||
|
||
// 探测脚本的输出形状是固定的,解析逻辑在任何平台上都能测。
|
||
// Windows 专有代码最容易腐烂在没人跑的地方,这几个用例就是防这个的。
|
||
const PROFILES_OK: &str = "PROFILE|Domain|True|Block|True\n\
|
||
PROFILE|Private|True|Block|True\n\
|
||
PROFILE|Public|True|Block|True";
|
||
|
||
#[test]
|
||
fn allow_rule_must_cover_any_profile() {
|
||
let only_private = format!("{PROFILES_OK}\nRULE|True|Inbound|Allow|Domain, Private|QFT Desktop");
|
||
assert_eq!(classify_probe(&only_private), FirewallStatus::Missing);
|
||
|
||
let any = format!("{PROFILES_OK}\nRULE|True|Inbound|Allow|Any|QFT Desktop");
|
||
assert_eq!(classify_probe(&any), FirewallStatus::Allowed);
|
||
}
|
||
|
||
#[test]
|
||
fn disabled_allow_rule_does_not_count() {
|
||
let text = format!("{PROFILES_OK}\nRULE|False|Inbound|Allow|Any|QFT Desktop");
|
||
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
|
||
}
|
||
|
||
#[test]
|
||
fn outbound_rules_are_irrelevant() {
|
||
let text = format!("{PROFILES_OK}\nRULE|True|Outbound|Allow|Any|QFT Desktop");
|
||
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
|
||
// 出站的阻止规则同样不该被误判成入站被拦
|
||
let text = format!("{PROFILES_OK}\nRULE|True|Outbound|Block|Any|随便什么");
|
||
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
|
||
}
|
||
|
||
/// 这是「点了放行还是连不上」最常见的成因:用户在安全警报弹窗上点了取消,
|
||
/// 系统按程序路径建了一条阻止规则,名字和我们的规则完全不同。
|
||
#[test]
|
||
fn auto_created_block_rule_beats_our_allow_rule() {
|
||
let text = format!(
|
||
"{PROFILES_OK}\n\
|
||
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
|
||
RULE|True|Inbound|Block|Public|qft-desktop.exe"
|
||
);
|
||
match classify_probe(&text) {
|
||
FirewallStatus::BlockedByRule(names) => {
|
||
assert!(names.contains("qft-desktop.exe"), "要报出实际规则名:{names}");
|
||
}
|
||
other => panic!("阻止规则必须压过放行规则,实际判定为 {other:?}"),
|
||
}
|
||
// 这一类是可以靠提权自动清掉的
|
||
assert!(classify_probe(&text).fixable_by_grant());
|
||
assert!(classify_probe(&text).needs_action());
|
||
}
|
||
|
||
#[test]
|
||
fn disabled_block_rule_is_harmless() {
|
||
let text = format!(
|
||
"{PROFILES_OK}\n\
|
||
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
|
||
RULE|False|Inbound|Block|Public|qft-desktop.exe"
|
||
);
|
||
assert_eq!(classify_probe(&text), FirewallStatus::Allowed);
|
||
}
|
||
|
||
/// 「阻止所有传入连接」打开时,加多少放行规则都没用,
|
||
/// 必须报成另一种状态,否则用户会一直点那个不起作用的按钮。
|
||
#[test]
|
||
fn blanket_inbound_block_is_reported_separately() {
|
||
let text = "PROFILE|Domain|True|Block|True\n\
|
||
PROFILE|Private|True|Block|True\n\
|
||
PROFILE|Public|True|Block|False\n\
|
||
RULE|True|Inbound|Allow|Any|QFT Desktop";
|
||
match classify_probe(text) {
|
||
FirewallStatus::BlockedByPolicy(reason) => {
|
||
assert!(reason.contains("Public"), "要指出是哪个配置文件:{reason}");
|
||
}
|
||
other => panic!("应报告系统级封禁,实际为 {other:?}"),
|
||
}
|
||
// 这一类我们不去动,属于用户的安全设置
|
||
assert!(!classify_probe(text).fixable_by_grant());
|
||
assert!(classify_probe(text).needs_action());
|
||
}
|
||
|
||
#[test]
|
||
fn blanket_block_on_a_disabled_profile_is_ignored() {
|
||
// 防火墙本身关着的配置文件,AllowInboundRules 是什么都无所谓
|
||
let text = "PROFILE|Domain|True|Block|True\n\
|
||
PROFILE|Private|True|Block|True\n\
|
||
PROFILE|Public|False|Block|False\n\
|
||
RULE|True|Inbound|Allow|Any|QFT Desktop";
|
||
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
|
||
}
|
||
|
||
#[test]
|
||
fn firewall_entirely_off_needs_no_rule() {
|
||
let text = "PROFILE|Domain|False|Block|True\n\
|
||
PROFILE|Private|False|Block|True\n\
|
||
PROFILE|Public|False|Block|True";
|
||
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
|
||
}
|
||
|
||
#[test]
|
||
fn not_configured_inbound_setting_is_not_a_blanket_block() {
|
||
let text = "PROFILE|Public|True|Block|NotConfigured\n\
|
||
RULE|True|Inbound|Allow|Any|QFT Desktop";
|
||
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
|
||
}
|
||
|
||
#[test]
|
||
fn every_status_has_a_non_empty_detail() {
|
||
for value in [
|
||
FirewallStatus::Allowed,
|
||
FirewallStatus::Missing,
|
||
FirewallStatus::BlockedByPolicy("策略".into()),
|
||
FirewallStatus::BlockedByRule("规则名".into()),
|
||
FirewallStatus::Unknown("原因".into()),
|
||
FirewallStatus::Unsupported("不支持"),
|
||
] {
|
||
assert!(!value.detail().trim().is_empty(), "{value:?} 缺少说明文案");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn manual_instructions_never_recreate_the_profile_bug() {
|
||
let text = manual_instructions(39393);
|
||
#[cfg(target_os = "windows")]
|
||
{
|
||
assert!(
|
||
text.contains("-Profile Any"),
|
||
"手动命令必须覆盖所有网络类型,否则在公用网络上无效:{text}"
|
||
);
|
||
assert!(
|
||
!text.contains("Private,Domain"),
|
||
"照抄这条命令会重建出在 Direct AP 网卡上不适用的规则:{text}"
|
||
);
|
||
}
|
||
let _ = text;
|
||
}
|
||
|
||
#[test]
|
||
fn status_is_read_only_and_repeatable() {
|
||
// 检测必须无副作用:连续调用结果一致,且不改动任何系统设置
|
||
assert_eq!(status(), status());
|
||
}
|
||
}
|
||
|