initial commit

- login works
- basic documentation
This commit is contained in:
2026-05-09 06:28:09 +02:00
commit d2a2baebc8
16 changed files with 2524 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
use std::ffi::CStr;
pub trait SliceExt {
fn split_once_ch(&self, ch: u8) -> Option<(&[u8], &[u8])>;
}
impl SliceExt for [u8] {
fn split_once_ch(&self, ch: u8) -> Option<(&[u8], &[u8])> {
let (idx, _) = self.iter().enumerate().find(|(_, b)| **b == ch)?;
// SAFETY: idx is IN-OF-BOUNDS index of the slice
unsafe { Some((self.get_unchecked(0..idx), self.get_unchecked((idx + 1)..))) }
}
}
pub trait CStrExt {
fn split_ch(&self, ch: u8) -> Option<(&[u8], &CStr)>;
}
impl CStrExt for CStr {
fn split_ch(&self, ch: u8) -> Option<(&[u8], &CStr)> {
let self_slice = self.to_bytes_with_nul();
self_slice.split_once_ch(ch).map(|(k, v)| {
// # SAFETY split originated in a slice with final null byte, hence second split will be
// null terminated
(k, unsafe { Self::from_bytes_with_nul_unchecked(v) })
})
}
}
+21
View File
@@ -0,0 +1,21 @@
use std::fmt::Display;
use serde::Deserialize;
#[derive(Debug, Deserialize, thiserror::Error)]
pub struct AuthError {
error: String,
error_description: Option<String>,
}
impl Display for AuthError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let error = &self.error;
if let Some(ref error_description) = self.error_description {
writeln!(f, "authentication type '{error}' with message '{error_description:?}'")
} else {
writeln!(f, "authentication type '{error}'")
}
}
}
+95
View File
@@ -0,0 +1,95 @@
use std::{
ffi::OsStr,
fs::File,
io::{self},
};
use curl::easy::{Easy, List};
use serde::Deserialize;
mod api;
#[derive(Debug, Deserialize)]
pub struct KeycloakAPI {
base_url: String,
default_realm: String,
client_id: String,
client_secret: String,
}
#[derive(Debug, thiserror::Error)]
pub enum LoadError {
#[error("opening configuration: {0}")]
OpenConfig(#[from] io::Error),
#[error("parsing configuration: {0}")]
ParseConfig(#[from] serde_json::Error),
}
#[derive(Debug, thiserror::Error)]
pub enum LoginError {
#[error("on POST request: {0}")]
Fetch(#[from] curl::Error),
#[error("unexpected API response: {0}")]
InvalidAPIResponse(#[from] serde_json::Error),
#[error("from the API: {0}")]
InvalidLogin(#[from] api::AuthError),
}
fn curl_request(uri: &str, body: &[u8], header: &str) -> Result<(u32, Vec<u8>), curl::Error> {
let mut easy = Easy::new();
easy.post(true)?;
let mut headers = List::new();
headers.append(header)?;
easy.http_headers(headers)?;
easy.url(uri)?;
easy.post_fields_copy(body)?;
let mut response_data = Vec::new();
{
let mut transfer = easy.transfer();
transfer.write_function(|data| {
response_data.extend_from_slice(data);
Ok(data.len())
})?;
transfer.perform()?;
}
Ok((easy.response_code()?, response_data))
}
impl KeycloakAPI {
pub fn load_from_configuration(cfg: &OsStr) -> Result<Self, LoadError> {
let f = File::open(cfg)?;
Ok(serde_json::from_reader(f)?)
}
pub fn check_credentials(&self, username: &str, password: &str) -> Result<(), LoginError> {
let body = format!(
"grant_type=password&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&username={USERNAME}&password={PASSWORD}",
CLIENT_ID = urlencoding::encode(&self.client_id),
CLIENT_SECRET = urlencoding::encode(&self.client_secret),
USERNAME = urlencoding::encode(username),
PASSWORD = urlencoding::encode(password),
);
let (status_code, body) = curl_request(
&format!(
"{}/realms/{}/protocol/openid-connect/token",
self.base_url, self.default_realm,
),
body.as_bytes(),
"Content-Type: application/x-www-form-urlencoded",
)?;
if status_code == 200 {
Ok(())
} else {
Err(LoginError::InvalidLogin(serde_json::from_slice(&body)?))
}
}
}
+118
View File
@@ -0,0 +1,118 @@
//! Privileged PAM module.
use std::{
ffi::{CStr, OsStr},
os::unix::ffi::OsStrExt as _,
};
use nonstick::{ErrorCode, ModuleClient, PamModule, pam_export};
use keycloak::KeycloakAPI;
use crate::ext::CStrExt as _;
pub mod ext;
pub mod keycloak;
pub const DEFAULT_CONFIGURATION_PATH: &CStr = c"/etc/keycloak-pam.json";
struct KeycloakPAM;
pam_export!(KeycloakPAM);
/// # Arguments
///
/// - `config=`, optional, accepts a path to load json configuration from, defaults to [`DEFAULT_CONFIGURATION_PATH`]
/// - `debug`, optional, flag, ignores the PAM policy about silence and prints regardless
pub struct Args<'a> {
config: &'a CStr,
debug: bool,
}
impl<'a> Args<'a> {
fn parse(args: &[&'a CStr]) -> Self {
let mut parsed_args = Args {
config: DEFAULT_CONFIGURATION_PATH,
debug: false,
};
for arg in args {
if arg == &c"debug" {
parsed_args.debug = true;
}
if let Some((b"config", path)) = arg.split_ch(b'=') {
parsed_args.config = path;
}
}
parsed_args
}
}
impl<M: ModuleClient> PamModule<M> for KeycloakPAM {
fn authenticate(
handle: &mut M,
args: Vec<&CStr>,
flags: nonstick::AuthnFlags,
) -> nonstick::Result<()> {
fn osstr_to_str(p: &OsStr) -> nonstick::Result<&str> {
p.to_str().ok_or(ErrorCode::AuthInfoUnavailable)
}
let args = Args::parse(&args);
let username = handle.username(None)?;
let username = osstr_to_str(&username)?;
let password = handle.authtok(None)?;
let password = osstr_to_str(&password)?;
let no_silent_flag = (flags & nonstick::AuthnFlags::SILENT).is_empty();
let can_print = no_silent_flag || args.debug;
let api_client =
match KeycloakAPI::load_from_configuration(OsStr::from_bytes(args.config.to_bytes())) {
Ok(v) => v,
Err(error) => {
if can_print {
eprintln!("{error}");
}
return Err(ErrorCode::ServiceError);
}
};
match api_client.check_credentials(username, password) {
Ok(()) => Ok(()),
Err(error) => {
if can_print {
eprintln!("{error}");
}
let err = match error {
keycloak::LoginError::Fetch(_)
| keycloak::LoginError::InvalidAPIResponse(_) => ErrorCode::ServiceError,
keycloak::LoginError::InvalidLogin(_) => ErrorCode::CredentialsError,
};
Err(err)
}
}
}
// fn account_management(
// handle: &mut M,
// args: Vec<&std::ffi::CStr>,
// flags: nonstick::AuthnFlags,
// ) -> nonstick::Result<()> {
// todo!()
// }
fn change_authtok(
handle: &mut M,
args: Vec<&std::ffi::CStr>,
action: nonstick::AuthtokAction,
flags: nonstick::AuthtokFlags,
) -> nonstick::Result<()> {
_ = (handle, args, action, flags);
todo!()
}
}