Skip to main content

pacsea/logic/
faillock.rs

1//! Faillock status checking and configuration parsing.
2
3use std::process::Command;
4
5/// What: Faillock status information for a user.
6///
7/// Inputs: None (constructed from faillock command output).
8///
9/// Output: Status information about failed login attempts.
10///
11/// Details:
12/// - Contains the number of failed attempts, maximum allowed attempts,
13/// - whether the account is locked, and the lockout duration in minutes.
14#[derive(Debug, Clone)]
15pub struct FaillockStatus {
16    /// Number of failed attempts currently recorded.
17    pub attempts_used: u32,
18    /// Maximum number of failed attempts before lockout.
19    pub max_attempts: u32,
20    /// Whether the account is currently locked.
21    pub is_locked: bool,
22    /// Lockout duration in minutes.
23    pub lockout_duration_minutes: u32,
24    /// Timestamp of the last failed attempt (if any).
25    pub last_failed_timestamp: Option<std::time::SystemTime>,
26}
27
28impl FaillockStatus {
29    /// What: Number of failed password attempts left before faillock locks the account.
30    ///
31    /// Inputs:
32    /// - `self`: Status returned by [`check_faillock_status`].
33    ///
34    /// Output:
35    /// - `Some(n)` with the attempts left, or `None` when lockout is disabled.
36    ///
37    /// Details:
38    /// - `max_attempts == 0` mirrors `deny = 0`, which disables `pam_faillock`
39    ///   lockout, so there is no attempt budget to report.
40    #[must_use]
41    pub const fn remaining_attempts(&self) -> Option<u32> {
42        if self.max_attempts == 0 {
43            return None;
44        }
45        Some(self.max_attempts.saturating_sub(self.attempts_used))
46    }
47}
48
49/// What: Faillock configuration values.
50///
51/// Inputs: None (parsed from `/etc/security/faillock.conf`).
52///
53/// Output: Configuration values for faillock behavior.
54///
55/// Details:
56/// - Contains the deny count (max attempts) and fail interval (lockout duration).
57#[derive(Debug, Clone)]
58pub struct FaillockConfig {
59    /// Maximum number of failed attempts before lockout (deny setting).
60    pub deny: u32,
61    /// Lockout duration in minutes (`fail_interval` setting).
62    pub fail_interval: u32,
63}
64
65/// What: Decide whether the recorded failure count triggers a lockout.
66///
67/// Inputs:
68/// - `attempts`: Number of consecutive failed attempts recorded for the user.
69/// - `deny`: Configured `deny` threshold (`0` disables lockout).
70///
71/// Output:
72/// - `true` if the account should currently be considered locked.
73///
74/// Details:
75/// - Mirrors `pam_faillock` semantics: `deny = 0` disables lockout entirely,
76///   so the threshold comparison must be skipped in that case.
77#[must_use]
78const fn lockout_triggered(attempts: u32, deny: u32) -> bool {
79    deny > 0 && attempts >= deny
80}
81
82/// What: Check faillock status for a user.
83///
84/// Inputs:
85/// - `username`: Username to check faillock status for.
86///
87/// Output:
88/// - `Ok(FaillockStatus)` with status information, or `Err(String)` on error.
89///
90/// # Errors
91///
92/// - Returns `Err` if the `faillock` command cannot be executed.
93///
94/// Details:
95/// - Executes `faillock --user <username>` command.
96/// - Parses output to count lines with "V" (valid attempts).
97/// - Compares with max attempts from config to determine if locked.
98/// - Returns status with attempt count, max attempts, lock status, and lockout duration.
99pub fn check_faillock_status(username: &str) -> Result<FaillockStatus, String> {
100    // Get config first to determine max attempts and lockout duration
101    let config = parse_faillock_config().unwrap_or(FaillockConfig {
102        deny: 3,
103        fail_interval: 15,
104    });
105
106    // Execute faillock command
107    let output = Command::new("faillock")
108        .args(["--user", username])
109        .output()
110        .map_err(|e| format!("Failed to execute faillock command: {e}"))?;
111
112    if !output.status.success() {
113        // If command fails, assume no lockout (might not be configured)
114        return Ok(FaillockStatus {
115            attempts_used: 0,
116            max_attempts: config.deny,
117            is_locked: false,
118            lockout_duration_minutes: config.fail_interval,
119            last_failed_timestamp: None,
120        });
121    }
122
123    let output_str = String::from_utf8_lossy(&output.stdout);
124    let lines: Vec<&str> = output_str.lines().collect();
125
126    // Count lines with "V" (valid attempts) - skip header line
127    // Also track the most recent failed attempt timestamp (the one that triggered lockout)
128    let mut attempts_used = 0u32;
129    let mut in_user_section = false;
130    let mut seen_header = false;
131    let mut most_recent_timestamp: Option<std::time::SystemTime> = None;
132
133    for line in lines {
134        let trimmed = line.trim();
135        if trimmed.is_empty() {
136            continue;
137        }
138
139        // Check if this is the username header line (format: "username:")
140        if trimmed.ends_with(':') && trimmed.trim_end_matches(':') == username {
141            in_user_section = true;
142            seen_header = false; // Reset header flag for this user section
143            continue;
144        }
145
146        // If we're in the user section, look for lines with "V"
147        if in_user_section {
148            // Skip the header line that contains "When", "Type", "Source", "Valid"
149            // This line also contains "V" but is not an attempt
150            if !seen_header
151                && trimmed.contains("When")
152                && trimmed.contains("Type")
153                && trimmed.contains("Source")
154                && trimmed.contains("Valid")
155            {
156                seen_header = true;
157                continue;
158            }
159
160            // Check if line contains "V" (valid attempt marker)
161            // Format is typically: "YYYY-MM-DD HH:MM:SS TTY /dev/pts/X V"
162            // Must be a date-like line (starts with YYYY-MM-DD format)
163            if (trimmed.contains(" V") || trimmed.ends_with('V'))
164                && trimmed.chars().take(4).all(|c| c.is_ascii_digit())
165            {
166                attempts_used += 1;
167                // Parse timestamp from the line (format: "YYYY-MM-DD HH:MM:SS")
168                // Extract first 19 characters which should be "YYYY-MM-DD HH:MM:SS"
169                if trimmed.len() >= 19 {
170                    let timestamp_str = &trimmed[0..19];
171                    if let Ok(dt) =
172                        chrono::NaiveDateTime::parse_from_str(timestamp_str, "%Y-%m-%d %H:%M:%S")
173                    {
174                        // Faillock timestamps are in local time, so we need to convert them properly
175                        // First, assume the timestamp is in local timezone
176                        let local_dt = dt.and_local_timezone(chrono::Local);
177                        // Get the single valid timezone conversion (or use UTC as fallback)
178                        let dt_utc = local_dt.single().map_or_else(
179                            || dt.and_utc(),
180                            |dt_local| dt_local.with_timezone(&chrono::Utc),
181                        );
182                        // Convert chrono DateTime to SystemTime
183                        let unix_timestamp = dt_utc.timestamp();
184                        if unix_timestamp >= 0
185                            && let Some(st) = std::time::SystemTime::UNIX_EPOCH.checked_add(
186                                std::time::Duration::from_secs(
187                                    u64::try_from(unix_timestamp).unwrap_or(0),
188                                ),
189                            )
190                        {
191                            // Keep the most recent timestamp (faillock shows oldest first, so last one is newest)
192                            most_recent_timestamp = Some(st);
193                        }
194                    }
195                }
196            }
197        }
198    }
199
200    // Check if user should be locked based on attempts
201    let should_be_locked = lockout_triggered(attempts_used, config.deny);
202
203    // If locked, check if lockout has expired based on timestamp
204    let is_locked = if should_be_locked {
205        most_recent_timestamp.map_or(should_be_locked, |last_timestamp| {
206            // Check if lockout duration has passed since last failed attempt
207            let now = std::time::SystemTime::now();
208            now.duration_since(last_timestamp).map_or(true, |elapsed| {
209                let lockout_seconds = u64::from(config.fail_interval) * 60;
210                // If elapsed time is less than lockout duration, user is still locked
211                elapsed.as_secs() < lockout_seconds
212            })
213        })
214    } else {
215        false
216    };
217
218    Ok(FaillockStatus {
219        attempts_used,
220        max_attempts: config.deny,
221        is_locked,
222        lockout_duration_minutes: config.fail_interval,
223        last_failed_timestamp: most_recent_timestamp,
224    })
225}
226
227/// What: Parse faillock configuration from `/etc/security/faillock.conf`.
228///
229/// Inputs: None (reads from system config file).
230///
231/// Output:
232/// - `Ok(FaillockConfig)` with parsed values, or `Err(String)` on error.
233///
234/// # Errors
235///
236/// - Returns `Err` if the config file cannot be read (though defaults are used in practice).
237///
238/// Details:
239/// - Reads `/etc/security/faillock.conf`.
240/// - Parses `deny` setting (default 3 if commented out).
241/// - Parses `fail_interval` setting (default 15 minutes if commented out).
242/// - Handles comments (lines starting with `#`) and whitespace.
243pub fn parse_faillock_config() -> Result<FaillockConfig, String> {
244    use std::fs;
245
246    let config_path = "/etc/security/faillock.conf";
247    let Ok(contents) = fs::read_to_string(config_path) else {
248        // File doesn't exist or can't be read, use defaults
249        return Ok(FaillockConfig {
250            deny: 3,
251            fail_interval: 15,
252        });
253    };
254
255    let mut deny = 3u32; // Default
256    let mut fail_interval = 15u32; // Default in minutes
257
258    for line in contents.lines() {
259        let trimmed = line.trim();
260
261        // Skip empty lines and full-line comments
262        if trimmed.is_empty() || trimmed.starts_with('#') {
263            continue;
264        }
265
266        // Handle inline comments
267        let line_without_comment = trimmed.split('#').next().unwrap_or("").trim();
268
269        // Parse deny setting
270        if line_without_comment.starts_with("deny")
271            && let Some(value_str) = line_without_comment.split('=').nth(1)
272        {
273            let value_trimmed = value_str.trim();
274            if let Ok(value) = value_trimmed.parse::<u32>() {
275                deny = value;
276            }
277        }
278
279        // Parse fail_interval setting
280        if line_without_comment.starts_with("fail_interval")
281            && let Some(value_str) = line_without_comment.split('=').nth(1)
282        {
283            let value_trimmed = value_str.trim();
284            if let Ok(value) = value_trimmed.parse::<u32>() {
285                fail_interval = value;
286            }
287        }
288    }
289
290    Ok(FaillockConfig {
291        deny,
292        fail_interval,
293    })
294}
295
296/// What: Check if user is locked out and return lockout message if so.
297///
298/// Inputs:
299/// - `username`: Username to check.
300/// - `app`: Application state for translations.
301///
302/// Output:
303/// - `Some(message)` if user is locked out, `None` otherwise.
304///
305/// Details:
306/// - Checks faillock status and returns formatted lockout message if locked.
307/// - Returns `None` if not locked or if check fails.
308/// - Uses translations from `AppState`.
309#[must_use]
310pub fn get_lockout_message_if_locked(
311    username: &str,
312    app: &crate::state::AppState,
313) -> Option<String> {
314    if let Ok(status) = check_faillock_status(username)
315        && status.is_locked
316    {
317        return Some(crate::i18n::t_fmt(
318            app,
319            "app.modals.alert.account_locked_with_time",
320            &[
321                &username as &dyn std::fmt::Display,
322                &status.lockout_duration_minutes,
323            ],
324        ));
325    }
326    None
327}
328
329/// What: Calculate remaining lockout time in minutes based on last failed attempt timestamp.
330///
331/// Inputs:
332/// - `last_timestamp`: Timestamp of the last failed attempt.
333/// - `lockout_duration_minutes`: Total lockout duration in minutes.
334///
335/// Output:
336/// - `Some(minutes)` if still locked out, `None` if lockout has expired.
337///
338/// Details:
339/// - Calculates time elapsed since last failed attempt.
340/// - Returns remaining minutes if lockout is still active, `None` if expired.
341#[must_use]
342pub fn calculate_remaining_lockout_minutes(
343    last_timestamp: &std::time::SystemTime,
344    lockout_duration_minutes: u32,
345) -> Option<u32> {
346    let now = std::time::SystemTime::now();
347    now.duration_since(*last_timestamp)
348        .map_or(Some(lockout_duration_minutes), |elapsed| {
349            let lockout_seconds = u64::from(lockout_duration_minutes) * 60;
350            if elapsed.as_secs() < lockout_seconds {
351                let remaining_seconds = lockout_seconds - elapsed.as_secs();
352                let remaining_minutes =
353                    (remaining_seconds / 60) + u64::from(remaining_seconds % 60 > 0);
354                Some(u32::try_from(remaining_minutes.min(u64::from(u32::MAX))).unwrap_or(u32::MAX))
355            } else {
356                None // Lockout expired
357            }
358        })
359}
360
361/// What: Check faillock status and calculate lockout information for display.
362///
363/// Inputs:
364/// - `username`: Username to check.
365///
366/// Output:
367/// - Tuple of `(is_locked, lockout_until, remaining_minutes)`.
368///
369/// Details:
370/// - Checks faillock status and calculates remaining lockout time if locked.
371/// - Returns lockout information for UI display.
372#[must_use]
373pub fn get_lockout_info(username: &str) -> (bool, Option<std::time::SystemTime>, Option<u32>) {
374    if let Ok(status) = check_faillock_status(username)
375        && status.is_locked
376    {
377        if let Some(last_timestamp) = status.last_failed_timestamp {
378            let remaining = calculate_remaining_lockout_minutes(
379                &last_timestamp,
380                status.lockout_duration_minutes,
381            );
382            // Calculate lockout_until timestamp
383            let lockout_until = last_timestamp
384                + std::time::Duration::from_secs(u64::from(status.lockout_duration_minutes) * 60);
385            // Return remaining time - if None, it means lockout expired, show 0
386            // But if timestamp is in future (timezone issue), remaining should be Some
387            return (true, Some(lockout_until), remaining);
388        }
389        // Locked but no timestamp - still show as locked but no time remaining
390        return (true, None, Some(0));
391    }
392    (false, None, None)
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398    use std::fs;
399    use std::io::Write;
400
401    #[test]
402    /// What: Test parsing faillock config with defaults.
403    ///
404    /// Inputs:
405    /// - Config file that doesn't exist or has commented settings.
406    ///
407    /// Output:
408    /// - Returns default values (deny=3, `fail_interval=15`).
409    ///
410    /// Details:
411    /// - Verifies default values are used when config is missing or commented.
412    fn test_parse_faillock_config_defaults() {
413        // This test may fail if the file exists, but that's okay
414        // The function should handle missing files gracefully
415        let _config = parse_faillock_config();
416        // Just verify it doesn't panic
417    }
418
419    #[test]
420    /// What: Test parsing faillock config with custom values.
421    ///
422    /// Inputs:
423    /// - Temporary config file with custom deny and `fail_interval` values.
424    ///
425    /// Output:
426    /// - Returns parsed values from config file.
427    ///
428    /// Details:
429    /// - Creates a temporary config file and verifies parsing works correctly.
430    fn test_parse_faillock_config_custom_values() {
431        use std::env::temp_dir;
432        let temp_file = temp_dir().join("test_faillock.conf");
433        let content = "deny = 5\nfail_interval = 30\n";
434        if let Ok(mut file) = fs::File::create(&temp_file) {
435            let _ = file.write_all(content.as_bytes());
436            // Note: We can't easily test this without mocking file reading
437            // Just verify the function doesn't panic
438            let _config = parse_faillock_config();
439            let _ = fs::remove_file(&temp_file);
440        }
441    }
442
443    #[test]
444    /// What: Test parsing faillock config with comments.
445    ///
446    /// Inputs:
447    /// - Config file with commented lines and inline comments.
448    ///
449    /// Output:
450    /// - Parses values correctly, ignoring comments.
451    ///
452    /// Details:
453    /// - Verifies that comments (both full-line and inline) are handled correctly.
454    fn test_parse_faillock_config_with_comments() {
455        // The function should handle comments correctly
456        // Since we can't easily mock file reading, just verify it doesn't panic
457        let _config = parse_faillock_config();
458    }
459
460    #[test]
461    /// What: Test faillock status checking handles errors gracefully.
462    ///
463    /// Inputs:
464    /// - Username that may or may not have faillock entries.
465    ///
466    /// Output:
467    /// - Returns status without panicking.
468    ///
469    /// Details:
470    /// - Verifies the function handles various error cases.
471    fn test_check_faillock_status_handles_errors() {
472        let username = std::env::var("USER").unwrap_or_else(|_| "testuser".to_string());
473        let result = check_faillock_status(&username);
474        // Should return Ok or handle errors gracefully
475        if let Ok(status) = result {
476            // `max_attempts` may legitimately be 0 (`deny = 0` disables lockout).
477            assert!(status.lockout_duration_minutes > 0);
478        } else {
479            // Error is acceptable (e.g., faillock not configured)
480        }
481    }
482
483    #[test]
484    /// What: Test faillock status structure.
485    ///
486    /// Inputs:
487    /// - Username.
488    ///
489    /// Output:
490    /// - Returns status with all fields populated.
491    ///
492    /// Details:
493    /// - Verifies that the status struct contains all expected fields.
494    fn test_faillock_status_structure() {
495        let username = std::env::var("USER").unwrap_or_else(|_| "testuser".to_string());
496        if let Ok(status) = check_faillock_status(&username) {
497            // Verify all fields are present
498            let _ = status.attempts_used;
499            let _ = status.max_attempts;
500            let _ = status.is_locked;
501            let _ = status.lockout_duration_minutes;
502            // Just verify the struct can be accessed
503        }
504    }
505
506    #[test]
507    /// What: `deny = 0` never triggers a lockout.
508    ///
509    /// Inputs:
510    /// - Zero and non-zero failure counts with `deny = 0`.
511    ///
512    /// Output:
513    /// - `lockout_triggered` returns `false` for every count.
514    ///
515    /// Details:
516    /// - Regression test for #169: `pam_faillock` treats `deny = 0` as disabled.
517    fn deny_zero_disables_lockout() {
518        assert!(!lockout_triggered(0, 0));
519        assert!(!lockout_triggered(5, 0));
520    }
521
522    #[test]
523    /// What: A positive `deny` still locks at the threshold.
524    ///
525    /// Inputs:
526    /// - Failure counts below, at, and above `deny = 3`.
527    ///
528    /// Output:
529    /// - `false` below the threshold, `true` at or above it.
530    ///
531    /// Details:
532    /// - Guards the normal lockout path against the `deny = 0` change.
533    fn deny_threshold_still_works() {
534        assert!(!lockout_triggered(2, 3));
535        assert!(lockout_triggered(3, 3));
536        assert!(lockout_triggered(4, 3));
537    }
538
539    /// What: Build a `FaillockStatus` for attempt-budget tests.
540    ///
541    /// Inputs:
542    /// - `attempts_used`: Recorded failures.
543    /// - `max_attempts`: Configured `deny` value.
544    ///
545    /// Output:
546    /// - An unlocked status with no timestamp.
547    ///
548    /// Details:
549    /// - Avoids reading the host's faillock state in unit tests.
550    const fn status_with(attempts_used: u32, max_attempts: u32) -> FaillockStatus {
551        FaillockStatus {
552            attempts_used,
553            max_attempts,
554            is_locked: false,
555            lockout_duration_minutes: 15,
556            last_failed_timestamp: None,
557        }
558    }
559
560    #[test]
561    /// What: `deny = 0` reports no attempt budget.
562    ///
563    /// Inputs:
564    /// - Status with `max_attempts = 0` and zero or more failures.
565    ///
566    /// Output:
567    /// - `remaining_attempts` returns `None`.
568    ///
569    /// Details:
570    /// - Without this, the password prompt says "0 attempts remaining" on
571    ///   systems that disabled lockout.
572    fn remaining_attempts_none_when_lockout_disabled() {
573        assert_eq!(status_with(0, 0).remaining_attempts(), None);
574        assert_eq!(status_with(2, 0).remaining_attempts(), None);
575    }
576
577    #[test]
578    /// What: A positive `deny` reports the attempts left.
579    ///
580    /// Inputs:
581    /// - Status with `max_attempts = 3` and 1 or 5 failures.
582    ///
583    /// Output:
584    /// - `Some(2)` for 1 failure, `Some(0)` once the budget is spent.
585    ///
586    /// Details:
587    /// - Saturates instead of underflowing past the threshold.
588    fn remaining_attempts_counts_down_when_lockout_enabled() {
589        assert_eq!(status_with(1, 3).remaining_attempts(), Some(2));
590        assert_eq!(status_with(5, 3).remaining_attempts(), Some(0));
591    }
592}