git.delta.rocks / fleet / refs/commits / 0ea4b47ffa04

difftreelog

source

remowt/cmds/remowt-agent/src/main.rs11.7 KiBsourcehistory
1use std::borrow::Cow;2use std::collections::{BTreeMap, HashMap};3use std::fs::Permissions;4use std::future::pending;5use std::io;6use std::os::unix::fs::PermissionsExt as _;7use std::path::PathBuf;8use std::sync::{Arc, Mutex, OnceLock};910use bifrostlink::declarative::RemoteEndpoints;11use bifrostlink::Rpc;12use bifrostlink_ports::stdio::from_stdio;13use bifrostlink_ports::unix_socket::from_socket;14use clap::Parser;15use remowt_endpoints::{16	forward::Forward, fs::Fs, iroh_tunnel::IrohTunnel, nix_daemon::NixDaemon, pty::Pty,17	subprocess::Subprocess, systemd::Systemd,18};19use remowt_link_shared::iroh_tunnel::TunnelDialer;20use remowt_link_shared::{editor::EditorEndpointsClient, Address, BifConfig};21use remowt_polkit_shared::{emphasize, Identity, PidDisplay};22use remowt_ui_prompt::bifrost::PromptEndpointsClient;23use remowt_ui_prompt::rofi::RofiPrompter;24use remowt_ui_prompt::{PrependSourcePrompter, Prompter, Source};25use tokio::fs;26use tokio::net::UnixStream;27use tokio::runtime::Builder;28use tokio::task::AbortHandle;29use tracing::{debug, trace};30use zbus::fdo;31use zbus::zvariant::{OwnedValue, Str};32use zbus::{interface, Connection};33use zbus_polkit::policykit1::Subject;3435use self::helper::{Helper, SocketHelper, SuidHelper};3637pub mod askpass;38pub mod bus;39pub mod editor;40pub mod helper;4142struct CancelTaskOnDrop {43	tasks: Arc<Mutex<HashMap<String, AbortHandle>>>,44	handle: String,45}46impl Drop for CancelTaskOnDrop {47	fn drop(&mut self) {48		debug!("cancel on drop");49		if let Some(task) = self50			.tasks51			.lock()52			.expect("not poisoned")53			.remove(&self.handle)54		{55			task.abort();56		}57	}58}5960struct Agent<H, P> {61	tasks: Arc<Mutex<HashMap<String, AbortHandle>>>,62	helper: H,63	prompter: P,64}65impl<H, P> Agent<H, P> {66	fn new(helper: H, prompter: P) -> Self {67		Agent {68			tasks: Arc::new(Mutex::new(HashMap::new())),69			helper,70			prompter,71		}72	}73}7475#[interface(name = "org.freedesktop.PolicyKit1.AuthenticationAgent")]76impl<H, P> Agent<H, P>77where78	H: Helper + Clone + Send + Sync + 'static,79	P: Prompter + Clone + Send + Sync + 'static,80{81	/// BeginAuthentication method82	#[allow(clippy::too_many_arguments)]83	async fn begin_authentication(84		&self,85		action_id: String,86		message: String,87		_icon_name: String,88		mut details: BTreeMap<String, String>,89		cookie: String,90		identities: Vec<Identity>,91	) -> zbus::fdo::Result<()> {92		use std::fmt::Write;93		debug!("begin auth");94		let _cancel_guard = Arc::new(OnceLock::new());95		let task = {96			let helper = self.helper.clone();97			let prompter = self.prompter.clone();98			let cookie = cookie.clone();99			let _cancel_guard = _cancel_guard.clone();100			tokio::task::spawn(async move {101				let _cancel_guard = _cancel_guard.clone();102				trace!("conversation task");103				let mut description = format!("{message}\n\n<b>Action id:</b> {action_id}",);104				if let Some(subject) = details.remove("polkit.caller-pid") {105					let _ = write!(description, "\n<b>Caller:</b> ");106					if let Ok(pid) = subject.parse::<u32>() {107						let _ = write!(description, "{}", PidDisplay(pid));108					} else {109						let _ = write!(description, "{}", emphasize("invalid pid"));110					}111				}112				if let Some(subject) = details.remove("polkit.subject-pid") {113					let _ = write!(description, "\n<b>Subject:</b> ");114					if let Ok(pid) = subject.parse::<u32>() {115						let _ = write!(description, "{}", PidDisplay(pid));116					} else {117						let _ = write!(description, "{}", emphasize("invalid pid"));118					}119				}120				let mut prompter = PrependSourcePrompter {121					source: vec![Source(Cow::Borrowed("polkit agent"))],122					description: description.clone(),123					prompter,124				};125126				let identity_displays: Vec<String> =127					identities.iter().map(|v| v.to_string()).collect();128				let identity_displays: Vec<&str> =129					identity_displays.iter().map(|v| v.as_str()).collect();130				debug!("choose identity");131				let choosen_identity = match identity_displays.len() {132					0 => {133						return Err(fdo::Error::AuthFailed(134							"no identity to authenticate as".to_owned(),135						))136					}137					1 => 0,138					_ => {139						prompter140							.prompt_enum(141								"Identity",142								"Select identity to use for polkit authorization",143								&identity_displays,144								&[],145							)146							.await?147					}148				};149				debug!("identity chosen");150151				let _ = write!(152					description,153					"\n<b>Identity:</b> {}",154					identities[choosen_identity as usize]155				);156				prompter.description = description;157158				prompter.source.push(Source(Cow::Borrowed("polkit daemon")));159160				helper161					.help_me(162						&cookie,163						prompter,164						identities[choosen_identity as usize].clone(),165					)166					.await167					.map_err(|e| fdo::Error::Failed(e.to_string()))?;168				// let connection = Connection::system().await?;169				// let helper = PolkitHelperProxy::new(&connection).await?;170171				Ok(())172			})173		};174		self.tasks175			.lock()176			.unwrap()177			.insert(cookie.clone(), task.abort_handle());178		debug!("abort handle stored");179		let _ = _cancel_guard.set(CancelTaskOnDrop {180			tasks: self.tasks.clone(),181			handle: cookie.clone(),182		});183184		let _ = task.await;185186		Ok(())187	}188189	/// CancelAuthentication method190	async fn cancel_authentication(&self, cookie: &str) -> zbus::fdo::Result<()> {191		debug!("auth cancelled");192		if let Some(abort) = self.tasks.lock().unwrap().remove(cookie) {193			debug!("abort handle found");194			abort.abort();195		}196		// debug!("Authentication cancled ! {cookie}");197		Ok(())198	}199}200201const OBJ_PATH: &str = "/org/freedesktop/PolicyKit1/AuthenticationAgent";202203#[derive(Parser)]204enum Opts {205	AskPass {206		prompt: String,207		description: String,208	},209	Editor {210		/// Argument to nvim211		path: String,212	},213	/// Expose a remote TCP/UDP address on the local (User) machine, printing the local port.214	Forward {215		/// Protocol: `tcp` (ssh or iroh) or `udp` (iroh-only).216		proto: ForwardProto,217		/// Remote socket address to expose locally, e.g. `127.0.0.1:8080`.218		addr: String,219	},220	RealAgent {221		#[arg(long)]222		path: Option<PathBuf>,223		/// Expect own address to be AgentPrivileged, skip installing polkit agent224		#[arg(long)]225		privileged: bool,226		#[arg(long)]227		local: bool,228	},229	LocalAgent,230}231232#[derive(Clone, Copy, clap::ValueEnum)]233enum ForwardProto {234	Tcp,235	Udp,236}237238fn main() -> anyhow::Result<()> {239	tracing_subscriber::fmt()240		.with_writer(io::stderr)241		.without_time()242		.init();243	let opts = Opts::parse();244245	let runtime = Builder::new_current_thread().enable_all().build()?;246247	match opts {248		Opts::AskPass {249			prompt,250			description,251		} => runtime.block_on(askpass::ask(&prompt, description)),252		Opts::LocalAgent => runtime.block_on(main_real()),253		Opts::Editor { path } => runtime.block_on(editor::edit(path)),254		Opts::Forward { proto, addr } => {255			runtime.block_on(editor::forward(matches!(proto, ForwardProto::Udp), addr))256		}257		Opts::RealAgent {258			path,259			privileged,260			local,261		} => runtime.block_on(main_real_agent(path, privileged, local)),262	}263}264async fn main_real() -> anyhow::Result<()> {265	let system_conn = Connection::system().await?;266	let helper = SocketHelper {267		fallback: SuidHelper,268	};269	register_auth_agent(&system_conn, Agent::new(helper, RofiPrompter)).await?;270271	let session_conn = Connection::session().await?;272	askpass::serve(&session_conn, RofiPrompter).await?;273274	let _keep_alive = (system_conn, session_conn);275	pending().await276}277async fn main_real_agent(278	path: Option<PathBuf>,279	privileged: bool,280	local: bool,281) -> anyhow::Result<()> {282	let address = if privileged {283		Address::AgentPrivileged284	} else {285		Address::Agent286	};287	let mut rpc = Rpc::<BifConfig>::new(address);288289	let dialer = Arc::new(TunnelDialer::new());290	Fs::new().register_endpoints(&mut rpc);291	Systemd.register_endpoints(&mut rpc);292	Pty::new(dialer.clone()).register_endpoints(&mut rpc);293	Subprocess::new(dialer.clone()).register_endpoints(&mut rpc);294	NixDaemon::new(dialer.clone()).register_endpoints(&mut rpc);295	IrohTunnel::new(dialer.clone()).register_endpoints(&mut rpc);296	Forward::new(dialer.clone()).register_endpoints(&mut rpc);297298	remowt_plugin::host::serve(&mut rpc);299300	let user_prompter = PromptEndpointsClient::wrap(rpc.remote(Address::User));301	let editor_client = EditorEndpointsClient::wrap(rpc.remote(Address::User));302303	let bus = bus::spawn().await?;304	askpass::serve(&bus.conn, user_prompter.clone()).await?;305	editor::serve(&bus.conn, editor_client).await?;306307	let helpers = tempfile::Builder::new().prefix("remowt-path.").tempdir()?;308	let exe = std::env::current_exe()?;309	let askpass_helper = helpers.path().join("remowt-askpass");310	let editor_helper = helpers.path().join("remowt-editor");311	let forward_helper = helpers.path().join("remowt-forward");312	{313		let script = format!(314			"#!/bin/sh\nexec {} ask-pass \"password\" \"$1\"\n",315			sh_quote(&exe.to_string_lossy())316		);317		fs::write(&askpass_helper, script).await?;318		fs::set_permissions(&askpass_helper, Permissions::from_mode(0o755)).await?;319	}320	{321		let script = format!(322			"#!/bin/sh\nexec {} editor \"$1\"\n",323			sh_quote(&exe.to_string_lossy())324		);325		fs::write(&editor_helper, script).await?;326		fs::set_permissions(&editor_helper, Permissions::from_mode(0o755)).await?;327	}328	{329		let script = format!(330			"#!/bin/sh\nexec {} forward \"$@\"\n",331			sh_quote(&exe.to_string_lossy())332		);333		fs::write(&forward_helper, script).await?;334		fs::set_permissions(&forward_helper, Permissions::from_mode(0o755)).await?;335	}336337	// Safety: Hoping tokio own threads won't read any of those...338	unsafe {339		prepend_path(helpers.path());340		std::env::set_var("SUDO_ASKPASS", &askpass_helper);341		std::env::set_var("SSH_ASKPASS", &askpass_helper);342		std::env::set_var("SSH_ASKPASS_REQUIRE", "force");343		std::env::set_var("EDITOR", &editor_helper);344		std::env::set_var("VISUAL", &editor_helper);345		std::env::set_var("DBUS_SESSION_BUS_ADDRESS", &bus.address);346	}347348	let port = match path {349		Some(path) => from_socket(UnixStream::connect(path).await?),350		None => from_stdio(),351	};352	rpc.add_direct(Address::User, port, bifrostlink::Rtt(0));353354	let polkit_conn = if !privileged && !local {355		// The unprivileged agent doubles as a polkit authentication agent so356		// `run0` (e.g. our own elevation) routes its prompt to the User over357		// bifrost instead of failing on a tty-less session.358		let conn = Connection::system().await?;359		let helper = SocketHelper {360			fallback: SuidHelper,361		};362		register_auth_agent(&conn, Agent::new(helper, user_prompter)).await?;363		Some(conn)364	} else {365		None366	};367368	let _keep_alive = (bus, helpers, polkit_conn);369	pending().await370}371372async fn register_auth_agent<H, P>(conn: &Connection, agent: Agent<H, P>) -> anyhow::Result<()>373where374	H: Helper + Clone + Send + Sync + 'static,375	P: Prompter + Clone + Send + Sync + 'static,376{377	let proxy = zbus_polkit::policykit1::AuthorityProxy::new(conn).await?;378	conn.object_server().at(OBJ_PATH, agent).await?;379380	let subject = auth_agent_subject()?;381	proxy382		.register_authentication_agent(&subject, "C", OBJ_PATH)383		.await?;384	debug!(kind = subject.subject_kind, "registered polkit agent");385	Ok(())386}387388fn auth_agent_subject() -> anyhow::Result<Subject> {389	let mut details = HashMap::new();390	if let Ok(session_id) = std::env::var("XDG_SESSION_ID") {391		let val: OwnedValue = Str::from(session_id).into();392		details.insert("session-id".to_string(), val);393		return Ok(Subject {394			subject_kind: "unix-session".to_string(),395			subject_details: details,396		});397	}398399	details.insert("pid".to_string(), OwnedValue::from(std::process::id()));400	Ok(Subject {401		subject_kind: "unix-process".to_string(),402		subject_details: details,403	})404}405406fn sh_quote(s: &str) -> String {407	format!("'{}'", s.replace('\'', "'\\''"))408}409410/// Prepend `dir` to the process `PATH`.411///412/// # SAFETY413///414/// Same as `set_var`415unsafe fn prepend_path(dir: &std::path::Path) {416	let value = match std::env::var_os("PATH") {417		Some(existing) => {418			let mut v = dir.as_os_str().to_owned();419			v.push(":");420			v.push(existing);421			v422		}423		None => dir.as_os_str().to_owned(),424	};425	unsafe {426		std::env::set_var("PATH", value);427	}428}