authentication/lib.rs
1//! # Authentication Module
2//!
3//! The Authentication module provides user and group management functionality for the Xila operating system.
4//! It handles user authentication, password hashing, and secure storage of user/group information.
5//!
6//! ## Features
7//!
8//! - **User Management**: Create, authenticate, rename and manage user accounts
9//! - **Group Management**: Create and manage user groups
10//! - **Password Security**: Secure password hashing using SHA-512 with salt
11//! - **File-based Storage**: Persistent storage of user and group data in JSON format
12//! - **Async Operations**: All operations are asynchronous for better performance
13//!
14//! ## File Structure
15//!
16//! - Users are stored in `/system/accounts/users/`, one record per user, in a
17//! file named after the user
18//! - Groups are stored in `/system/accounts/groups/`
19//! - Random salt generation uses `/devices/random/source`
20//!
21//! ## User names
22//!
23//! New and renamed accounts must satisfy [`users::is_valid_user_name`]: an
24//! ASCII letter followed by at most 31 ASCII letters, digits, `_` or `-`.
25//! Existing accounts load whatever their name, but record lookups always
26//! reject names that are not a single ordinary directory entry.
27//!
28//! ## Home directories
29//!
30//! Like the home field of `/etc/passwd`, each account records its home. It is
31//! set to `/users/<user name>` when the account is created and read from the
32//! account afterwards (`VirtualFileSystem::get_user_home`), never recomputed
33//! from the current name. The directory itself is created at the first login.
34//! The built-in root account has no record; its home is [`users::ROOT_HOME`].
35//!
36//! Renaming an account ([`change_user_name`]) keeps its recorded home, as Linux
37//! `usermod --login` does without `--move-home`. Moving a home is a separate,
38//! explicit operation that Xila does not perform implicitly.
39//!
40//! ## Account record versions
41//!
42//! Records carry a `version` field ([`USER_RECORD_VERSION`]). Version 1 adds
43//! the `home` field. Records without a `version` are version 0, written before
44//! homes were recorded: their home is `/users/<identifier>`, the path they
45//! already used. That fallback is applied in memory when the record is read,
46//! so booting never writes to storage; a version 0 record is upgraded only when
47//! it is rewritten anyway (password change or rename), and then records the
48//! same `/users/<identifier>` home. Records of an unknown version, or version 1
49//! records without a valid home, are rejected. Firmware older than version 1
50//! ignores the new fields and falls back to `/users/<identifier>`.
51
52#![no_std]
53
54extern crate alloc;
55
56embedded_i18n::i18n!("locales");
57
58mod error;
59mod seed;
60pub use seed::{SEED_PENDING_CONTENT, SEED_PENDING_PATH, initialize_seeded};
61mod group;
62mod hash;
63mod user;
64
65use alloc::{vec, vec::Vec};
66use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
67pub use error::*;
68use file_system::{AccessFlags, CreateFlags, Entry, Flags, IoErrorKind, Kind, Path, Permissions};
69pub use group::*;
70use task::TaskIdentifier;
71pub use user::*;
72use virtual_file_system::{File, VirtualFileSystem};
73
74// Keep the file system and users manager in step across asynchronous operations.
75static ACCOUNT_MUTATIONS: Mutex<CriticalSectionRawMutex, ()> = Mutex::new(());
76
77const READ_CHUNK_SIZE: usize = 32;
78
79/// Path to the users directory in the filesystem
80const USERS_FOLDER_PATH: &str = "/system/accounts/users";
81
82/// Path to the groups directory in the filesystem
83const GROUP_FOLDER_PATH: &str = "/system/accounts/groups";
84
85/// Path to the random device used for salt generation
86const RANDOM_DEVICE_PATH: &str = "/devices/random/source";
87
88/// The dependencies required by authentication operations.
89pub struct Context<'a> {
90 pub virtual_file_system: &'a VirtualFileSystem,
91 pub task_manager: &'a task::Manager,
92 pub users_manager: &'a users::Manager,
93 pub task: TaskIdentifier,
94}
95
96/// Loads all users and groups from the filesystem into memory.
97///
98/// This function scans the `/system/accounts/groups` and
99/// `/system/accounts/users` directories, reads all group and user files, and
100/// adds them to the Users manager with their recorded homes. It only reads:
101/// version 0 user records get their `/users/<identifier>` home in memory.
102/// It should be called during system initialization.
103///
104/// # Returns
105///
106/// Returns `Ok(())` if all users and groups were loaded successfully,
107/// or an `Error` if any operation failed.
108///
109/// # Errors
110///
111/// This function can return errors in the following cases:
112/// - Failed to read users or groups directory
113/// - Failed to add users or groups to the Users manager
114///
115/// Records that cannot be read or parsed are skipped with a warning
116/// instead of failing the whole load.
117///
118/// # Examples
119///
120/// ```rust
121/// use authentication::load_all_users_and_groups;
122///
123/// async fn example(context: &authentication::Context<'_>) -> Result<(), authentication::Error> {
124/// load_all_users_and_groups(context).await?;
125/// Ok(())
126/// }
127/// ```
128pub async fn load_all_users_and_groups(context: &Context<'_>) -> Result<()> {
129 let _mutation = ACCOUNT_MUTATIONS.lock().await;
130 load_account_records(context).await
131}
132
133// The caller must hold ACCOUNT_MUTATIONS.
134async fn load_account_records(context: &Context<'_>) -> Result<()> {
135 use group::read_group_file;
136 use user::read_user_file;
137 use virtual_file_system::Directory;
138 // Open Xila users folder.
139 let virtual_file_system = context.virtual_file_system;
140 let users_manager = context.users_manager;
141
142 let mut buffer: Vec<u8> = vec![];
143
144 {
145 let task = context.task;
146
147 let groups_directory = Directory::open(virtual_file_system, task, GROUP_FOLDER_PATH)
148 .await
149 .map_err(Error::FailedToReadGroupDirectory)?;
150
151 // Read all groups.
152 for group_entry in groups_directory.filter(is_record) {
153 let group = match read_group_file(context, &mut buffer, &group_entry.name).await {
154 Ok(group) => group,
155 Err(error) => {
156 log::warning!("Skipped a group record that cannot be loaded: {error}");
157 continue;
158 }
159 };
160
161 users_manager
162 .add_group(group.get_identifier(), group.get_name(), group.get_users())
163 .await
164 .map_err(Error::FailedToAddGroup)?;
165 }
166 }
167
168 {
169 let task = context.task;
170
171 let users_directory = Directory::open(virtual_file_system, task, USERS_FOLDER_PATH)
172 .await
173 .map_err(Error::FailedToReadUsersDirectory)?;
174
175 // Read all users.
176 for user_entry in users_directory.filter(is_record) {
177 let user = match read_user_file(context, &mut buffer, &user_entry.name).await {
178 Ok(user) => user,
179 Err(error) => {
180 // The name is not logged: it is personal data.
181 log::warning!("Skipped an account record that cannot be loaded: {error}");
182 continue;
183 }
184 };
185
186 users_manager
187 .add_user(
188 user.get_identifier(),
189 user.get_name(),
190 user.get_primary_group(),
191 user.get_home(),
192 )
193 .await
194 .map_err(Error::FailedToAddUser)?;
195 }
196 }
197
198 Ok(())
199}
200
201/// Whether a directory entry can be an account or group record: a regular
202/// file. Directory iterators also report `.` and `..`, and a stray directory
203/// is not a record either.
204fn is_record(entry: &Entry) -> bool {
205 entry.kind == Kind::File && !matches!(entry.name.as_str(), "." | "..")
206}
207
208/// Create a new record without replacing an existing entry.
209async fn create_record(
210 context: &Context<'_>,
211 path: &Path,
212 contents: &[u8],
213) -> core::result::Result<(), IoErrorKind> {
214 let virtual_file_system = context.virtual_file_system;
215 let mut file = File::open(
216 virtual_file_system,
217 context.task,
218 path,
219 Flags::new(
220 AccessFlags::Write,
221 Some(CreateFlags::CREATE_EXCLUSIVE),
222 None,
223 ),
224 )
225 .await?;
226
227 let write = write_record(&mut file, contents).await;
228 let close = file.close(virtual_file_system).await;
229 let result = write.and(close);
230 if result.is_err() {
231 remove_created_record(context, path).await;
232 }
233 result
234}
235
236async fn remove_created_record(context: &Context<'_>, path: &Path) {
237 if let Err(error) = context
238 .virtual_file_system
239 .remove(context.task, &path)
240 .await
241 {
242 log::warning!("Failed to remove a record after creation failed: {error}");
243 }
244}
245
246async fn write_record(
247 file: &mut File<'_>,
248 mut contents: &[u8],
249) -> core::result::Result<(), IoErrorKind> {
250 while !contents.is_empty() {
251 let count = file.write(contents).await?;
252 if count == 0 {
253 return Err(IoErrorKind::WriteZero);
254 }
255 contents = &contents[count..];
256 }
257 file.flush().await
258}
259
260/// Write `contents` to `temporary`, then rename it over `destination`, so the
261/// destination holds either its previous or its new contents.
262async fn atomic_write(
263 context: &Context<'_>,
264 temporary: &str,
265 destination: &str,
266 contents: &[u8],
267) -> Result<()> {
268 let virtual_file_system = context.virtual_file_system;
269 let mut file = File::open(
270 virtual_file_system,
271 context.task,
272 temporary,
273 Flags::new(AccessFlags::Write, Some(CreateFlags::CREATE_TRUNCATE), None),
274 )
275 .await
276 .map_err(Error::FailedToWriteUserFile)?;
277
278 let write = async {
279 file.set_permissions(Permissions::USER_READ_WRITE).await?;
280 write_record(&mut file, contents).await
281 }
282 .await;
283 let close = file.close(virtual_file_system).await;
284 write.map_err(Error::FailedToWriteUserFile)?;
285 close.map_err(Error::FailedToCloseFile)?;
286 virtual_file_system
287 .rename(context.task, &temporary, &destination)
288 .await
289 .map_err(Error::FailedToWriteUserFile)
290}