summaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: 42a9c1bc2d1940c27ca99ba0a31986f589b82f13 (plain)
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
// Copyright (C) 2023  Tomasz Kramkowski <tomasz@kramkow.ski>
// SPDX-License-Identifier: MIT

mod pam;
mod passwd;
mod syslog;

use cap_std::fs::{Dir, OpenOptions};
use pam::PAMHandle;
use std::ffi::{c_char, c_int, CStr, CString};
use std::io::{ErrorKind, Write};
use std::panic;
use std::path::Path;
use std::process;
use syslog::{Facility, Level, Priority};

fn create_and_open_dir<P: AsRef<Path> + ?Sized>(
    d: &Dir,
    path: &P,
) -> std::io::Result<Dir> {
    if let Err(e) = d.create_dir(path) {
        if e.kind() != ErrorKind::AlreadyExists {
            return Err(e);
        }
    }
    d.open_dir(path)
}

struct SessionError;

impl From<std::io::Error> for SessionError {
    fn from(_: std::io::Error) -> Self {
        SessionError
    }
}

const PRIORITY: Priority = Priority {
    level: Level::Debug,
    facility: Facility::Auth,
};

fn open_session(h: &PAMHandle, mountpoint: &str) -> Result<(), SessionError> {
    let user = match h.get_user::<CStr>(None) {
        Ok(user) => user,
        Err(e) => {
            if let Ok(message) =
                CString::new(format!("Failure to get username: {e}"))
            {
                h.syslog(PRIORITY, &message);
            }
            return Err(SessionError);
        }
    };
    let uid = match passwd::get_uid_by_name(&user) {
        Some(uid) => uid.to_string(),
        None => {
            if let Ok(message) =
                CString::new(format!("Failure to map user {user:?} to passwd entry"))
            {
                h.syslog(PRIORITY, &message);
            }
            return Err(SessionError);
        }
    };
    let d = Dir::open_ambient_dir(mountpoint, cap_std::ambient_authority())?;
    let d = create_and_open_dir(&d, "user")?;
    let d = create_and_open_dir(&d, &uid)?;
    let d = create_and_open_dir(&d, "leaf")?;
    let pid = process::id().to_string();
    let mut options = OpenOptions::new();
    options.write(true);
    let mut procs = d.open_with("cgroup.procs", &options)?;
    procs.write_all(pid.as_bytes())?;
    Ok(())
}

const CG_MOUNT: &str = "/sys/fs/cgroup";

#[no_mangle]
pub extern "C" fn pam_sm_open_session(
    h: &mut PAMHandle,
    _flags: c_int,
    _argc: c_int,
    _argv: *const *const c_char,
) -> c_int {
    match panic::catch_unwind(|| open_session(h, CG_MOUNT)) {
        Ok(Ok(())) => pam::SUCCESS,
        _ => pam::SESSION_ERR,
    }
}

#[no_mangle]
pub extern "C" fn pam_sm_close_session(
    _h: &mut PAMHandle,
    _flags: c_int,
    _argc: c_int,
    _argv: *const *const c_char,
) -> c_int {
    pam::IGNORE
}