rootasrole 4.1.0

A better alternative to sudo(-rs)/su
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use std::{borrow::Cow, ffi::CStr};

use bon::Builder;
use log::{debug, error, info, warn};
use nonstick2::{
    AuthnFlags, ConversationAdapter, ErrorCode, LibPamTransaction, PamShared, Result as PamResult,
    TransactionBuilder, conv::Demux, items::ItemsMut, libpam::SessionActive,
};

#[cfg(feature = "timeout")]
use crate::timeout;
use crate::{
    Cli,
    error::{SrError, SrResult},
};
use rootasrole_core::{
    Cred,
    database::options::{SAuthentication, STimeout},
};

use self::rpassword::Terminal;

#[allow(dead_code, reason = "This file is part of sudo-rs.")]
mod cutils;
#[allow(dead_code, reason = "This file is part of sudo-rs.")]
pub mod rpassword;
#[allow(dead_code, reason = "This file is part of sudo-rs.")]
pub mod securemem;

const PAM_SERVICE: &str = env!("RAR_PAM_SERVICE");
pub const PAM_PROMPT: &str = "Password: ";

#[derive(Builder)]
pub struct SrConversationHandler<'a> {
    #[builder(into)]
    username: Option<Cow<'a, str>>,
    #[builder(default = "Password: ", into)]
    prompt: Cow<'a, str>,
    #[builder(default)]
    use_stdin: bool,
    #[builder(default)]
    no_interact: bool,
}

impl SrConversationHandler<'_> {
    fn open(&self) -> std::io::Result<Terminal<'_>> {
        if self.use_stdin {
            Ok(Terminal::open_stdie())
        } else {
            Terminal::open_tty()
        }
    }
    /// Whether PAM asks for the password with its default prompt, `Password:` or
    /// `<user>'s Password:`, optionally followed by one space.
    fn is_pam_password_prompt(&self, prompt: &impl AsRef<str>) -> bool {
        let is_password = |prompt: &str| matches!(prompt, "Password:" | "Password: ");
        let pam_prompt = prompt.as_ref();
        is_password(pam_prompt)
            || self.username.as_ref().is_some_and(|username| {
                pam_prompt
                    .strip_prefix(username.as_ref())
                    .and_then(|prompt| prompt.strip_prefix("'s "))
                    .is_some_and(is_password)
            })
    }
}

impl Default for SrConversationHandler<'_> {
    fn default() -> Self {
        SrConversationHandler {
            prompt: "Password: ".into(),
            username: None,
            use_stdin: false,
            no_interact: false,
        }
    }
}

impl ConversationAdapter for SrConversationHandler<'_> {
    fn prompt(&self, prompt: impl AsRef<std::ffi::OsStr>) -> PamResult<std::ffi::OsString> {
        if self.no_interact {
            return Err(ErrorCode::ConversationError);
        }
        let mut term = self.open().map_err(|_| ErrorCode::ConversationError)?;
        term.prompt(&prompt.as_ref().to_string_lossy().to_string())
            .map_err(|_| ErrorCode::ConversationError)?;
        let read = term.read_cleartext().map_err(|_| ErrorCode::BufferError)?;
        drop(term);
        Ok(std::ffi::OsString::from(
            String::from_utf8_lossy(&read).to_string(),
        ))
    }

    fn masked_prompt(&self, prompt: impl AsRef<std::ffi::OsStr>) -> PamResult<std::ffi::OsString> {
        if self.no_interact {
            return Err(ErrorCode::ConversationError);
        }
        //if the prompted message is the password prompt, we replace to self.prompt
        let pam_prompt = if self.is_pam_password_prompt(&prompt.as_ref().to_string_lossy()) {
            self.prompt.clone()
        } else {
            prompt.as_ref().to_string_lossy()
        };
        let mut term = self.open().map_err(|_| ErrorCode::ConversationError)?;
        term.prompt(&pam_prompt)
            .map_err(|_| ErrorCode::ConversationError)?;
        let read = term.read_password().map_err(|_| ErrorCode::BufferError)?;
        drop(term);
        let os_str = CStr::from_bytes_until_nul(&read)
            .map_err(|_| ErrorCode::BufferError)?
            .to_str()
            .map_err(|_| ErrorCode::BufferError)?;
        Ok(std::ffi::OsString::from(os_str))
    }

    fn error_msg(&self, message: impl AsRef<std::ffi::OsStr>) {
        error!("{}", message.as_ref().to_string_lossy());
        eprintln!("{}", message.as_ref().to_string_lossy());
    }

    fn info_msg(&self, message: impl AsRef<std::ffi::OsStr>) {
        info!("{}", message.as_ref().to_string_lossy());
        println!("{}", message.as_ref().to_string_lossy());
    }
}

/// The terminal and the requesting user of the transaction, like sudo sets them: modules such
/// as `pam_access`, `pam_securetty` or `pam_tty_audit`, and the logs, read them.
fn set_pam_items(txn: &mut impl PamShared, user: &Cred) -> PamResult<()> {
    use rootasrole_exec::terminal::TerminalExt;
    let mut items = txn.items_mut();
    items.set_remote_user(Some(std::ffi::OsStr::new(&user.user.name)))?;
    if let Ok(tty) = std::io::stdin().ttyname() {
        items.set_tty_name(Some(&tty))?;
    }
    Ok(())
}

pub fn start_session<'a>(
    authentication: SAuthentication,
    #[cfg_attr(not(feature = "timeout"), allow(unused_variables))] timeout: &STimeout,
    user: &Cred,
    cli: &Cli,
) -> SrResult<LibPamTransaction<Demux<SrConversationHandler<'a>>, SessionActive>> {
    let need_password_auth = if authentication.is_skip() {
        warn!("Skipping password authentication (PAM session-only mode).");
        false
    } else {
        #[cfg(feature = "timeout")]
        {
            !timeout::is_valid(user, user, timeout)
        }
        #[cfg(not(feature = "timeout"))]
        {
            true
        }
    };

    debug!("need password authentication: {need_password_auth}");

    let conv = SrConversationHandler::builder()
        .maybe_prompt(cli.prompt.as_ref().map(|s| Cow::Owned(s.clone())))
        .use_stdin(cli.stdin)
        .build();

    let mut txn = TransactionBuilder::new_with_service(PAM_SERVICE)
        .username(&user.user.name)
        .build(conv.into_conversation())
        .map_err(|e| {
            error!("Failed to create PAM transaction: {e}");
            SrError::SystemError
        })?;
    set_pam_items(&mut txn, user).map_err(|e| {
        error!("Failed to set the terminal and the requesting user for PAM: {e}");
        SrError::SystemError
    })?;

    let txn = if need_password_auth {
        txn.authenticate(AuthnFlags::SILENT)
            .map_err(|e| {
                error!("Authentication failed: {}", e.1);
                SrError::AuthenticationFailed
            })?
            .account_management(AuthnFlags::SILENT)
            .map_err(|e| {
                error!("Authentication failed: {}", e.1);
                SrError::AuthenticationFailed
            })?
    } else {
        txn.account_management(AuthnFlags::SILENT).map_err(|e| {
            error!("Account management failed: {}", e.1);
            SrError::AuthenticationFailed
        })?
    };

    let txn = txn
        .establish_credentials()
        .map_err(|e| {
            error!("Failed to establish credentials: {}", e.1);
            SrError::SystemError
        })?
        .open_session()
        .map_err(|e| {
            error!("Failed to open session: {}", e.1);
            SrError::SystemError
        })?;

    // Failing to save the cookie only means that the user will be asked to authenticate again
    #[cfg(feature = "timeout")]
    if let Err(e) = timeout::update_cookie(user, user, timeout) {
        error!("Failed to update timeout cookie: {e}");
    }

    Ok(txn)
}

#[cfg(test)]
mod tests {
    use super::*;
    use jiff::SignedDuration;
    use nix::{libc::dev_t, unistd::Pid};
    use nonstick2::items::Items;
    use rootasrole_core::{
        Cred,
        database::options::{SAuthentication, STimeout, TimestampType},
    };
    use rootasrole_exec::terminal::TerminalExt;
    use serde_json::Map;
    use std::{ffi::OsStr, sync::Mutex};
    use test_log::test;

    static PAM_TEST_LOCK: Mutex<()> = Mutex::new(());

    // Helper function to create a test user
    fn create_test_user() -> Cred {
        Cred::builder()
            .maybe_tty(Some(0 as dev_t))
            .ppid(Pid::from_raw(1))
            .groups()
            .unwrap()
            .user()
            .unwrap()
            .curdir()
            .unwrap()
            .build()
    }

    // Helper function to create a test timeout
    fn create_test_timeout() -> STimeout {
        STimeout {
            type_field: Some(TimestampType::TTY),
            duration: Some(SignedDuration::from_secs(300)), // 5 minutes
            max_usage: Some(3),
            extra_fields: Map::default(),
        }
    }

    fn pam_ready(user: &Cred) -> bool {
        let conv = SrConversationHandler::builder().no_interact(true).build();

        let Ok(txn) = TransactionBuilder::new_with_service(PAM_SERVICE)
            .username(&user.user.name)
            .build(conv.into_conversation())
        else {
            return false;
        };

        txn.account_management(AuthnFlags::SILENT).is_ok()
    }

    #[test]
    fn test_pam_items_are_set() {
        let user = create_test_user();
        let conv = SrConversationHandler::builder().no_interact(true).build();
        let Ok(mut txn) = TransactionBuilder::new_with_service(PAM_SERVICE)
            .username(&user.user.name)
            .build(conv.into_conversation())
        else {
            eprintln!("Skipping test, PAM is not available");
            return;
        };
        set_pam_items(&mut txn, &user).unwrap();
        assert_eq!(
            txn.items().remote_user().unwrap(),
            Some(std::ffi::OsString::from(&user.user.name))
        );
        // the terminal of the test, when it has one
        assert_eq!(
            txn.items().tty_name().unwrap(),
            std::io::stdin().ttyname().ok()
        );
    }

    #[test]
    fn test_sr_conversation_handler_new() {
        let handler = SrConversationHandler::builder()
            .prompt("Test prompt: ")
            .build();
        assert_eq!(handler.prompt, "Test prompt: ");
        assert!(handler.username.is_none());
        assert!(!handler.use_stdin);
        assert!(!handler.no_interact);
    }

    #[test]
    fn test_sr_conversation_handler_default() {
        let handler = SrConversationHandler::default();
        assert_eq!(handler.prompt, "Password: ");
        assert!(handler.username.is_none());
        assert!(!handler.use_stdin);
        assert!(!handler.no_interact);
    }

    #[test]
    fn test_is_pam_password_prompt_basic() {
        let handler = SrConversationHandler::default();

        // Test basic password prompts
        assert!(handler.is_pam_password_prompt(&"Password:"));
        assert!(handler.is_pam_password_prompt(&"Password: "));
        assert!(!handler.is_pam_password_prompt(&"Enter password:"));
        assert!(!handler.is_pam_password_prompt(&"Password required:"));
        assert!(!handler.is_pam_password_prompt(&""));
    }

    #[test]
    fn test_is_pam_password_prompt_with_username() {
        let handler = SrConversationHandler::builder()
            .username("testuser")
            .build();

        // Test user-specific password prompts
        assert!(handler.is_pam_password_prompt(&"testuser's Password:"));
        assert!(handler.is_pam_password_prompt(&"testuser's Password: "));
        assert!(!handler.is_pam_password_prompt(&"otheruser's Password:"));
        assert!(!handler.is_pam_password_prompt(&"testuser Password:")); // Missing apostrophe-s
        assert!(!handler.is_pam_password_prompt(&"testuser's Password:  "));
        assert!(!handler.is_pam_password_prompt(&"testuser's Password: x"));
        // the username is compared as text, never as a pattern
        let handler = SrConversationHandler::builder().username("a.b").build();
        assert!(handler.is_pam_password_prompt(&"a.b's Password:"));
        assert!(!handler.is_pam_password_prompt(&"axb's Password:"));
    }

    #[test]
    fn test_conversation_handler_error_msg() {
        let handler = SrConversationHandler::default();

        // This test verifies the error_msg method doesn't panic
        // In a real test environment, you might want to capture stderr
        handler.error_msg(OsStr::new("Test error message"));
    }

    #[test]
    fn test_conversation_handler_info_msg() {
        let handler = SrConversationHandler::default();

        // This test verifies the info_msg method doesn't panic
        // In a real test environment, you might want to capture stdout
        handler.info_msg(OsStr::new("Test info message"));
    }

    #[test]
    fn test_check_auth_skip_authentication() {
        let _ = env_logger::builder().is_test(true).try_init();
        let authentication = SAuthentication::Skip;
        let timeout = create_test_timeout();
        let user = create_test_user();

        let _guard = PAM_TEST_LOCK.lock().unwrap();

        if !pam_ready(&user) {
            eprintln!("Skipping: PAM backend not available in this test environment");
            return;
        }

        // When authentication is skipped, it should always succeed
        let cli = Cli::builder().prompt("Password: ").build();
        let result = start_session(authentication, &timeout, &user, &cli);
        assert!(result.is_ok());
    }

    #[test]
    fn test_check_auth_required_but_valid_timeout() {
        let _guard = PAM_TEST_LOCK.lock().unwrap();
        if env!("RAR_PAM_SERVICE") == "dosr" {
            println!(
                "Skipping test_check_auth_required_but_valid_timeout because RAR_PAM_SERVICE is set to original dosr"
            );
            return;
        }
        let authentication = SAuthentication::Perform;
        let timeout = create_test_timeout();
        let user = create_test_user();

        let cli = Cli::builder().prompt("Password: ").build();
        let _ = start_session(authentication, &timeout, &user, &cli);
    }

    #[test]
    fn test_conversation_handler_no_interact_flag() {
        let handler = SrConversationHandler::builder().no_interact(true).build();

        let prompt_result = handler.prompt(OsStr::new("Test prompt"));
        assert!(matches!(prompt_result, Err(ErrorCode::ConversationError)));

        let masked_prompt_result = handler.masked_prompt(OsStr::new("Password:"));
        assert!(matches!(
            masked_prompt_result,
            Err(ErrorCode::ConversationError)
        ));
    }

    #[test]
    fn test_password_prompt_replacement() {
        let custom_prompt = "Enter your secret: ";
        let handler = SrConversationHandler::builder()
            .prompt(custom_prompt)
            .build();

        assert_eq!(handler.prompt, custom_prompt);

        assert!(handler.is_pam_password_prompt(&"Password:"));
        assert!(handler.is_pam_password_prompt(&"Password: "));
    }

    #[test]
    fn test_regex_patterns_edge_cases() {
        let handler = SrConversationHandler::builder()
            .username("user.with.dots")
            .build();

        // Test with username containing special regex characters
        assert!(handler.is_pam_password_prompt(&"user.with.dots's Password:"));

        // Test case sensitivity
        assert!(!handler.is_pam_password_prompt(&"password:"));
        assert!(!handler.is_pam_password_prompt(&"PASSWORD:"));

        // Test with extra spaces and characters
        assert!(!handler.is_pam_password_prompt(&"Password:  ")); // Extra spaces
        assert!(!handler.is_pam_password_prompt(&" Password:")); // Leading space
    }

    #[test]
    fn test_conversation_handler_fields() {
        let handler = SrConversationHandler::builder()
            .prompt("Custom: ")
            .use_stdin(true)
            .no_interact(true)
            .username("alice")
            .build();

        assert!(handler.use_stdin);
        assert!(handler.no_interact);
        assert_eq!(handler.username.as_ref().unwrap(), "alice");
        assert_eq!(handler.prompt, "Custom: ");
    }

    #[test]
    fn test_timeout_types() {
        let _guard = PAM_TEST_LOCK.lock().unwrap();
        let timeout_ppid = STimeout {
            type_field: Some(TimestampType::PPID),
            duration: Some(SignedDuration::from_secs(300)),
            max_usage: Some(1),
            extra_fields: Map::default(),
        };

        let timeout_tty = STimeout {
            type_field: Some(TimestampType::TTY),
            duration: Some(SignedDuration::from_secs(600)),
            max_usage: Some(5),
            extra_fields: Map::default(),
        };

        let user = create_test_user();
        if !pam_ready(&user) {
            eprintln!("Skipping: PAM backend not available in this test environment");
            return;
        }
        let auth = SAuthentication::Skip;

        let cli = Cli::builder().prompt("Password: ").build();
        // Test different timeout types don't cause errors
        assert!(start_session(auth, &timeout_ppid, &user, &cli).is_ok());
        assert!(start_session(auth, &timeout_tty, &user, &cli).is_ok());
    }
}