sanitize: strip control and bidi characters from client text (M7)

This commit is contained in:
raucao committed 2026-11-30 10:31:00 +04:00
1 parent 5d750fb0d3
commit 75f4998ced
9 files changed
+279 -41

No files matched your search

+11
View File
@@ -988,6 +988,17 @@ UI lives in `data/resources/ui/*.blp` (Blueprint) and is compiled to `.ui` by
- Event content and client-supplied metadata are attacker-controlled text. Show
them only as **plain labels** (`use_markup(false)`), never as Pango markup — a
client must not be able to forge formatting that looks like Regent's own UI.
Before it is shown **or stored**, client text is also stripped of control
characters and Unicode bidi/directional markers (`U+061C`, `U+200E`, `U+200F`,
`U+202A..=U+202E`, `U+2066..=U+2069`) and bounded, by `crate::sanitize`
(`clean`/`clean_bound`/`clean_opt`). That covers the `connect` metadata
(`client_info`), the `nostrconnect://` fields and `requested_perms`, a user
label (`apps::bound_label`), the **load** paths of `apps.json`,
`profiles.json` (`display_name`) and the activity log (`audit::bound` +
`recent`), and headless stdout (defence in depth at the print site): an ANSI
escape in a name is a terminal escape in `--pair` output, and a bidi override
makes an app name read as another. An empty-after-cleaning value counts as
absent.
They are deliberately **not** `selectable`: a selectable `GtkLabel` selects its
whole text the moment it takes focus, and a dialog focuses its first focusable
widget on open, so the first value would open with a selection highlight behind
+1
View File
@@ -56,6 +56,7 @@ cargo_build = custom_target(binary_name,
'src/portal.rs',
'src/runner.rs',
'src/runtime.rs',
'src/sanitize.rs',
'src/signer/approval.rs',
'src/signer/mod.rs',
'src/signer/policy.rs',
+8 -5
View File
@@ -205,14 +205,17 @@ async fn finish_pairing(
.await
.map_err(|error| format!("pairing failed: {error}"))?;
let name = pairing
.name
.clone()
.unwrap_or_else(|| "an unnamed application".to_string());
// Sanitized again here even though `parse_client_uri` already cleaned them:
// this is the one place a client string reaches a terminal, and defence in
// depth is cheap. An ANSI escape in a name would otherwise run in the shell.
let name = crate::sanitize::clean_bound(
pairing.name.as_deref().unwrap_or("an unnamed application"),
64,
);
let asked = pairing
.requested
.as_deref()
.map(|perms| format!(" — it asked for {perms}"))
.map(|perms| format!(" — it asked for {}", crate::sanitize::clean_bound(perms, 200)))
.unwrap_or_default();
println!(
"regent: paired with {name} ({}){asked}",
+1
View File
@@ -10,6 +10,7 @@ mod instance;
mod portal;
mod runner;
mod runtime;
mod sanitize;
mod signer;
mod state;
mod store;
+82
View File
@@ -0,0 +1,82 @@
//! Stripping and bounding attacker-controlled text.
//!
//! Event content and client metadata are supplied by an application we do not
//! trust. They are already rendered as plain text — never Pango markup — but two
//! other tricks survive that:
//!
//! - **Control characters.** A `\x1b[2J` in a client name is an ANSI escape in
//! the terminal (`regent --pair` prints it to stdout), and a newline forges a
//! second line in a log or a dialog.
//! - **Unicode bidi overrides.** `U+202E` and friends reorder a rendered label,
//! so a declared app name can *look* like a different app or a trusted path.
//!
//! This is the one place that decides what "clean" means; every client string
//! that reaches a dialog, `apps.json`, the activity log or stdout goes through
//! it. Empty-after-cleaning counts as absent at the call sites.
/// Remove control characters and Unicode bidi/directional formatting
/// characters, then trim.
///
/// `char::is_control` covers C0/C1 (`\n`, `\r`, `\t`, `\x1b`, …); the explicit
/// set is the bidi controls and directional marks it does not.
pub fn clean(value: &str) -> String {
value
.chars()
.filter(|c| !c.is_control() && !is_bidi(*c))
.collect::<String>()
.trim()
.to_string()
}
/// [`clean`], then cap to at most `limit` characters.
pub fn clean_bound(value: &str, limit: usize) -> String {
clean(value).chars().take(limit).collect()
}
/// [`clean_bound`] for an optional field: `None`, or the cleaned value when it
/// is non-empty afterwards. An all-control value counts as absent.
pub fn clean_opt(value: Option<String>, limit: usize) -> Option<String> {
value
.map(|value| clean_bound(&value, limit))
.filter(|value| !value.is_empty())
}
/// Whether a character reorders or overrides text direction.
fn is_bidi(c: char) -> bool {
matches!(
c,
'\u{061C}' // Arabic letter mark
| '\u{200E}' // left-to-right mark
| '\u{200F}' // right-to-left mark
| '\u{202A}'..='\u{202E}' // embeddings / overrides / pop
| '\u{2066}'..='\u{2069}' // isolates
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn control_and_bidi_characters_are_stripped() {
assert_eq!(clean("a\nb\tc"), "abc");
assert_eq!(clean("\u{1b}[2Jclear"), "[2Jclear", "the escape byte goes");
assert_eq!(clean("safe\u{202E}name"), "safename", "the override goes");
assert_eq!(clean("iso\u{2066}late"), "isolate");
assert_eq!(clean("mark\u{200F}"), "mark");
// Trimming is part of cleaning.
assert_eq!(clean(" spaced "), "spaced");
// Ordinary non-ASCII is kept.
assert_eq!(clean("café ☕"), "café ☕");
}
#[test]
fn clean_bound_bounds_after_cleaning() {
let hostile = format!("{}\n{}", "n".repeat(10_000), "evil");
let cleaned = clean_bound(&hostile, 64);
assert_eq!(cleaned.chars().count(), 64);
assert!(!cleaned.contains('\n'));
// The bound applies to the cleaned text, not the input.
assert_eq!(clean_bound("a\u{202E}b\u{202E}c", 2), "ab");
}
}
+61 -17
View File
@@ -637,30 +637,26 @@ pub fn parse_client_uri(uri: &str) -> Result<ClientPairing> {
client,
relays,
secret,
// Bound client-supplied text: it reaches a dialog, the log and apps.json.
// An empty value is treated as absent — some clients always include
// Bound and sanitize client-supplied text: it reaches a dialog, the log
// and apps.json, and must not carry control or bidi characters. An empty
// value is treated as absent — some clients always include
// `name=&url=&image=&perms=`, and a stored `Some("")` reads as "declared
// nothing" everywhere it is shown.
name: name
.filter(|name| !name.trim().is_empty())
.map(|name| bound(&name, 64)),
.map(|name| crate::sanitize::clean_bound(&name, 64)),
url: url
.filter(|url| !url.trim().is_empty())
.map(|url| bound(&url, 256)),
.map(|url| crate::sanitize::clean_bound(&url, 256)),
image: image
.filter(|image| !image.trim().is_empty())
.map(|image| bound(&image, 256)),
.map(|image| crate::sanitize::clean_bound(&image, 256)),
requested: requested
.filter(|perms| !perms.trim().is_empty())
.map(|perms| bound(&perms, 200)),
.map(|perms| crate::sanitize::clean_bound(&perms, 200)),
})
}
/// Trim client-supplied text to a sane length.
fn bound(value: &str, limit: usize) -> String {
value.chars().take(limit).collect()
}
/// Register a client-initiated pairing and send it the `connect` response.
///
/// Approve **before** publishing: the client validates the secret and usually
@@ -1356,11 +1352,11 @@ fn client_info(public_key: &PublicKey, params: &[String]) -> ClientInfo {
};
ClientInfo {
public_key: *public_key,
name: field("name"),
url: field("url"),
// Bounded like the `nostrconnect://` path: this reaches apps.json, and
// an icon URL is a fetch input.
image: field("image").map(|image| bound(&image, 256)),
name: crate::sanitize::clean_opt(field("name"), 64),
url: crate::sanitize::clean_opt(field("url"), 256),
// Bounded and sanitized like the `nostrconnect://` path: this reaches
// apps.json, and an icon URL is a fetch input.
image: crate::sanitize::clean_opt(field("image"), 256),
}
}
@@ -1374,7 +1370,10 @@ fn requested_perms(params: &[String]) -> Option<String> {
if raw.is_empty() {
return None;
}
Some(raw.chars().take(200).collect())
// A fourth client-string path: it reaches the pairing dialog's "Asked for"
// row and headless stdout, so it is cleaned and bounded like the others.
let cleaned = crate::sanitize::clean_bound(raw, 200);
(!cleaned.is_empty()).then_some(cleaned)
}
/// An event a client asked to have signed, still unsigned.
@@ -3046,6 +3045,51 @@ mod tests {
);
}
/// Client metadata is sanitized and bounded on both paths (M7).
#[test]
fn client_metadata_is_sanitized_and_bounded() {
let keys = Keys::generate();
let hostile = "n".repeat(10_000);
let with = vec![
keys.public_key().to_hex(),
String::new(),
String::new(),
format!(
r#"{{"name":"{hostile}\u202Eevil","url":"https://x.example/","image":"https://x.example/i.png"}}"#
),
];
let info = client_info(&keys.public_key(), &with);
let name = info.name.unwrap();
assert_eq!(name.chars().count(), 64, "the name is bounded");
assert!(
!name.contains('\u{202E}'),
"the bidi override is stripped"
);
// `requested_perms` is a fourth path: cleaned and bounded.
let perms = vec![
keys.public_key().to_hex(),
String::new(),
format!("sign_event:1\u{2066}{}", "x".repeat(500)),
];
let requested = requested_perms(&perms).unwrap();
assert!(requested.chars().count() <= 200);
assert!(!requested.contains('\u{2066}'), "the isolate is stripped");
}
/// A bidi override in a `nostrconnect://` name is stripped.
#[test]
fn a_nostrconnect_name_with_a_bidi_override_is_cleaned() {
let keys = Keys::generate();
let uri = format!(
"nostrconnect://{}?relay=wss%3A%2F%2Frelay.example.com&secret=s\
&name=Pay%E2%80%AEpal",
keys.public_key().to_hex()
);
let pairing = parse_client_uri(&uri).expect("parse");
assert_eq!(pairing.name.as_deref(), Some("Paypal"));
}
/// The client learns the signer key from the response author and must get
/// its own secret back as the result.
#[test]
+46 -3
View File
@@ -86,10 +86,10 @@ impl App {
}
}
/// Trim a user- or client-supplied name and cap it, because it reaches
/// `apps.json`, a dialog and the activity log.
/// Trim and sanitize a user- or client-supplied name and cap it, because it
/// reaches `apps.json`, a dialog and the activity log.
fn bound_label(value: &str) -> Option<String> {
let value: String = value.trim().chars().take(64).collect();
let value = crate::sanitize::clean_bound(value, 64);
(!value.is_empty()).then_some(value)
}
@@ -133,6 +133,7 @@ impl AppRegistry {
Ok(contents) => match serde_json::from_str::<Self>(&contents) {
Ok(mut registry) => {
registry.path = path;
registry.sanitize_metadata();
registry
}
Err(error) => {
@@ -167,6 +168,20 @@ impl AppRegistry {
Ok(())
}
/// Re-clean the stored client metadata on load.
///
/// `apps.json` is on disk and could be hand-edited, or written by an older
/// build; these are display fields and must not carry control or bidi
/// characters into the UI. Same bounds `approve` applies to what it stores.
fn sanitize_metadata(&mut self) {
for app in &mut self.apps {
app.name = crate::sanitize::clean_opt(app.name.take(), 64);
app.label = crate::sanitize::clean_opt(app.label.take(), 64);
app.url = crate::sanitize::clean_opt(app.url.take(), 256);
app.image = crate::sanitize::clean_opt(app.image.take(), 256);
}
}
pub fn contains(&self, public_key: &PublicKey) -> bool {
let hex = public_key.to_hex();
self.apps.iter().any(|app| app.public_key == hex)
@@ -657,4 +672,32 @@ mod tests {
.all(|app| app.identity == identity.to_hex()));
assert_eq!(registry.list_for(identity).len(), 1);
}
/// `apps.json` is on disk and could be hand-edited or written by an older
/// build: its display fields are cleaned on load (M7).
#[test]
fn hostile_metadata_is_cleaned_when_the_registry_loads() {
let path = temp_path();
let key = Keys::generate().public_key().to_hex();
let json = serde_json::json!({
"apps": [{
"public_key": key,
"name": "bad\u{202E}name".to_string(),
"image": "https://x.example/i\u{1b}.png".to_string(),
"url": format!("{}{}", "u".repeat(500), "url"),
"approved_at": 1,
"identity": key,
"policy": {"methods": [], "kinds": []},
}],
})
.to_string();
std::fs::write(&path, json).expect("write");
let registry = AppRegistry::at(path.clone());
let app = &registry.list()[0];
assert_eq!(app.name.as_deref(), Some("badname"), "bidi stripped");
assert!(!app.image.as_deref().unwrap().contains('\u{1b}'));
assert_eq!(app.url.as_deref().unwrap().chars().count(), 256);
std::fs::remove_file(path).ok();
}
}
+32 -5
View File
@@ -70,10 +70,7 @@ const KEEP_ENTRIES: usize = 500;
const MAX_NAME_CHARS: usize = 64;
fn bound(text: &str) -> String {
text.chars()
.filter(|c| !c.is_control())
.take(MAX_NAME_CHARS)
.collect()
crate::sanitize::clean_bound(text, MAX_NAME_CHARS)
}
/// A handle to the on-disk log.
@@ -149,7 +146,15 @@ impl ActivityLog {
let mut entries: Vec<Entry> = BufReader::new(file)
.lines()
.map_while(std::result::Result::ok)
.filter_map(|line| serde_json::from_str(&line).ok())
.filter_map(|line| serde_json::from_str::<Entry>(&line).ok())
// Entries written before the name was sanitized — or a hand-edited
// log — must not render control/bidi characters either.
.map(|mut entry| {
if let Some(name) = &entry.name {
entry.name = Some(bound(name));
}
entry
})
.collect();
entries.reverse();
entries.truncate(limit);
@@ -293,6 +298,28 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// A name written before sanitization (or by hand) is cleaned when the log
/// is read, so the Activity view cannot render bidi/control characters.
#[test]
fn a_bidi_name_is_cleaned_when_the_log_is_read() {
let (dir, log) = scratch();
std::fs::create_dir_all(&dir).unwrap();
let line = serde_json::json!({
"at": 1,
"app": "aa",
"name": "evil\u{202E}name".to_string(),
"method": "sign_event",
"kind": 1,
"outcome": "allowed-once",
})
.to_string();
std::fs::write(dir.join("activity.jsonl"), format!("{line}\n")).unwrap();
let entry = &log.recent(1)[0];
assert_eq!(entry.name.as_deref(), Some("evilname"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn clearing_one_identity_keeps_the_others() {
let (dir, log) = scratch();
+37 -11
View File
@@ -157,11 +157,12 @@ impl Profiles {
}
/// The profile name for display, if one was fetched.
///
/// Sanitized and bounded on **read**: `profiles.json` is on disk and could
/// be hand-edited, and a kind-0 name is attacker-controlled data that
/// renders in the switcher and the identities list.
pub fn display_name(&self, key: &PublicKey) -> Option<String> {
self.get(key)
.and_then(|profile| profile.display_name)
.map(|name| name.trim().to_string())
.filter(|name| !name.is_empty())
crate::sanitize::clean_opt(self.get(key).and_then(|profile| profile.display_name), 64)
}
/// The identity's picture URL, if one was fetched and is still well formed.
@@ -890,17 +891,15 @@ fn profile_from_metadata(metadata: &Metadata) -> Profile {
}
}
/// Trim and drop a blank name, so the store never holds a padded one.
/// Trim, sanitize and drop a blank name, so the store never holds a padded one
/// or one carrying control/bidi characters.
fn bound_name(value: Option<String>) -> Option<String> {
let value = value?;
let value = value.trim();
(!value.is_empty()).then(|| value.to_string())
crate::sanitize::clean_opt(value, 64)
}
/// Trim, cap and drop a blank picture URL.
/// Trim, sanitize, cap and drop a blank picture URL.
fn bound_picture(value: Option<&str>) -> Option<String> {
let value: String = value?.trim().chars().take(MAX_PICTURE_LEN).collect();
(!value.is_empty()).then_some(value)
crate::sanitize::clean_opt(value.map(str::to_string), MAX_PICTURE_LEN)
}
#[cfg(test)]
@@ -931,6 +930,33 @@ mod tests {
profiles.get(key).unwrap()
}
/// A cached `display_name` is sanitized and bounded on **read**: the file is
/// on disk and a kind-0 name is attacker-controlled (M7).
#[test]
fn a_cached_display_name_is_cleaned_on_read() {
let dir = std::env::temp_dir().join(format!(
"regent-profiles-name-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let public_key = key();
let path = dir.join("profiles.json");
let json = serde_json::json!({
public_key.to_hex(): {
"display_name": format!("{}\u{202E}evil", "n".repeat(500)),
},
})
.to_string();
std::fs::write(&path, json).unwrap();
let profiles = Profiles::at(path);
let name = profiles.display_name(&public_key).unwrap();
assert_eq!(name.chars().count(), 64, "bounded on read");
assert!(!name.contains('\u{202E}'), "bidi stripped on read");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn profiles_round_trip_and_refresh_after_a_day() {
let dir = std::env::temp_dir().join(format!("regent-profiles-{}", std::process::id()));