sector-f-linux

Sector F Linux
git clone https://git.sectorflabs.com/sector-f-linux.git
Log | Files | Refs | README | LICENSE

system.rs (20472B)


      1 //! The real backend (ADR-0012): greetd does the login, AccountsService makes the first account
      2 //! (polkit allows it only while no human account can log in), logind does the power.
      3 
      4 use std::os::unix::net::UnixStream;
      5 
      6 use greetd_ipc::{AuthMessageType, ErrorType, Request, Response, codec::SyncCodec};
      7 use std::collections::HashMap;
      8 
      9 use zbus::blocking::{Connection, Proxy};
     10 use zbus::zvariant::{OwnedObjectPath, Value};
     11 
     12 use crate::backend::{Backend, LoginError, Network, Power, Security, User, tidy};
     13 
     14 const ACCOUNTS: &str = "org.freedesktop.Accounts";
     15 const ACCOUNTS_PATH: &str = "/org/freedesktop/Accounts";
     16 const LOGIND: &str = "org.freedesktop.login1";
     17 const TIMEDATE: &str = "org.freedesktop.timedate1";
     18 const TIMEDATE_PATH: &str = "/org/freedesktop/timedate1";
     19 const HOSTNAME: &str = "org.freedesktop.hostname1";
     20 const HOSTNAME_PATH: &str = "/org/freedesktop/hostname1";
     21 const NM: &str = "org.freedesktop.NetworkManager";
     22 const NM_PATH: &str = "/org/freedesktop/NetworkManager";
     23 const NM_DEVICE: &str = "org.freedesktop.NetworkManager.Device";
     24 const NM_WIRELESS: &str = "org.freedesktop.NetworkManager.Device.Wireless";
     25 const NM_AP: &str = "org.freedesktop.NetworkManager.AccessPoint";
     26 /// NetworkManager's NM_DEVICE_TYPE_WIFI.
     27 const NM_DEVICE_TYPE_WIFI: u32 = 2;
     28 
     29 // NetworkManager's access point flags.
     30 const AP_PRIVACY: u32 = 0x1;
     31 const KEY_MGMT_PSK: u32 = 0x100;
     32 const KEY_MGMT_SAE: u32 = 0x400;
     33 
     34 /// How an access point is secured, from its three flag words, or `None` for what cannot be joined
     35 /// here: WEP (privacy and no key management), a work network with its own login (802.1X), and the
     36 /// rest. A network that offers both WPA2 and WPA3 is joined as WPA2, which every router takes.
     37 pub fn ap_security(flags: u32, wpa: u32, rsn: u32) -> Option<Security> {
     38     let key_mgmt = wpa | rsn;
     39     if key_mgmt == 0 {
     40         return (flags & AP_PRIVACY == 0).then_some(Security::Open);
     41     }
     42     if key_mgmt & KEY_MGMT_PSK != 0 {
     43         Some(Security::Psk)
     44     } else if key_mgmt & KEY_MGMT_SAE != 0 {
     45         Some(Security::Sae)
     46     } else {
     47         None
     48     }
     49 }
     50 
     51 /// The first human uid, as in /etc/login.defs.
     52 const FIRST_UID: u32 = 1000;
     53 
     54 pub struct System {
     55     /// What greetd runs for a user once they are in (the Patina session).
     56     session: Vec<String>,
     57 }
     58 
     59 impl System {
     60     pub fn new() -> Self {
     61         let session = std::env::var("PATINA_GREETER_SESSION")
     62             .unwrap_or_else(|_| "patina-session --session".into());
     63         Self {
     64             session: session.split_whitespace().map(String::from).collect(),
     65         }
     66     }
     67 
     68     fn bus() -> Result<Connection, String> {
     69         Connection::system().map_err(|e| format!("the system bus: {e}"))
     70     }
     71 
     72     fn proxy<'a>(
     73         bus: &'a Connection,
     74         dest: &'a str,
     75         path: &'a str,
     76         iface: &'a str,
     77     ) -> Result<Proxy<'a>, String> {
     78         Proxy::new(bus, dest, path, iface).map_err(|e| e.to_string())
     79     }
     80 
     81     /// The first Wi-Fi device NetworkManager has, if it has one.
     82     fn wifi_device(bus: &Connection) -> Result<Option<OwnedObjectPath>, String> {
     83         let nm = Self::proxy(bus, NM, NM_PATH, NM)?;
     84         let devices: Vec<OwnedObjectPath> =
     85             nm.call("GetDevices", &()).map_err(|e| e.to_string())?;
     86         for path in devices {
     87             let kind = Self::proxy(bus, NM, path.as_str(), NM_DEVICE)?
     88                 .get_property::<u32>("DeviceType")
     89                 .map_err(|e| e.to_string())?;
     90             if kind == NM_DEVICE_TYPE_WIFI {
     91                 return Ok(Some(path));
     92             }
     93         }
     94         Ok(None)
     95     }
     96 
     97     /// The access points in range, each with its object path (so one can be joined), unfiltered.
     98     fn access_points(
     99         bus: &Connection,
    100         device: &OwnedObjectPath,
    101     ) -> Result<Vec<(OwnedObjectPath, Network)>, String> {
    102         let wireless = Self::proxy(bus, NM, device.as_str(), NM_WIRELESS)?;
    103         let paths: Vec<OwnedObjectPath> = wireless
    104             .call("GetAccessPoints", &())
    105             .map_err(|e| e.to_string())?;
    106         let mut found = Vec::new();
    107         for path in paths {
    108             // Read in a block of its own, so the proxy's borrow of the path has ended before the
    109             // path is kept.
    110             let network = {
    111                 let ap = Self::proxy(bus, NM, path.as_str(), NM_AP)?;
    112                 let get_u32 = |name: &str| ap.get_property::<u32>(name).unwrap_or(0);
    113                 ap_security(get_u32("Flags"), get_u32("WpaFlags"), get_u32("RsnFlags")).map(
    114                     |security| {
    115                         let ssid: Vec<u8> = ap.get_property("Ssid").unwrap_or_default();
    116                         Network {
    117                             ssid: String::from_utf8_lossy(&ssid).into_owned(),
    118                             strength: ap.get_property::<u8>("Strength").unwrap_or(0),
    119                             security,
    120                         }
    121                     },
    122                 )
    123             };
    124             if let Some(network) = network {
    125                 found.push((path, network));
    126             }
    127         }
    128         Ok(found)
    129     }
    130 
    131     /// Whether AccountsService says the account is locked (no password set yet). If it cannot be
    132     /// asked, not: the login is then shown, and greetd decides.
    133     fn locked(bus: &Connection, name: &str) -> bool {
    134         let Ok(manager) = Self::proxy(bus, ACCOUNTS, ACCOUNTS_PATH, "org.freedesktop.Accounts")
    135         else {
    136             return false;
    137         };
    138         let Ok(path) = manager.call::<_, _, OwnedObjectPath>("FindUserByName", &(name,)) else {
    139             return false;
    140         };
    141         Self::proxy(
    142             bus,
    143             ACCOUNTS,
    144             path.as_str(),
    145             "org.freedesktop.Accounts.User",
    146         )
    147         .and_then(|u| u.get_property::<bool>("Locked").map_err(|e| e.to_string()))
    148         .unwrap_or(false)
    149     }
    150 
    151     /// Talks to greetd: the password goes in, and a session starts if it is right.
    152     fn greetd_login(&self, user: &str, password: &str) -> Result<(), LoginError> {
    153         let problem = |e: &dyn std::fmt::Display| LoginError::Problem(format!("greetd: {e}"));
    154         let sock = std::env::var("GREETD_SOCK")
    155             .map_err(|_| LoginError::Problem("not started by greetd (no GREETD_SOCK)".into()))?;
    156         let mut stream = UnixStream::connect(sock).map_err(|e| problem(&e))?;
    157 
    158         Request::CreateSession {
    159             username: user.to_string(),
    160         }
    161         .write_to(&mut stream)
    162         .map_err(|e| problem(&e))?;
    163         let mut answer = Response::read_from(&mut stream).map_err(|e| problem(&e))?;
    164         loop {
    165             match answer {
    166                 Response::AuthMessage {
    167                     auth_message_type, ..
    168                 } => {
    169                     // The password for a secret prompt; anything else (info, error text) is
    170                     // acknowledged with nothing. More steps (a fingerprint) are a known gap.
    171                     let reply = match auth_message_type {
    172                         AuthMessageType::Secret | AuthMessageType::Visible => {
    173                             Some(password.to_string())
    174                         }
    175                         _ => None,
    176                     };
    177                     Request::PostAuthMessageResponse { response: reply }
    178                         .write_to(&mut stream)
    179                         .map_err(|e| problem(&e))?;
    180                     answer = Response::read_from(&mut stream).map_err(|e| problem(&e))?;
    181                 }
    182                 Response::Success => break,
    183                 Response::Error {
    184                     error_type,
    185                     description,
    186                 } => {
    187                     Request::CancelSession.write_to(&mut stream).ok();
    188                     return Err(match error_type {
    189                         ErrorType::AuthError => LoginError::Wrong,
    190                         ErrorType::Error => LoginError::Problem(description),
    191                     });
    192                 }
    193             }
    194         }
    195         Request::StartSession {
    196             cmd: self.session.clone(),
    197             env: vec![],
    198         }
    199         .write_to(&mut stream)
    200         .map_err(|e| problem(&e))?;
    201         match Response::read_from(&mut stream).map_err(|e| problem(&e))? {
    202             Response::Success => Ok(()),
    203             Response::Error { description, .. } => Err(LoginError::Problem(description)),
    204             other => Err(LoginError::Problem(format!(
    205                 "unexpected answer from greetd: {other:?}"
    206             ))),
    207         }
    208     }
    209 }
    210 
    211 /// The human accounts in /etc/passwd: uid from 1000 below nobody's 65534, with a shell that logs in.
    212 /// (name, full name)
    213 fn human_accounts(passwd: &str) -> Vec<(String, String)> {
    214     passwd
    215         .lines()
    216         .filter_map(|line| {
    217             let f: Vec<&str> = line.split(':').collect();
    218             let uid: u32 = f.get(2)?.parse().ok()?;
    219             let shell = f.get(6)?;
    220             if !(FIRST_UID..60000).contains(&uid)
    221                 || shell.ends_with("nologin")
    222                 || shell.ends_with("false")
    223             {
    224                 return None;
    225             }
    226             let full = f.get(4)?.split(',').next().unwrap_or("");
    227             Some((
    228                 f[0].to_string(),
    229                 if full.is_empty() { f[0] } else { full }.to_string(),
    230             ))
    231         })
    232         .collect()
    233 }
    234 
    235 impl Backend for System {
    236     fn users(&self) -> Vec<User> {
    237         let passwd = std::fs::read_to_string("/etc/passwd").unwrap_or_default();
    238         let bus = Self::bus().ok();
    239         human_accounts(&passwd)
    240             .into_iter()
    241             .filter(|(name, _)| bus.as_ref().is_none_or(|b| !Self::locked(b, name)))
    242             .map(|(name, full_name)| User { name, full_name })
    243             .collect()
    244     }
    245 
    246     fn first_run(&self) -> bool {
    247         self.users().is_empty()
    248     }
    249 
    250     fn login(&self, user: &str, password: &str) -> Result<(), LoginError> {
    251         self.greetd_login(user, password)
    252     }
    253 
    254     fn create_first_user(
    255         &self,
    256         full_name: &str,
    257         username: &str,
    258         password: &str,
    259     ) -> Result<(), String> {
    260         let hash = pwhash::sha512_crypt::hash(password).map_err(|e| format!("hashing: {e}"))?;
    261         let bus = Self::bus()?;
    262         let manager = Self::proxy(&bus, ACCOUNTS, ACCOUNTS_PATH, "org.freedesktop.Accounts")?;
    263         // account type 1: an administrator (wheel), as the first person on a machine is.
    264         let path: OwnedObjectPath = manager
    265             .call("CreateUser", &(username, full_name, 1i32))
    266             .map_err(|e| format!("could not create the account: {e}"))?;
    267         let user = Self::proxy(
    268             &bus,
    269             ACCOUNTS,
    270             path.as_str(),
    271             "org.freedesktop.Accounts.User",
    272         )?;
    273         if let Err(e) = user.call::<_, _, ()>("SetPassword", &(hash.as_str(), "")) {
    274             // Take the half-made account back out (polkit allows it while it is locked), so
    275             // the setup can run again.
    276             let uid: Option<i64> = user.get_property::<u64>("Uid").ok().map(|u| u as i64);
    277             if let Some(uid) = uid {
    278                 manager.call::<_, _, ()>("DeleteUser", &(uid, true)).ok();
    279             }
    280             return Err(format!("could not set the password: {e}"));
    281         }
    282         Ok(())
    283     }
    284 
    285     fn power(&self, action: Power) -> Result<(), String> {
    286         let bus = Self::bus()?;
    287         let manager = Self::proxy(
    288             &bus,
    289             LOGIND,
    290             "/org/freedesktop/login1",
    291             "org.freedesktop.login1.Manager",
    292         )?;
    293         let method = match action {
    294             Power::Reboot => "Reboot",
    295             Power::PowerOff => "PowerOff",
    296         };
    297         manager
    298             .call::<_, _, ()>(method, &(false,))
    299             .map_err(|e| e.to_string())
    300     }
    301 
    302     /// timedated's own list, so it is the zones this system has.
    303     fn timezones(&self) -> Vec<String> {
    304         let list = || -> Result<Vec<String>, String> {
    305             let bus = Self::bus()?;
    306             Self::proxy(&bus, TIMEDATE, TIMEDATE_PATH, TIMEDATE)?
    307                 .call::<_, _, Vec<String>>("ListTimezones", &())
    308                 .map_err(|e| e.to_string())
    309         };
    310         list().unwrap_or_default()
    311     }
    312 
    313     fn timezone(&self) -> String {
    314         let get = || -> Result<String, String> {
    315             let bus = Self::bus()?;
    316             Self::proxy(&bus, TIMEDATE, TIMEDATE_PATH, TIMEDATE)?
    317                 .get_property::<String>("Timezone")
    318                 .map_err(|e| e.to_string())
    319         };
    320         get().unwrap_or_default()
    321     }
    322 
    323     fn set_timezone(&self, zone: &str) -> Result<(), String> {
    324         let bus = Self::bus()?;
    325         // The second argument is whether polkit may ask for a password: no one is there to give it.
    326         Self::proxy(&bus, TIMEDATE, TIMEDATE_PATH, TIMEDATE)?
    327             .call::<_, _, ()>("SetTimezone", &(zone, false))
    328             .map_err(|e| format!("could not set the time zone: {e}"))
    329     }
    330 
    331     fn hostname(&self) -> String {
    332         let get = || -> Result<String, String> {
    333             let bus = Self::bus()?;
    334             let hostnamed = Self::proxy(&bus, HOSTNAME, HOSTNAME_PATH, HOSTNAME)?;
    335             // The static name is the one that persists; the running one when none is set.
    336             match hostnamed.get_property::<String>("StaticHostname") {
    337                 Ok(name) if !name.is_empty() => Ok(name),
    338                 _ => hostnamed
    339                     .get_property::<String>("Hostname")
    340                     .map_err(|e| e.to_string()),
    341             }
    342         };
    343         get().unwrap_or_default()
    344     }
    345 
    346     fn wifi_available(&self) -> bool {
    347         Self::bus()
    348             .and_then(|bus| Self::wifi_device(&bus))
    349             .is_ok_and(|device| device.is_some())
    350     }
    351 
    352     fn wifi_networks(&self) -> Vec<Network> {
    353         let list = || -> Result<Vec<Network>, String> {
    354             let bus = Self::bus()?;
    355             let Some(device) = Self::wifi_device(&bus)? else {
    356                 return Ok(Vec::new());
    357             };
    358             // A scan takes seconds, and the list is what is known now; the setup asks again.
    359             let options: HashMap<&str, Value> = HashMap::new();
    360             Self::proxy(&bus, NM, device.as_str(), NM_WIRELESS)?
    361                 .call::<_, _, ()>("RequestScan", &(options,))
    362                 .ok();
    363             Ok(tidy(
    364                 Self::access_points(&bus, &device)?
    365                     .into_iter()
    366                     .map(|(_, network)| network)
    367                     .collect(),
    368             ))
    369         };
    370         list().unwrap_or_default()
    371     }
    372 
    373     fn wifi_connect(&self, ssid: &str, password: &str) -> Result<(), String> {
    374         let bus = Self::bus()?;
    375         let device = Self::wifi_device(&bus)?.ok_or("this computer has no Wi-Fi")?;
    376         let ap = Self::access_points(&bus, &device)?
    377             .into_iter()
    378             .find(|(_, n)| n.ssid == ssid)
    379             .ok_or_else(|| format!("could not join {ssid}: it is out of range"))?;
    380 
    381         let mut wireless: HashMap<&str, Value> = HashMap::new();
    382         wireless.insert("ssid", Value::from(ssid.as_bytes().to_vec()));
    383         wireless.insert("mode", Value::from("infrastructure"));
    384         let mut connection: HashMap<&str, Value> = HashMap::new();
    385         connection.insert("id", Value::from(ssid));
    386         connection.insert("type", Value::from("802-11-wireless"));
    387         let mut settings: HashMap<&str, HashMap<&str, Value>> = HashMap::new();
    388         settings.insert("connection", connection);
    389         settings.insert("802-11-wireless", wireless);
    390         let key_mgmt = match ap.1.security {
    391             Security::Open => None,
    392             Security::Psk => Some("wpa-psk"),
    393             Security::Sae => Some("sae"),
    394         };
    395         if let Some(key_mgmt) = key_mgmt {
    396             let mut security: HashMap<&str, Value> = HashMap::new();
    397             security.insert("key-mgmt", Value::from(key_mgmt));
    398             security.insert("psk", Value::from(password));
    399             settings.insert("802-11-wireless-security", security);
    400         }
    401 
    402         let nm = Self::proxy(&bus, NM, NM_PATH, NM)?;
    403         // "/" for the access point: NetworkManager picks the best one for the name.
    404         let any = OwnedObjectPath::try_from("/").map_err(|e| e.to_string())?;
    405         let (saved, active): (OwnedObjectPath, OwnedObjectPath) = nm
    406             .call("AddAndActivateConnection", &(settings, &device, &any))
    407             .map_err(|e| format!("could not join {ssid}: {e}"))?;
    408 
    409         // Joined, or failed. A wrong password ends with the connection deactivated, quickly. The
    410         // device says how far it got: from "configuring an address" on, the password was accepted
    411         // and the network answered, even if DHCP has not finished, which is the network's own
    412         // time and not a reason to refuse. The state is polled for half a minute.
    413         let active = Self::proxy(
    414             &bus,
    415             NM,
    416             active.as_str(),
    417             "org.freedesktop.NetworkManager.Connection.Active",
    418         )?;
    419         let device_state = || -> u32 {
    420             Self::proxy(&bus, NM, device.as_str(), NM_DEVICE)
    421                 .and_then(|d| d.get_property::<u32>("State").map_err(|e| e.to_string()))
    422                 .unwrap_or(0)
    423         };
    424         for _ in 0..60 {
    425             match active.get_property::<u32>("State") {
    426                 Ok(2) => return Ok(()),
    427                 // Deactivating or deactivated: it did not work.
    428                 Ok(3 | 4) | Err(_) => break,
    429                 Ok(_) => {}
    430             }
    431             // NM_DEVICE_STATE_IP_CONFIG, IP_CHECK, SECONDARIES, ACTIVATED.
    432             if matches!(device_state(), 70 | 80 | 90 | 100) {
    433                 return Ok(());
    434             }
    435             std::thread::sleep(std::time::Duration::from_millis(500));
    436         }
    437         // Do not keep a network that would not join (a mistyped password) on the machine.
    438         Self::proxy(
    439             &bus,
    440             NM,
    441             saved.as_str(),
    442             "org.freedesktop.NetworkManager.Settings.Connection",
    443         )
    444         .and_then(|c| c.call::<_, _, ()>("Delete", &()).map_err(|e| e.to_string()))
    445         .ok();
    446         Err(format!(
    447             "could not join {ssid}: {}",
    448             if key_mgmt.is_some() {
    449                 "the password was not accepted, or the network did not answer"
    450             } else {
    451                 "the network did not answer"
    452             }
    453         ))
    454     }
    455 
    456     fn set_hostname(&self, name: &str) -> Result<(), String> {
    457         let bus = Self::bus()?;
    458         Self::proxy(&bus, HOSTNAME, HOSTNAME_PATH, HOSTNAME)?
    459             .call::<_, _, ()>("SetStaticHostname", &(name, false))
    460             .map_err(|e| format!("could not set the name: {e}"))
    461     }
    462 }
    463 
    464 #[cfg(test)]
    465 mod tests {
    466     use super::{ap_security, human_accounts};
    467     use crate::backend::Security;
    468 
    469     #[test]
    470     fn access_points_are_open_or_with_a_password_or_not_joinable() {
    471         // (flags, wpa, rsn)
    472         assert_eq!(ap_security(0, 0, 0), Some(Security::Open));
    473         assert_eq!(
    474             ap_security(1, 0, 0),
    475             None,
    476             "privacy with no key management is WEP"
    477         );
    478         assert_eq!(
    479             ap_security(1, 0, 0x100),
    480             Some(Security::Psk),
    481             "WPA2 personal"
    482         );
    483         assert_eq!(
    484             ap_security(1, 0x100, 0),
    485             Some(Security::Psk),
    486             "WPA personal"
    487         );
    488         assert_eq!(
    489             ap_security(1, 0, 0x400),
    490             Some(Security::Sae),
    491             "WPA3 personal"
    492         );
    493         assert_eq!(
    494             ap_security(1, 0, 0x100 | 0x400),
    495             Some(Security::Psk),
    496             "WPA2/WPA3 joins as WPA2"
    497         );
    498         assert_eq!(
    499             ap_security(1, 0, 0x200),
    500             None,
    501             "a work network with its own login"
    502         );
    503         assert_eq!(ap_security(1, 0, 0x800), None, "opportunistic encryption");
    504     }
    505 
    506     #[test]
    507     fn only_people_who_can_log_in() {
    508         let passwd = "root:x:0:0:Super:/root:/bin/bash\n\
    509                       greetd:x:963:963:Greeter:/var/lib/greetd:/sbin/nologin\n\
    510                       alice:x:1000:1000:Alice Example,,,:/var/home/alice:/bin/bash\n\
    511                       bob:x:1001:1001::/var/home/bob:/bin/zsh\n\
    512                       svc:x:1002:1002:Service:/srv:/usr/sbin/nologin\n\
    513                       nobody:x:65534:65534:Kernel:/:/sbin/nologin\n";
    514         assert_eq!(
    515             human_accounts(passwd),
    516             vec![
    517                 ("alice".into(), "Alice Example".into()),
    518                 ("bob".into(), "bob".into())
    519             ]
    520         );
    521     }
    522 }