[browser] Autofill for Edge and Chrome: custos-browser (which login fits which page, native messaging frames), custos-native (the host), the MV3 extension
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "custos-browser"
|
||||
description = "Custos in the browser: which login may be filled into which page, and Chrome's native messaging frames"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
zeroize.workspace = true
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Chrome's native messaging frames: a 32-bit length in native byte order (little-endian on every machine
|
||||
//! Custos runs on), then that many bytes of UTF-8 JSON. Messages to the host are capped here at 64 KiB (the
|
||||
//! desktop's pipe limit); Chrome itself refuses messages to the browser over 1 MB.
|
||||
//!
|
||||
//! Frames can hold a login's password: they are `Zeroizing`, so the bytes are wiped when dropped.
|
||||
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// The largest message the extension may send to the host.
|
||||
pub const MAX_TO_HOST: usize = 64 * 1024;
|
||||
/// The largest message Chrome accepts from a host.
|
||||
pub const MAX_TO_BROWSER: usize = 1024 * 1024;
|
||||
|
||||
/// Reads one frame. `Ok(None)` when the browser closed the stream (the extension disconnected).
|
||||
pub fn read_frame(r: &mut impl Read) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
|
||||
let mut len = [0u8; 4];
|
||||
match r.read_exact(&mut len) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
let n = u32::from_le_bytes(len) as usize;
|
||||
if n > MAX_TO_HOST {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large"));
|
||||
}
|
||||
let mut buf = Zeroizing::new(vec![0u8; n]);
|
||||
r.read_exact(&mut buf)?;
|
||||
Ok(Some(buf))
|
||||
}
|
||||
|
||||
/// Writes one frame and flushes it (Chrome reads frame by frame).
|
||||
pub fn write_frame(w: &mut impl Write, msg: &[u8]) -> io::Result<()> {
|
||||
if msg.len() > MAX_TO_BROWSER {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large"));
|
||||
}
|
||||
w.write_all(&(msg.len() as u32).to_le_bytes())?;
|
||||
w.write_all(msg)?;
|
||||
w.flush()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn frames_round_trip_and_oversized_ones_are_refused() {
|
||||
let mut out = Vec::new();
|
||||
write_frame(&mut out, br#"{"op":"browser_status"}"#).unwrap();
|
||||
write_frame(&mut out, b"{}").unwrap();
|
||||
assert_eq!(&out[..4], &23u32.to_le_bytes());
|
||||
let mut r = &out[..];
|
||||
assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), br#"{"op":"browser_status"}"#);
|
||||
assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), b"{}");
|
||||
assert!(read_frame(&mut r).unwrap().is_none(), "end of stream is the extension going away");
|
||||
// A length over the limit is refused before anything is allocated.
|
||||
let big = ((MAX_TO_HOST + 1) as u32).to_le_bytes();
|
||||
assert_eq!(read_frame(&mut &big[..]).unwrap_err().kind(), io::ErrorKind::InvalidData);
|
||||
// A frame cut short is an error, not a short message.
|
||||
let mut cut = 10u32.to_le_bytes().to_vec();
|
||||
cut.extend_from_slice(b"{}");
|
||||
assert!(read_frame(&mut &cut[..]).is_err());
|
||||
assert!(write_frame(&mut Vec::new(), &vec![b' '; MAX_TO_BROWSER + 1]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! What the browser extension may fill where (docs/BROWSER.md). The extension and its native host live in
|
||||
//! this public repository; the rules that decide which login goes into which page live here too, so the
|
||||
//! desktop app and anyone reviewing the extension apply the same ones.
|
||||
//!
|
||||
//! - [`Origin`]: a page's origin as the browser reports it (never as the page claims).
|
||||
//! - [`login_matches`]: does a login's stored URL belong to that origin? Its host or a subdomain of it,
|
||||
//! same scheme, same port when the login names one. Never a "similar" name, so look-alike domains
|
||||
//! (`paypa1.com`, `paypal.com.evil.net`) never match.
|
||||
//! - [`framing`]: Chrome's native messaging frames (a 4-byte little-endian length, then JSON).
|
||||
//!
|
||||
//! ```
|
||||
//! use custos_browser::{login_matches, Origin};
|
||||
//! let page = Origin::parse("https://accounts.github.com/login?return=/")?;
|
||||
//! assert!(login_matches("https://github.com", &page).is_some());
|
||||
//! assert!(login_matches("https://github.com.evil.net", &page).is_none());
|
||||
//! # Ok::<(), custos_browser::OriginError>(())
|
||||
//! ```
|
||||
|
||||
pub mod framing;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// A page's origin: scheme, host (lowercase, no trailing dot) and port (the scheme's default when absent).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Origin {
|
||||
pub scheme: Scheme,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Scheme {
|
||||
Https,
|
||||
Http,
|
||||
}
|
||||
|
||||
impl Scheme {
|
||||
fn default_port(self) -> u16 {
|
||||
match self {
|
||||
Scheme::Https => 443,
|
||||
Scheme::Http => 80,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum OriginError {
|
||||
/// Not an `http(s)://host…` URL.
|
||||
NotWeb,
|
||||
/// A host that is empty, too long or has characters a host cannot have.
|
||||
BadHost,
|
||||
BadPort,
|
||||
}
|
||||
|
||||
impl fmt::Display for OriginError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
OriginError::NotWeb => "not a web address",
|
||||
OriginError::BadHost => "not a valid host",
|
||||
OriginError::BadPort => "not a valid port",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for OriginError {}
|
||||
|
||||
/// Splits `scheme://host:port/…` (userinfo refused: `https://bank.com@evil.net` must not read as bank.com).
|
||||
fn split(url: &str, default: Option<Scheme>) -> Result<(Scheme, String, Option<u16>), OriginError> {
|
||||
let url = url.trim();
|
||||
let (scheme, rest) = match url.split_once("://") {
|
||||
Some((s, rest)) => match s.to_ascii_lowercase().as_str() {
|
||||
"https" => (Scheme::Https, rest),
|
||||
"http" => (Scheme::Http, rest),
|
||||
_ => return Err(OriginError::NotWeb),
|
||||
},
|
||||
None => (default.ok_or(OriginError::NotWeb)?, url),
|
||||
};
|
||||
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
|
||||
if authority.contains('@') {
|
||||
return Err(OriginError::BadHost);
|
||||
}
|
||||
let (host, port) = if let Some(v6) = authority.strip_prefix('[') {
|
||||
let (h, after) = v6.split_once(']').ok_or(OriginError::BadHost)?;
|
||||
(format!("[{}]", h.to_ascii_lowercase()), after.strip_prefix(':'))
|
||||
} else {
|
||||
match authority.rsplit_once(':') {
|
||||
Some((h, p)) => (h.to_ascii_lowercase(), Some(p)),
|
||||
None => (authority.to_ascii_lowercase(), None),
|
||||
}
|
||||
};
|
||||
let host = host.trim_end_matches('.').to_string();
|
||||
let ok = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_' | '[' | ']' | ':');
|
||||
if host.is_empty() || host.len() > 253 || !host.chars().all(ok) || host.contains("..") {
|
||||
return Err(OriginError::BadHost);
|
||||
}
|
||||
let port = match port {
|
||||
None | Some("") => None,
|
||||
Some(p) => Some(
|
||||
p.parse::<u16>()
|
||||
.map_err(|_| OriginError::BadPort)
|
||||
.and_then(|n| if n == 0 { Err(OriginError::BadPort) } else { Ok(n) })?,
|
||||
),
|
||||
};
|
||||
Ok((scheme, host, port))
|
||||
}
|
||||
|
||||
impl Origin {
|
||||
/// A page URL as the browser reports it (`sender.url`, the tab's URL).
|
||||
pub fn parse(url: &str) -> Result<Origin, OriginError> {
|
||||
let (scheme, host, port) = split(url, None)?;
|
||||
Ok(Origin { scheme, port: port.unwrap_or(scheme.default_port()), host })
|
||||
}
|
||||
|
||||
fn is_loopback(&self) -> bool {
|
||||
self.host == "localhost"
|
||||
|| self.host.ends_with(".localhost")
|
||||
|| self.host == "127.0.0.1"
|
||||
|| self.host == "[::1]"
|
||||
}
|
||||
|
||||
fn is_ip(&self) -> bool {
|
||||
self.host.starts_with('[')
|
||||
|| self.host.split('.').all(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// May a login be filled into this page at all? Only over https, or plain http on this machine.
|
||||
pub fn fillable(&self) -> bool {
|
||||
self.scheme == Scheme::Https || self.is_loopback()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Origin {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let scheme = match self.scheme {
|
||||
Scheme::Https => "https",
|
||||
Scheme::Http => "http",
|
||||
};
|
||||
if self.port == self.scheme.default_port() {
|
||||
write!(f, "{scheme}://{}", self.host)
|
||||
} else {
|
||||
write!(f, "{scheme}://{}:{}", self.host, self.port)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How well a login's URL fits a page, best first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Match {
|
||||
/// The page is on the login's host itself (`www.` counts as the host).
|
||||
Exact,
|
||||
/// The page is on a subdomain of the login's host (`accounts.github.com` for `github.com`).
|
||||
Subdomain,
|
||||
}
|
||||
|
||||
/// Does the login stored with `item_url` belong on `page`? `None` when it must not be offered there.
|
||||
///
|
||||
/// A stored URL without a scheme (`github.com/login`) means https. The page must be fillable, the schemes
|
||||
/// equal, the port equal when the stored URL names one (else the page's must be the scheme's default), and
|
||||
/// the page's host the login's host or a subdomain of it. A login for a bare top-level name (`com`) or for
|
||||
/// an IP address matches only that exact host.
|
||||
pub fn login_matches(item_url: &str, page: &Origin) -> Option<Match> {
|
||||
if !page.fillable() {
|
||||
return None;
|
||||
}
|
||||
let (scheme, host, port) = split(item_url, Some(Scheme::Https)).ok()?;
|
||||
if scheme != page.scheme || port.unwrap_or(scheme.default_port()) != page.port {
|
||||
return None;
|
||||
}
|
||||
let strip = |h: &str| h.strip_prefix("www.").map(str::to_string).unwrap_or_else(|| h.to_string());
|
||||
let (item, at) = (strip(&host), strip(&page.host));
|
||||
if item == at {
|
||||
return Some(Match::Exact);
|
||||
}
|
||||
if page.is_ip() || !item.contains('.') || item.starts_with('[') {
|
||||
return None;
|
||||
}
|
||||
at.strip_suffix(&item).filter(|rest| rest.ends_with('.')).map(|_| Match::Subdomain)
|
||||
}
|
||||
|
||||
/// The best match among a login's URLs.
|
||||
pub fn best_match<'a>(urls: impl IntoIterator<Item = &'a str>, page: &Origin) -> Option<Match> {
|
||||
urls.into_iter().filter_map(|u| login_matches(u, page)).min()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn page(u: &str) -> Origin {
|
||||
Origin::parse(u).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn origins_parse_as_the_browser_reports_them() {
|
||||
assert_eq!(
|
||||
page("https://GitHub.com./login?x=1#y"),
|
||||
Origin { scheme: Scheme::Https, host: "github.com".into(), port: 443 }
|
||||
);
|
||||
assert_eq!(page("http://localhost:5173/").port, 5173);
|
||||
assert_eq!(page("https://[::1]:8443/").host, "[::1]");
|
||||
assert_eq!(page("https://bank.cz").to_string(), "https://bank.cz");
|
||||
assert_eq!(page("http://127.0.0.1:8080/a").to_string(), "http://127.0.0.1:8080");
|
||||
for bad in [
|
||||
"ftp://x.cz",
|
||||
"file:///C:/a.html",
|
||||
"chrome-extension://abc/",
|
||||
"javascript:alert(1)",
|
||||
"about:blank",
|
||||
"https://",
|
||||
"https://a..b.cz/",
|
||||
"https://bank.cz:99999/",
|
||||
"https://bank.cz:0/",
|
||||
"https://bad host.cz/",
|
||||
] {
|
||||
assert!(Origin::parse(bad).is_err(), "{bad}");
|
||||
}
|
||||
// Userinfo is refused outright: it is how look-alike links hide their real host.
|
||||
assert_eq!(Origin::parse("https://bank.cz@evil.net/"), Err(OriginError::BadHost));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_login_matches_its_host_and_its_subdomains_only() {
|
||||
let gh = page("https://github.com/login");
|
||||
assert_eq!(login_matches("https://github.com", &gh), Some(Match::Exact));
|
||||
assert_eq!(login_matches("github.com/login", &gh), Some(Match::Exact), "no scheme means https");
|
||||
assert_eq!(login_matches("https://www.github.com/", &gh), Some(Match::Exact));
|
||||
assert_eq!(login_matches("https://github.com", &page("https://www.github.com/")), Some(Match::Exact));
|
||||
assert_eq!(login_matches("https://github.com", &page("https://gist.github.com/")), Some(Match::Subdomain));
|
||||
// A login for a subdomain does not go to its parent or its siblings.
|
||||
assert_eq!(login_matches("https://gist.github.com", &gh), None);
|
||||
assert_eq!(login_matches("https://gist.github.com", &page("https://api.github.com/")), None);
|
||||
// Look-alikes never match.
|
||||
for evil in [
|
||||
"https://github.com.evil.net/",
|
||||
"https://evilgithub.com/",
|
||||
"https://github.co/",
|
||||
"https://githuh.com/",
|
||||
"https://xn--gthub-cta.com/",
|
||||
] {
|
||||
assert_eq!(login_matches("https://github.com", &page(evil)), None, "{evil}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scheme_port_and_plain_http_are_strict() {
|
||||
// Never over plain http on the internet, even for a login saved with http.
|
||||
assert_eq!(login_matches("http://intranet.example", &page("http://intranet.example/")), None);
|
||||
// On this machine plain http is fine, with the port the login names.
|
||||
assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:5173/login")), Some(Match::Exact));
|
||||
assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:8080/")), None);
|
||||
assert_eq!(login_matches("http://localhost", &page("http://localhost:8080/")), None);
|
||||
// An https login does not go to the http page of the same host, nor the other way round.
|
||||
assert_eq!(login_matches("https://localhost", &page("http://localhost/")), None);
|
||||
assert_eq!(
|
||||
login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa:5001/")),
|
||||
Some(Match::Exact)
|
||||
);
|
||||
assert_eq!(login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa/")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_names_and_addresses_match_exactly_only() {
|
||||
assert_eq!(login_matches("https://192.168.1.1", &page("https://192.168.1.1/")), Some(Match::Exact));
|
||||
assert_eq!(login_matches("https://168.1.1", &page("https://192.168.1.1/")), None);
|
||||
assert_eq!(login_matches("https://cz", &page("https://bank.cz/")), None);
|
||||
assert_eq!(login_matches("https://[::1]", &page("https://[::1]/")), Some(Match::Exact));
|
||||
assert_eq!(login_matches("not a url at all", &page("https://bank.cz/")), None);
|
||||
assert_eq!(login_matches("", &page("https://bank.cz/")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_best_of_several_urls_wins() {
|
||||
let p = page("https://www.github.com/");
|
||||
assert_eq!(best_match(["https://gitlab.com", "https://github.com"], &p), Some(Match::Exact));
|
||||
assert_eq!(best_match(["https://gitlab.com"], &p), None);
|
||||
assert_eq!(
|
||||
best_match(["https://github.com", "https://www.github.com"], &page("https://gist.github.com/")),
|
||||
Some(Match::Subdomain)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "custos-native"
|
||||
description = "Custos's native messaging host: the browser extension's way to the desktop Custos"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
custos-browser = { path = "../custos-browser" }
|
||||
serde_json.workspace = true
|
||||
zeroize.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Pipes", "Win32_System_Threading"] }
|
||||
@@ -0,0 +1,240 @@
|
||||
//! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Edge or Chrome starts it
|
||||
//! when the extension connects, and talks to it over stdin/stdout in native messaging frames. It forwards
|
||||
//! three requests to the desktop Custos over its Domi pipe and returns the answers:
|
||||
//!
|
||||
//! - `browser_status`: is Custos running and unlocked;
|
||||
//! - `browser_match { origin }`: the logins for a page (title, username; never a password);
|
||||
//! - `browser_fill { id, origin }`: one login's username, password and 2FA code, when it matches the page.
|
||||
//!
|
||||
//! The host adds nothing and decides nothing: Custos checks the origin against the login and asks the
|
||||
//! user once whether this host may use web logins. It forwards only those three requests, rebuilt from
|
||||
//! their known fields, so the extension cannot reach Custos's other Domi requests through it. It refuses
|
||||
//! a pipe that is not served by custos.exe.
|
||||
|
||||
use std::io::{self, Write};
|
||||
|
||||
use custos_browser::framing::{read_frame, write_frame};
|
||||
use serde_json::{Value, json};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
const PIPE: &str = r"\\.\pipe\custos-domi";
|
||||
const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill"];
|
||||
|
||||
/// The request Custos gets: only known fields, of the right types.
|
||||
fn rebuild(msg: &[u8]) -> Result<Value, &'static str> {
|
||||
let v: Value = serde_json::from_slice(msg).map_err(|_| "bad_request")?;
|
||||
let op = v.get("op").and_then(Value::as_str).filter(|o| OPS.contains(o)).ok_or("bad_request")?;
|
||||
let mut out = json!({ "op": op, "app": "Custos for your browser" });
|
||||
if op != "browser_status" {
|
||||
let origin = v.get("origin").and_then(Value::as_str).filter(|o| o.len() <= 2048).ok_or("bad_request")?;
|
||||
out["origin"] = origin.into();
|
||||
}
|
||||
if op == "browser_fill" {
|
||||
let id = v.get("id").and_then(Value::as_str).filter(|i| i.len() <= 128).ok_or("bad_request")?;
|
||||
out["id"] = id.into();
|
||||
}
|
||||
// The extension's own request number comes back with the answer, so it can pair them.
|
||||
if let Some(n) = v.get("seq").and_then(Value::as_u64) {
|
||||
out["seq"] = n.into();
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn error(code: &str, seq: Option<u64>) -> Vec<u8> {
|
||||
serde_json::to_vec(&json!({ "ok": false, "error": code, "seq": seq })).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn answer(msg: &[u8], pipe: &str) -> Zeroizing<Vec<u8>> {
|
||||
let seq = serde_json::from_slice::<Value>(msg).ok().and_then(|v| v.get("seq").and_then(Value::as_u64));
|
||||
let req = match rebuild(msg) {
|
||||
Ok(r) => r,
|
||||
Err(code) => return Zeroizing::new(error(code, seq)),
|
||||
};
|
||||
let bytes = Zeroizing::new(serde_json::to_vec(&req).unwrap_or_default());
|
||||
match pipe::call(pipe, &bytes) {
|
||||
Ok(resp) => {
|
||||
// Custos does not know the extension's request number: put it back.
|
||||
let Ok(mut v) = serde_json::from_slice::<Value>(&resp) else {
|
||||
return Zeroizing::new(error("bad_answer", seq));
|
||||
};
|
||||
if let (Some(obj), Some(n)) = (v.as_object_mut(), seq) {
|
||||
obj.insert("seq".into(), n.into());
|
||||
}
|
||||
let out = Zeroizing::new(serde_json::to_vec(&v).unwrap_or_default());
|
||||
zeroize_json(v);
|
||||
out
|
||||
}
|
||||
Err(code) => Zeroizing::new(error(code, seq)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wipes the strings of a parsed answer (it can hold a password) before dropping it.
|
||||
fn zeroize_json(v: Value) {
|
||||
use zeroize::Zeroize;
|
||||
match v {
|
||||
Value::String(mut s) => s.zeroize(),
|
||||
Value::Array(a) => a.into_iter().for_each(zeroize_json),
|
||||
Value::Object(o) => o.into_iter().for_each(|(_, v)| zeroize_json(v)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Tests point the host at another Custos.
|
||||
let pipe = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_string());
|
||||
let (mut stdin, stdout) = (io::stdin().lock(), io::stdout());
|
||||
loop {
|
||||
let msg = match read_frame(&mut stdin) {
|
||||
Ok(Some(m)) => m,
|
||||
// The extension disconnected, or sent something that is not a frame: done.
|
||||
Ok(None) | Err(_) => return,
|
||||
};
|
||||
let out = answer(&msg, &pipe);
|
||||
let mut w = stdout.lock();
|
||||
if write_frame(&mut w, &out).is_err() || w.flush().is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod pipe {
|
||||
use std::time::Duration;
|
||||
|
||||
use windows_sys::Win32::Foundation::{
|
||||
CloseHandle, ERROR_FILE_NOT_FOUND, ERROR_PIPE_BUSY, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE,
|
||||
INVALID_HANDLE_VALUE,
|
||||
};
|
||||
use windows_sys::Win32::Storage::FileSystem::{CreateFileW, OPEN_EXISTING, ReadFile, WriteFile};
|
||||
use windows_sys::Win32::System::Pipes::{
|
||||
GetNamedPipeServerProcessId, PIPE_READMODE_MESSAGE, SetNamedPipeHandleState, WaitNamedPipeW,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
struct Handle(HANDLE);
|
||||
impl Drop for Handle {
|
||||
fn drop(&mut self) {
|
||||
unsafe { CloseHandle(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
fn wide(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
|
||||
fn server_exe(h: HANDLE) -> Option<String> {
|
||||
unsafe {
|
||||
let mut pid = 0u32;
|
||||
if GetNamedPipeServerProcessId(h, &mut pid) == 0 {
|
||||
return None;
|
||||
}
|
||||
let p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
|
||||
if p.is_null() {
|
||||
return None;
|
||||
}
|
||||
let p = Handle(p);
|
||||
let mut buf = vec![0u16; 1024];
|
||||
let mut len = buf.len() as u32;
|
||||
let ok = QueryFullProcessImageNameW(p.0, 0, buf.as_mut_ptr(), &mut len);
|
||||
(ok != 0).then(|| String::from_utf16_lossy(&buf[..len as usize]))
|
||||
}
|
||||
}
|
||||
|
||||
/// One request, one answer. The error is a code the extension shows as a sentence.
|
||||
pub fn call(name: &str, request: &[u8]) -> Result<Zeroizing<Vec<u8>>, &'static str> {
|
||||
let w = wide(name);
|
||||
unsafe {
|
||||
let mut h = INVALID_HANDLE_VALUE;
|
||||
// Busy: every instance is in use. Not found: Custos is between instances for a moment, or not running.
|
||||
for _ in 0..50 {
|
||||
h = CreateFileW(
|
||||
w.as_ptr(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
0,
|
||||
std::ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
);
|
||||
if h != INVALID_HANDLE_VALUE {
|
||||
break;
|
||||
}
|
||||
match GetLastError() {
|
||||
ERROR_PIPE_BUSY => {
|
||||
WaitNamedPipeW(w.as_ptr(), 200);
|
||||
}
|
||||
ERROR_FILE_NOT_FOUND => std::thread::sleep(Duration::from_millis(20)),
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
if h == INVALID_HANDLE_VALUE {
|
||||
return Err("not_running");
|
||||
}
|
||||
let h = Handle(h);
|
||||
// Anything else serving this pipe could collect passwords: only custos.exe gets the request.
|
||||
if !server_exe(h.0).unwrap_or_default().to_lowercase().ends_with("\\custos.exe") {
|
||||
return Err("not_custos");
|
||||
}
|
||||
let mode = PIPE_READMODE_MESSAGE;
|
||||
SetNamedPipeHandleState(h.0, &mode, std::ptr::null(), std::ptr::null());
|
||||
let mut n = 0u32;
|
||||
if WriteFile(h.0, request.as_ptr(), request.len() as u32, &mut n, std::ptr::null_mut()) == 0 {
|
||||
return Err("not_running");
|
||||
}
|
||||
let mut buf = Zeroizing::new(vec![0u8; 64 * 1024]);
|
||||
if ReadFile(h.0, buf.as_mut_ptr(), buf.len() as u32, &mut n, std::ptr::null_mut()) == 0 {
|
||||
return Err("no_answer");
|
||||
}
|
||||
buf.truncate(n as usize);
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod pipe {
|
||||
pub fn call(_: &str, _: &[u8]) -> Result<zeroize::Zeroizing<Vec<u8>>, &'static str> {
|
||||
Err("not_running")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_the_three_browser_requests_pass_rebuilt_from_known_fields() {
|
||||
let fill = rebuild(br#"{"op":"browser_fill","id":"abc","origin":"https://github.com","seq":7,"ref":"domi://arca/x","namespace":"arca"}"#).unwrap();
|
||||
assert_eq!(
|
||||
fill,
|
||||
json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "seq": 7, "app": "Custos for your browser" })
|
||||
);
|
||||
assert_eq!(rebuild(br#"{"op":"browser_status"}"#).unwrap()["op"], "browser_status");
|
||||
assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz"}"#).is_ok());
|
||||
// Custos's other Domi requests never pass through the browser's host.
|
||||
for other in [
|
||||
r#"{"op":"get","ref":"domi://arca/rclone-config-pass"}"#,
|
||||
r#"{"op":"list","namespace":"arca"}"#,
|
||||
r#"{"op":"set","ref":"domi://x/y","value":"v"}"#,
|
||||
r#"{"op":"subkey"}"#,
|
||||
] {
|
||||
assert_eq!(rebuild(other.as_bytes()), Err("bad_request"), "{other}");
|
||||
}
|
||||
// Missing or wrong fields.
|
||||
assert!(rebuild(br#"{"op":"browser_fill","origin":"https://a.cz"}"#).is_err());
|
||||
assert!(rebuild(br#"{"op":"browser_match","origin":5}"#).is_err());
|
||||
assert!(rebuild(b"not json").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_custos_the_answer_says_so_and_keeps_the_request_number() {
|
||||
let out = answer(br#"{"op":"browser_status","seq":3}"#, r"\\.\pipe\custos-test-nobody-here");
|
||||
let v: Value = serde_json::from_slice(&out).unwrap();
|
||||
assert_eq!(v, json!({ "ok": false, "error": "not_running", "seq": 3 }));
|
||||
let bad: Value = serde_json::from_slice(&answer(br#"{"op":"get","seq":4}"#, PIPE)).unwrap();
|
||||
assert_eq!(bad, json!({ "ok": false, "error": "bad_request", "seq": 4 }));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user