git.delta.rocks / remowt / refs/commits / eadb0bb3c19e

difftreelog

source

cmds/polkit-dbus-helper/src/main.rs6.2 KiBsourcehistory
1use std::collections::{HashMap, HashSet};2use std::ffi::{CStr, CString};3use std::future::pending;4use std::sync::LazyLock;56use anyhow::Context as _;7use clap::Parser;8use nix::unistd::{setuid, Uid, User};9use pam_client::{Context, ConversationHandler, ErrorCode, Flag};10use remowt_polkit_shared::BackendRequest;11use remowt_ui_prompt::dbus::DbusPrompterProxyBlocking;12use remowt_ui_prompt::BlockingPrompter;13use tokio::task::{block_in_place, spawn_blocking};14use tracing::trace;15use zbus::fdo;16use zbus::message::Header;17use zbus::zvariant::OwnedValue;18use zbus::{blocking, interface, proxy, Connection};1920struct Helper {21	connection: Connection,22	blocking_connection: blocking::Connection,23}2425static ALLOWED_ENVIRONMENT: LazyLock<HashSet<&str>> = LazyLock::new(|| {26	[27		// pam ssh agent auth28		"SSH_AUTH_SOCK",29		// ssh itself provides this when running PAM30		"SSH_AUTH_INFO_0",31		// contains user which ran sudo32		"SUDO_USER",33	]34	.into_iter()35	.collect()36});3738struct Conversation<P>(P);39impl<P: BlockingPrompter> Conversation<P> {40	fn prompt_inner(&self, echo: bool, prompt: &CStr) -> Result<CString, ErrorCode> {41		trace!("do prompt");42		let out = self43			.044			.prompt_text(echo, &prompt.to_string_lossy(), "PAM prompt request", &[])45			.map_err(|e| {46				trace!("prompt error: {e}");47				ErrorCode::CONV_ERR48			})?;49		CString::new(out).map_err(|_| ErrorCode::CONV_AGAIN)50	}51	fn text_inner(&self, error: bool, msg: &CStr) {52		trace!("do text");53		let msg = msg.to_string_lossy();54		let _ = self.0.display_text(error, &msg, &[]);55	}56}57impl<P: BlockingPrompter> ConversationHandler for Conversation<P> {58	fn prompt_echo_on(&mut self, prompt: &CStr) -> Result<CString, ErrorCode> {59		self.prompt_inner(true, prompt)60	}6162	fn prompt_echo_off(&mut self, prompt: &CStr) -> Result<CString, ErrorCode> {63		self.prompt_inner(false, prompt)64	}6566	fn text_info(&mut self, msg: &CStr) {67		self.text_inner(false, msg)68	}6970	fn error_msg(&mut self, msg: &CStr) {71		self.text_inner(true, msg)72	}7374	fn radio_prompt(&mut self, prompt: &CStr) -> Result<bool, ErrorCode> {75		let prompt = prompt.to_string_lossy();76		let result = self77			.078			.prompt_radio(&prompt, "PAM prompt request", &[])79			.map_err(|_| ErrorCode::CONV_ERR)?;80		Ok(result)81	}82}8384#[proxy(85	default_service = "org.freedesktop.DBus",86	default_path = "/org/freedesktop/DBus"87)]88trait DBus {89	fn get_connection_credentials(&self, body: &str) -> zbus::Result<HashMap<String, OwnedValue>>;90}9192#[interface(name = "lach.PolkitHelper")]93impl Helper {94	async fn init_conversation(95		&self,96		request: BackendRequest,97		#[zbus(header)] hdr: Header<'_>,98	) -> fdo::Result<()> {99		let Some(sender) = hdr.sender().map(|v| v.to_owned()) else {100			trace!("missing sender");101			return Err(fdo::Error::AuthFailed("missing sender".to_owned()));102		};103104		let dbus = DBusProxy::new(&self.connection).await?;105106		// TOCTOU: sender might be already disconnected, and there might be another107		// user with different user id here, but does it matters?108		let reply = dbus.get_connection_credentials(&sender).await?;109		let connection_uid: u32 = (&reply["UnixUserID"]).try_into().unwrap();110111		let identity = request.identity.clone();112		let blocking_connection = self.blocking_connection.clone();113		let thread_result: fdo::Result<()> = block_in_place(move || {114			trace!("find user");115			let Some(identity_uid) = identity.uid() else {116				return Err(fdo::Error::AuthFailed("can't process identity".to_owned()));117			};118			let user = User::from_uid(identity_uid)119				.map_err(|_| fdo::Error::AuthFailed("error querying user".to_owned()))?120				.ok_or_else(|| fdo::Error::AuthFailed("uid not found".to_owned()))?;121122			let responder = DbusPrompterProxyBlocking::new(123				&blocking_connection,124				sender,125				request.prompter_path,126			)?;127			let conversation = Conversation(responder);128			trace!("run context for {}", &user.name);129			let mut ctx = Context::new(130				// TODO: Should another scope be used?131				"login",132				Some(&user.name),133				conversation,134			)135			.map_err(|_| fdo::Error::Failed("pam context init failed".to_owned()))?;136137			trace!("fill env");138			for (k, v) in request.environment {139				if k.contains('=') || !ALLOWED_ENVIRONMENT.contains(k.as_str()) {140					continue;141				}142				let _ = ctx.putenv(format!("{k}={v}"));143			}144145			trace!("authenticate");146			ctx.authenticate(Flag::NONE)147				.map_err(|_| fdo::Error::AuthFailed("pam authentication failed".to_owned()))?;148149			trace!("acct mgmt");150			ctx.acct_mgmt(Flag::NONE)151				.map_err(|_| fdo::Error::AuthFailed("pam acct mgmt failed".to_owned()))?;152153			Ok(())154		});155156		thread_result?;157158		trace!("respond");159		let proxy = zbus_polkit::policykit1::AuthorityProxy::new(&self.connection).await?;160161		let identity_details = request162			.identity163			.details164			.iter()165			.map(|(k, v)| (k.as_str(), (**v).try_clone().expect("success")))166			.collect::<HashMap<_, _>>();167		proxy168			.authentication_agent_response2(169				connection_uid,170				&request.cookie,171				&zbus_polkit::policykit1::Identity {172					identity_kind: &request.identity.kind,173					identity_details: &identity_details,174				},175			)176			.await?;177		Ok(())178	}179}180181const OBJ_PATH: &str = "/lach/PolkitHelper";182183#[derive(Parser)]184struct Opts {185	/// Not recommended: start as a session connection, then use escalation186	/// to respond to polkit requests.187	#[arg(long)]188	session: bool,189}190191#[tokio::main]192async fn main() -> anyhow::Result<()> {193	tracing_subscriber::fmt::init();194	let opts = Opts::parse();195	let connection = if opts.session {196		Connection::session().await197	} else {198		Connection::system().await199	}200	.context("failed to open connection")?;201202	let session = opts.session;203	let blocking_connection: anyhow::Result<blocking::Connection> = spawn_blocking(move || {204		Ok(if session {205			blocking::Connection::session()?206		} else {207			blocking::Connection::system()?208		})209	})210	.await?;211	let blocking_connection = blocking_connection.context("failed to open blocking connection")?;212213	if opts.session {214		setuid(Uid::from_raw(0))215			.context("polkit-backend needs to be suid if run in session mode")?;216	}217218	connection219		.object_server()220		.at(221			OBJ_PATH,222			Helper {223				connection: connection.clone(),224				blocking_connection,225			},226		)227		.await228		.context("failed listen path")?;229230	connection231		.request_name("lach.polkit.helper1")232		.await233		.context("failed to request name")?;234235	pending().await236}