[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,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