pam_kanidm/
core.rs

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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
use crate::constants::PamResultCode;
use crate::module::PamResult;
use crate::pam::ModuleOptions;
use kanidm_unix_common::client_sync::DaemonClientBlocking;
use kanidm_unix_common::unix_config::KanidmUnixdConfig;
use kanidm_unix_common::unix_passwd::{
    read_etc_passwd_file, read_etc_shadow_file, EtcShadow, EtcUser,
};
use kanidm_unix_common::unix_proto::{ClientRequest, ClientResponse};
use kanidm_unix_common::unix_proto::{
    DeviceAuthorizationResponse, PamAuthRequest, PamAuthResponse, PamServiceInfo,
};
use std::time::Duration;
use time::OffsetDateTime;

use tracing::{debug, error};

#[cfg(test)]
use kanidm_unix_common::client_sync::UnixStream;

pub enum RequestOptions {
    Main {
        config_path: &'static str,
    },
    #[cfg(test)]
    Test {
        socket: Option<UnixStream>,
        users: Vec<EtcUser>,
        // groups: Vec<EtcGroup>,
        shadow: Vec<EtcShadow>,
    },
}

enum Source {
    Daemon(DaemonClientBlocking),
    Fallback {
        users: Vec<EtcUser>,
        // groups: Vec<EtcGroup>,
        shadow: Vec<EtcShadow>,
    },
}

impl RequestOptions {
    fn connect_to_daemon(self) -> Source {
        match self {
            RequestOptions::Main { config_path } => {
                let maybe_client = KanidmUnixdConfig::new()
                    .read_options_from_optional_config(config_path)
                    .ok()
                    .and_then(|cfg| {
                        DaemonClientBlocking::new(cfg.sock_path.as_str(), cfg.unix_sock_timeout)
                            .ok()
                    });

                if let Some(client) = maybe_client {
                    Source::Daemon(client)
                } else {
                    let users = read_etc_passwd_file("/etc/passwd").unwrap_or_default();
                    // let groups = read_etc_group_file("/etc/group").unwrap_or_default();
                    let shadow = read_etc_shadow_file("/etc/shadow").unwrap_or_default();
                    Source::Fallback {
                        users,
                        // groups,
                        shadow,
                    }
                }
            }
            #[cfg(test)]
            RequestOptions::Test {
                socket,
                users,
                // groups,
                shadow,
            } => {
                if let Some(socket) = socket {
                    Source::Daemon(DaemonClientBlocking::from(socket))
                } else {
                    Source::Fallback { users, shadow }
                }
            }
        }
    }
}

pub trait PamHandler {
    fn account_id(&self) -> PamResult<String>;

    fn service_info(&self) -> PamResult<PamServiceInfo>;

    fn authtok(&self) -> PamResult<Option<String>>;

    /// Display a message to the user.
    fn message(&self, prompt: &str) -> PamResult<()>;

    /// Display a device grant request to the user.
    fn message_device_grant(&self, data: &DeviceAuthorizationResponse) -> PamResult<()>;

    /// Request a password from the user.
    fn prompt_for_password(&self) -> PamResult<Option<String>>;

    fn prompt_for_pin(&self, msg: Option<&str>) -> PamResult<Option<String>>;

    fn prompt_for_mfacode(&self) -> PamResult<Option<String>>;
}

pub fn sm_authenticate_connected<P: PamHandler>(
    pamh: &P,
    opts: &ModuleOptions,
    _current_time: OffsetDateTime,
    mut daemon_client: DaemonClientBlocking,
) -> PamResultCode {
    let info = match pamh.service_info() {
        Ok(info) => info,
        Err(e) => {
            error!(err = ?e, "get_pam_info");
            return e;
        }
    };

    let account_id = match pamh.account_id() {
        Ok(acc) => acc,
        Err(err) => return err,
    };

    let mut timeout: Option<u64> = None;
    let mut active_polling_interval = Duration::from_secs(1);

    let mut stacked_authtok = if opts.use_first_pass {
        match pamh.authtok() {
            Ok(authtok) => authtok,
            Err(err) => return err,
        }
    } else {
        None
    };

    let mut req = ClientRequest::PamAuthenticateInit { account_id, info };

    loop {
        let client_response = match daemon_client.call_and_wait(&req, timeout) {
            Ok(r) => r,
            Err(err) => {
                // Something unrecoverable occurred, bail and stop everything
                error!(?err, "PAM_AUTH_ERR");
                return PamResultCode::PAM_AUTH_ERR;
            }
        };

        match client_response {
            ClientResponse::PamAuthenticateStepResponse(PamAuthResponse::Success) => {
                return PamResultCode::PAM_SUCCESS;
            }
            ClientResponse::PamAuthenticateStepResponse(PamAuthResponse::Denied) => {
                return PamResultCode::PAM_AUTH_ERR;
            }
            ClientResponse::PamAuthenticateStepResponse(PamAuthResponse::Unknown) => {
                if opts.ignore_unknown_user {
                    return PamResultCode::PAM_IGNORE;
                } else {
                    return PamResultCode::PAM_USER_UNKNOWN;
                }
            }
            ClientResponse::PamAuthenticateStepResponse(PamAuthResponse::Password) => {
                let mut authtok = None;
                std::mem::swap(&mut authtok, &mut stacked_authtok);

                let cred = if let Some(cred) = authtok {
                    cred
                } else {
                    match pamh.prompt_for_password() {
                        Ok(Some(cred)) => cred,
                        Ok(None) => return PamResultCode::PAM_CRED_INSUFFICIENT,
                        Err(err) => return err,
                    }
                };

                // Now setup the request for the next loop.
                timeout = None;
                req = ClientRequest::PamAuthenticateStep(PamAuthRequest::Password { cred });
                continue;
            }
            ClientResponse::PamAuthenticateStepResponse(
                PamAuthResponse::DeviceAuthorizationGrant { data },
            ) => {
                if let Err(err) = pamh.message_device_grant(&data) {
                    return err;
                };

                timeout = Some(u64::from(data.expires_in));
                req =
                    ClientRequest::PamAuthenticateStep(PamAuthRequest::DeviceAuthorizationGrant {
                        data,
                    });
                continue;
            }
            ClientResponse::PamAuthenticateStepResponse(PamAuthResponse::MFACode { msg: _ }) => {
                let cred = match pamh.prompt_for_mfacode() {
                    Ok(Some(cred)) => cred,
                    Ok(None) => return PamResultCode::PAM_CRED_INSUFFICIENT,
                    Err(err) => return err,
                };

                // Now setup the request for the next loop.
                timeout = None;
                req = ClientRequest::PamAuthenticateStep(PamAuthRequest::MFACode { cred });
                continue;
            }
            ClientResponse::PamAuthenticateStepResponse(PamAuthResponse::MFAPoll {
                msg,
                polling_interval,
            }) => {
                if let Err(err) = pamh.message(msg.as_str()) {
                    if opts.debug {
                        println!("Message prompt failed");
                    }
                    return err;
                }

                active_polling_interval = Duration::from_secs(polling_interval.into());

                timeout = None;
                req = ClientRequest::PamAuthenticateStep(PamAuthRequest::MFAPoll);
                // We don't need to actually sleep here as we immediately will poll and then go
                // into the MFAPollWait response below.
            }
            ClientResponse::PamAuthenticateStepResponse(PamAuthResponse::MFAPollWait) => {
                // Counter intuitive, but we don't need a max poll attempts here because
                // if the resolver goes away, then this will error on the sock and
                // will shutdown. This allows the resolver to dynamically extend the
                // timeout if needed, and removes logic from the front end.
                std::thread::sleep(active_polling_interval);
                timeout = None;
                req = ClientRequest::PamAuthenticateStep(PamAuthRequest::MFAPoll);
            }

            ClientResponse::PamAuthenticateStepResponse(PamAuthResponse::SetupPin { msg }) => {
                if let Err(err) = pamh.message(msg.as_str()) {
                    return err;
                }

                let mut pin;
                let mut confirm;

                loop {
                    pin = match pamh.prompt_for_pin(Some("New PIN: ")) {
                        Ok(Some(p)) => p,
                        Ok(None) => {
                            debug!("no pin");
                            return PamResultCode::PAM_CRED_INSUFFICIENT;
                        }
                        Err(err) => {
                            debug!("unable to get pin");
                            return err;
                        }
                    };

                    confirm = match pamh.prompt_for_pin(Some("Confirm PIN: ")) {
                        Ok(Some(p)) => p,
                        Ok(None) => {
                            debug!("no pin");
                            return PamResultCode::PAM_CRED_INSUFFICIENT;
                        }
                        Err(err) => {
                            debug!("unable to get pin");
                            return err;
                        }
                    };

                    if pin == confirm {
                        break;
                    } else if let Err(err) = pamh.message("Inputs did not match. Try again.") {
                        return err;
                    }
                }

                // Now setup the request for the next loop.
                timeout = None;
                req = ClientRequest::PamAuthenticateStep(PamAuthRequest::SetupPin { pin });
                continue;
            }
            ClientResponse::PamAuthenticateStepResponse(PamAuthResponse::Pin) => {
                let mut authtok = None;
                std::mem::swap(&mut authtok, &mut stacked_authtok);

                let cred = if let Some(cred) = authtok {
                    cred
                } else {
                    match pamh.prompt_for_pin(None) {
                        Ok(Some(cred)) => cred,
                        Ok(None) => return PamResultCode::PAM_CRED_INSUFFICIENT,
                        Err(err) => return err,
                    }
                };

                // Now setup the request for the next loop.
                timeout = None;
                req = ClientRequest::PamAuthenticateStep(PamAuthRequest::Pin { cred });
                continue;
            }

            ClientResponse::Error(err) => {
                error!("Error from kanidm-unixd: {}", err);
                return PamResultCode::PAM_AUTH_ERR;
            }
            ClientResponse::Ok
            | ClientResponse::SshKeys(_)
            | ClientResponse::NssAccounts(_)
            | ClientResponse::NssAccount(_)
            | ClientResponse::NssGroups(_)
            | ClientResponse::PamStatus(_)
            | ClientResponse::ProviderStatus(_)
            | ClientResponse::NssGroup(_) => {
                debug!("PamResultCode::PAM_AUTH_ERR");
                return PamResultCode::PAM_AUTH_ERR;
            }
        }
    } // while true, continue calling PamAuthenticateStep until we get a decision.
}

pub fn sm_authenticate_fallback<P: PamHandler>(
    pamh: &P,
    opts: &ModuleOptions,
    current_time: OffsetDateTime,
    users: Vec<EtcUser>,
    shadow: Vec<EtcShadow>,
) -> PamResultCode {
    let account_id = match pamh.account_id() {
        Ok(acc) => acc,
        Err(err) => return err,
    };

    let user = users.into_iter().find(|etcuser| etcuser.name == account_id);

    let shadow = shadow
        .into_iter()
        .find(|etcshadow| etcshadow.name == account_id);

    let (_user, shadow) = match (user, shadow) {
        (Some(user), Some(shadow)) => (user, shadow),
        _ => {
            if opts.ignore_unknown_user {
                debug!("PamResultCode::PAM_IGNORE");
                return PamResultCode::PAM_IGNORE;
            } else {
                debug!("PamResultCode::PAM_USER_UNKNOWN");
                return PamResultCode::PAM_USER_UNKNOWN;
            }
        }
    };

    let expiration_date = shadow
        .epoch_expire_date
        .map(|expire| OffsetDateTime::UNIX_EPOCH + time::Duration::days(expire));

    if let Some(expire) = expiration_date {
        if current_time >= expire {
            debug!("PamResultCode::PAM_ACCT_EXPIRED");
            return PamResultCode::PAM_ACCT_EXPIRED;
        }
    };

    // All checks passed! We can now proceed to authenticate the account.
    let mut stacked_authtok = if opts.use_first_pass {
        match pamh.authtok() {
            Ok(authtok) => authtok,
            Err(err) => return err,
        }
    } else {
        None
    };

    let mut authtok = None;
    std::mem::swap(&mut authtok, &mut stacked_authtok);

    let cred = if let Some(cred) = authtok {
        cred
    } else {
        match pamh.prompt_for_password() {
            Ok(Some(cred)) => cred,
            Ok(None) => return PamResultCode::PAM_CRED_INSUFFICIENT,
            Err(err) => return err,
        }
    };

    if shadow.password.check_pw(cred.as_str()) {
        PamResultCode::PAM_SUCCESS
    } else {
        PamResultCode::PAM_AUTH_ERR
    }
}

pub fn sm_authenticate<P: PamHandler>(
    pamh: &P,
    opts: &ModuleOptions,
    req_opt: RequestOptions,
    current_time: OffsetDateTime,
) -> PamResultCode {
    match req_opt.connect_to_daemon() {
        Source::Daemon(daemon_client) => {
            sm_authenticate_connected(pamh, opts, current_time, daemon_client)
        }
        Source::Fallback { users, shadow } => {
            sm_authenticate_fallback(pamh, opts, current_time, users, shadow)
        }
    }
}

pub fn acct_mgmt<P: PamHandler>(
    pamh: &P,
    opts: &ModuleOptions,
    req_opt: RequestOptions,
    current_time: OffsetDateTime,
) -> PamResultCode {
    let account_id = match pamh.account_id() {
        Ok(acc) => acc,
        Err(err) => return err,
    };

    match req_opt.connect_to_daemon() {
        Source::Daemon(mut daemon_client) => {
            let req = ClientRequest::PamAccountAllowed(account_id);
            match daemon_client.call_and_wait(&req, None) {
                Ok(r) => match r {
                    ClientResponse::PamStatus(Some(true)) => {
                        debug!("PamResultCode::PAM_SUCCESS");
                        PamResultCode::PAM_SUCCESS
                    }
                    ClientResponse::PamStatus(Some(false)) => {
                        debug!("PamResultCode::PAM_AUTH_ERR");
                        PamResultCode::PAM_AUTH_ERR
                    }
                    ClientResponse::PamStatus(None) => {
                        if opts.ignore_unknown_user {
                            debug!("PamResultCode::PAM_IGNORE");
                            PamResultCode::PAM_IGNORE
                        } else {
                            debug!("PamResultCode::PAM_USER_UNKNOWN");
                            PamResultCode::PAM_USER_UNKNOWN
                        }
                    }
                    _ => {
                        // unexpected response.
                        error!(err = ?r, "PAM_IGNORE, unexpected resolver response");
                        PamResultCode::PAM_IGNORE
                    }
                },
                Err(e) => {
                    error!(err = ?e, "PamResultCode::PAM_IGNORE");
                    PamResultCode::PAM_IGNORE
                }
            }
        }
        Source::Fallback { users, shadow } => {
            let user = users.into_iter().find(|etcuser| etcuser.name == account_id);

            let shadow = shadow
                .into_iter()
                .find(|etcshadow| etcshadow.name == account_id);

            let (_user, shadow) = match (user, shadow) {
                (Some(user), Some(shadow)) => (user, shadow),
                _ => {
                    if opts.ignore_unknown_user {
                        debug!("PamResultCode::PAM_IGNORE");
                        return PamResultCode::PAM_IGNORE;
                    } else {
                        debug!("PamResultCode::PAM_USER_UNKNOWN");
                        return PamResultCode::PAM_USER_UNKNOWN;
                    }
                }
            };

            let expiration_date = shadow
                .epoch_expire_date
                .map(|expire| OffsetDateTime::UNIX_EPOCH + time::Duration::days(expire));

            if let Some(expire) = expiration_date {
                if current_time >= expire {
                    debug!("PamResultCode::PAM_ACCT_EXPIRED");
                    return PamResultCode::PAM_ACCT_EXPIRED;
                }
            };

            // All checks passed!

            debug!("PAM_SUCCESS");
            PamResultCode::PAM_SUCCESS
        }
    }
}

pub fn sm_open_session<P: PamHandler>(
    pamh: &P,
    _opts: &ModuleOptions,
    req_opt: RequestOptions,
) -> PamResultCode {
    let account_id = match pamh.account_id() {
        Ok(acc) => acc,
        Err(err) => return err,
    };

    match req_opt.connect_to_daemon() {
        Source::Daemon(mut daemon_client) => {
            let req = ClientRequest::PamAccountBeginSession(account_id);

            match daemon_client.call_and_wait(&req, None) {
                Ok(ClientResponse::Ok) => {
                    debug!("PAM_SUCCESS");
                    PamResultCode::PAM_SUCCESS
                }
                other => {
                    debug!(err = ?other, "PAM_IGNORE");
                    PamResultCode::PAM_IGNORE
                }
            }
        }
        Source::Fallback {
            users: _,
            shadow: _,
        } => {
            debug!("PAM_SUCCESS");
            PamResultCode::PAM_SUCCESS
        }
    }
}

pub fn sm_close_session<P: PamHandler>(_pamh: &P, _opts: &ModuleOptions) -> PamResultCode {
    PamResultCode::PAM_SUCCESS
}

pub fn sm_chauthtok<P: PamHandler>(_pamh: &P, _opts: &ModuleOptions) -> PamResultCode {
    PamResultCode::PAM_IGNORE
}

pub fn sm_setcred<P: PamHandler>(_pamh: &P, _opts: &ModuleOptions) -> PamResultCode {
    PamResultCode::PAM_SUCCESS
}