///| The PAM conversation, through polkit's helper. /// /// polkit authenticates with `polkit-agent-helper-1` (part of polkit, run as root). An agent /// talks to it one line at a time: the helper writes what PAM asks or says, /// PAM_PROMPT_ECHO_OFF (a password: answer with one line) /// PAM_PROMPT_ECHO_ON (a visible answer, say a user name or a one-time code) /// PAM_ERROR_MSG / PAM_TEXT_INFO (messages, no answer) /// SUCCESS / FAILURE (the end; on success the helper has told polkitd itself) /// with the text escaped as g_strescape does. There are two ways to start it: /// - polkit 126+ (systemd): connect to /run/polkit/agent-helper.socket and send the user name and /// the cookie, one line each (socket activation; no setuid binary). /// - otherwise run the setuid helper with the user name as its argument and send the cookie. ///| What the helper said. pub(all) enum HelperEvent { PromptEchoOff(String) PromptEchoOn(String) ErrorMsg(String) TextInfo(String) Success Failure /// The helper went away without saying SUCCESS or FAILURE (it crashed, was refused, or /// couldn't run PAM at all). Gone } derive(Eq, Debug) ///| Undo g_strescape: \n \t \r \b \f \v \\ \" and octal \NNN (bytes, re-read as UTF-8). pub fn unescape(s : String) -> String { let out : Array[Byte] = [] let cs = chars_of(s) let push_char = fn(c : Char) { let b = @utf8.encode(c.to_string()) for i = 0; i < b.length(); i = i + 1 { out.push(b[i]) } } let mut i = 0 while i < cs.length() { let c = cs[i] if c != '\\' || i + 1 >= cs.length() { push_char(c) i = i + 1 continue } let d = cs[i + 1] if d >= '0' && d <= '7' { let mut v = 0 let mut k = 0 while k < 3 && i + 1 + k < cs.length() && cs[i + 1 + k] >= '0' && cs[i + 1 + k] <= '7' { v = v * 8 + (cs[i + 1 + k].to_int() - '0'.to_int()) k = k + 1 } out.push((v & 0xff).to_byte()) i = i + 1 + k continue } let r = match d { 'n' => '\n' 't' => '\t' 'r' => '\r' 'b' => '\b' 'f' => '\u{0c}' 'v' => '\u{0b}' _ => d } push_char(r) i = i + 2 } @utf8.decode_lossy(Bytes::from_array(out)) } ///| Parse one line from the helper (without its newline). None for lines we don't know. pub fn parse_helper_line(line : String) -> HelperEvent? { let after = fn(p : String) { unescape(line[p.length():].to_string()) } if line.has_prefix("PAM_PROMPT_ECHO_OFF ") { Some(PromptEchoOff(after("PAM_PROMPT_ECHO_OFF "))) } else if line.has_prefix("PAM_PROMPT_ECHO_ON ") { Some(PromptEchoOn(after("PAM_PROMPT_ECHO_ON "))) } else if line.has_prefix("PAM_ERROR_MSG ") { Some(ErrorMsg(after("PAM_ERROR_MSG "))) } else if line.has_prefix("PAM_TEXT_INFO ") { Some(TextInfo(after("PAM_TEXT_INFO "))) } else if line.has_prefix("SUCCESS") { Some(Success) } else if line.has_prefix("FAILURE") { Some(Failure) } else { None } } ///| Where polkit installs the setuid helper, by distribution. pub let helper_paths : Array[String] = [ "/usr/lib/polkit-1/polkit-agent-helper-1", "/usr/libexec/polkit-agent-helper-1", "/usr/libexec/polkit-1/polkit-agent-helper-1", "/usr/lib/policykit-1/polkit-agent-helper-1", ] ///| The socket-activated helper (polkit 126+). pub let helper_socket : String = "/run/polkit/agent-helper.socket" ///| How to reach the helper: a socket to connect to, or a program to run on a socket pair. pub(all) enum HelperRoute { Socket(String) Program(String) } derive(Eq, Debug) ///| A route, for the log and for errors. pub fn route_text(r : HelperRoute) -> String { match r { Socket(p) => "socket " + p Program(p) => p } } ///| A PAM conversation: polkit's helper, or the demo's stand-in (demo.mbt). pub(open) trait Conversation { /// What was said since the last call (non-blocking); ends with Success, Failure or Gone. poll(Self) -> Array[HelperEvent] /// Answer the prompt (the bytes, without a newline); false when it can't be sent. answer(Self, FixedArray[Byte]) -> Bool /// The fd to wait on, -1 for none (the caller then polls on a timer). fd(Self) -> Int /// End the conversation. close(Self) -> Unit } ///| One run of polkit-agent-helper-1. pub struct HelperSession { conn : LineConn /// SUCCESS, FAILURE or Gone was reported. mut ended : Bool } ///| Start the helper to authenticate `user` for `cookie` by the first route that works; Err /// says which routes were tried and how each failed. pub fn HelperSession::start_any(routes : Array[HelperRoute], user : String, cookie : String) -> Result[HelperSession, String] { let tried : Array[String] = [] for r in routes { match HelperSession::start(r, user, cookie) { Some(s) => { alog("password check for " + user + " via " + route_text(r)) return Ok(s) } None => tried.push(route_text(r)) } } if tried.length() == 0 { Err("polkit's password checker (polkit-agent-helper-1) is not installed") } else { Err("polkit's password checker could not be started (tried " + tried.join(", ") + ")") } } ///| Start the helper to authenticate `user` for `cookie`. None when it can't be reached. pub fn HelperSession::start(route : HelperRoute, user : String, cookie : String) -> HelperSession? { let (fd, first) = match route { Socket(path) => (@sys.unix_connect(path), user + "\n" + cookie + "\n") Program(path) => if @sys.has_exe(path) { (@sys.spawn_socket([path, user]), cookie + "\n") } else { (-1, "") } } if fd < 0 { return None } let conn = LineConn::new(fd) if !conn.send_raw(@utf8.encode(first)) { conn.close() return None } Some({ conn, ended: false }) } ///| A session over an already-connected fd (tests). pub fn HelperSession::over(fd : Int) -> HelperSession { { conn: LineConn::new(fd), ended: false } } ///| pub impl Conversation for HelperSession with poll(self) { let out : Array[HelperEvent] = [] if self.ended { return out } for line in self.conn.read_lines() { match parse_helper_line(field_text(line)) { Some(ev) => { out.push(ev) if ev == Success || ev == Failure { self.ended = true self.conn.close() return out } } None => () } } if self.conn.eof { out.push(Gone) self.ended = true self.conn.close() } out } ///| pub impl Conversation for HelperSession with answer(self, a) { let n = a.length() let b = FixedArray::makei(n + 1, i => if i < n { a[i] } else { b'\n' }) let ok = self.conn.send_raw(Bytes::makei(b.length(), i => b[i])) zero(b) ok } ///| pub impl Conversation for HelperSession with fd(self) { self.conn.fd() } ///| Closing the connection ends the helper's PAM conversation. pub impl Conversation for HelperSession with close(self) { self.ended = true self.conn.close() }