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

use cap_std::fs::{Dir, OpenOptions};
use pam::constants::{PamFlag, PamResultCode};
use pam::module::{PamHandle, PamHooks};
use std::ffi::CStr;
use std::fmt::{Display, Write as _};
use std::io::{ErrorKind, Write};
use std::path::Path;
use std::process;

fn create_and_open_dir<P: AsRef<Path> + Copy>(
    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
    }
}

trait MaxDisplayLength: Display {
    const MAX_DISPLAY_LENGTH: usize;
}
impl MaxDisplayLength for u32 {
    const MAX_DISPLAY_LENGTH: usize = u32::MAX.ilog10() as usize + 1;
}

fn safe_to_string<T: MaxDisplayLength>(v: T) -> Result<String, SessionError> {
    let mut buf = String::new();
    buf.try_reserve_exact(T::MAX_DISPLAY_LENGTH)
        .or(Err(SessionError))?;
    write!(buf, "{v}").unwrap();
    Ok(buf)
}

fn open_session(h: &mut PamHandle, mountpoint: &str) -> Result<(), SessionError> {
    let user = h.get_user(None).or(Err(SessionError))?;
    let user = users::get_user_by_name(&user).ok_or(SessionError)?;
    let uid = safe_to_string(user.uid())?;
    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 = safe_to_string(process::id())?;
    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";

struct PAMUserCG;
pam::pam_hooks!(PAMUserCG);

impl PamHooks for PAMUserCG {
    fn sm_open_session(
        h: &mut PamHandle,
        _args: Vec<&CStr>,
        _flags: PamFlag,
    ) -> PamResultCode {
        match open_session(h, CG_MOUNT) {
            Ok(()) => PamResultCode::PAM_SUCCESS,
            Err(SessionError) => PamResultCode::PAM_SESSION_ERR,
        }
    }
}