Compare commits

...

12 commits

Author SHA1 Message Date
Merlijn 6ffa616bb2
Merge 3077d86aa1 into aee9ed05f3 2025-04-08 19:02:32 +08:00
Firstyear aee9ed05f3
Update fs4 and improve klock handling () 2025-04-08 05:04:26 +00:00
James Hodgkinson 5458b13398
Less footguns () 2025-04-08 04:48:53 +00:00
Firstyear 94b6287e27
Unify unix config parser ()
* Unify unix config parser
* Document the various structs
* Compiler Update
2025-04-08 14:21:26 +10:00
dependabot[bot] b6813a11d3
Bump openssl from 0.10.71 to 0.10.72 in the cargo group ()
Bumps the cargo group with 1 update: [openssl](https://github.com/sfackler/rust-openssl).


Updates `openssl` from 0.10.71 to 0.10.72
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-v0.10.71...openssl-v0.10.72)

---
updated-dependencies:
- dependency-name: openssl
  dependency-version: 0.10.72
  dependency-type: direct:production
  dependency-group: cargo
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-08 01:31:20 +00:00
ToxicMushroom 3077d86aa1
final fixes 2025-04-06 04:22:56 +02:00
ToxicMushroom 9b3f814b67
cargo fmt 2025-04-06 01:29:26 +02:00
ToxicMushroom a708d8c938
Working diff viewer 2025-04-06 01:25:35 +02:00
ToxicMushroom 339a20947a
Fixup email submission, tested 2025-04-05 17:22:07 +02:00
ToxicMushroom bb0e759134 Add primary email selection, update email add button. Use scim. 2025-04-05 12:40:33 +02:00
ToxicMushroom 645f13b285 patch up rebase 2025-04-05 12:40:33 +02:00
ToxicMushroom 245e68c5ba - Form validation
- Editable emails
- Basic profile updating
2025-04-05 12:40:33 +02:00
39 changed files with 1264 additions and 697 deletions

32
Cargo.lock generated
View file

@ -391,6 +391,7 @@ dependencies = [
"multer",
"pin-project-lite",
"serde",
"serde_html_form",
"tower 0.5.2",
"tower-layer",
"tower-service",
@ -1600,12 +1601,12 @@ dependencies = [
[[package]]
name = "fs4"
version = "0.12.0"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c29c30684418547d476f0b48e84f4821639119c483b1eccd566c8cd0cd05f521"
checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
dependencies = [
"rustix 0.38.44",
"windows-sys 0.52.0",
"rustix 1.0.3",
"windows-sys 0.59.0",
]
[[package]]
@ -3064,6 +3065,8 @@ dependencies = [
"futures",
"kanidm_build_profiles",
"kanidm_proto",
"kanidm_utils_users",
"selinux",
"serde",
"serde_json",
"serde_with",
@ -3955,9 +3958,9 @@ checksum = "c2806eaa3524762875e21c3dcd057bc4b7bfa01ce4da8d46be1cd43649e1cc6b"
[[package]]
name = "openssl"
version = "0.10.71"
version = "0.10.72"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e14130c6a98cd258fdcb0fb6d744152343ff729cbfcb28c656a9d12b999fbcd"
checksum = "fedfea7d58a1f73118430a55da6a286e7b044961736ce96a16a17068ea25e5da"
dependencies = [
"bitflags 2.9.0",
"cfg-if",
@ -3987,9 +3990,9 @@ checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"
[[package]]
name = "openssl-sys"
version = "0.9.106"
version = "0.9.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bb61ea9811cc39e3c2069f40b8b8e2e70d8569b361f879786cc7ed48b777cdd"
checksum = "8288979acd84749c744a9014b4382d42b8f7b2592847b5afb2ed29e5d16ede07"
dependencies = [
"cc",
"libc",
@ -5136,6 +5139,19 @@ dependencies = [
"syn 2.0.100",
]
[[package]]
name = "serde_html_form"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d2de91cf02bbc07cde38891769ccd5d4f073d22a40683aa4bc7a95781aaa2c4"
dependencies = [
"form_urlencoded",
"indexmap 2.8.0",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "serde_json"
version = "1.0.140"

View file

@ -173,7 +173,7 @@ dhat = "0.3.3"
dyn-clone = "^1.0.17"
fernet = "^0.2.1"
filetime = "^0.2.24"
fs4 = "^0.12.0"
fs4 = "^0.13.0"
futures = "^0.3.31"
futures-util = { version = "^0.3.30", features = ["sink"] }
gix = { version = "0.64.0", default-features = false }
@ -210,7 +210,7 @@ notify-debouncer-full = { version = "0.5" }
num_enum = "^0.5.11"
oauth2_ext = { version = "^4.4.2", package = "oauth2", default-features = false }
openssl-sys = "^0.9"
openssl = "^0.10.70"
openssl = "^0.10.72"
opentelemetry = { version = "0.27.0" }
opentelemetry_api = { version = "0.27.0", features = ["logs", "metrics"] }

View file

@ -8,7 +8,7 @@ const MD5_TRANSPOSE: &[u8] = b"\x0c\x06\x00\x0d\x07\x01\x0e\x08\x02\x0f\x09\x03\
const CRYPT_HASH64: &[u8] = b"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
pub fn md5_sha2_hash64_encode(bs: &[u8]) -> String {
let ngroups = (bs.len() + 2) / 3;
let ngroups = bs.len().div_ceil(3);
let mut out = String::with_capacity(ngroups * 4);
for g in 0..ngroups {
let mut g_idx = g * 3;

View file

@ -71,7 +71,7 @@ pub enum ScimSchema {
}
#[serde_as]
#[derive(Deserialize, Serialize, Debug, Clone, ToSchema)]
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, ToSchema)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ScimMail {
#[serde(default)]

View file

@ -21,6 +21,8 @@ ${SUDOCMD} apt-get update &&
cmake \
build-essential \
jq \
lld \
clang \
tpm-udev
if [ -z "${PACKAGING}" ]; then
@ -73,10 +75,6 @@ if [ -z "$(which cargo)" ]; then
ERROR=1
fi
if [ $ERROR -eq 0 ] && [ -z "$(which cross)" ]; then
echo "You don't have cross installed! Installing it now..."
cargo install -f cross
fi
if [ $ERROR -eq 0 ] && [ -z "$(which cargo-deb)" ]; then
echo "You don't have cargo-deb installed! Installing it now..."
cargo install -f cargo-deb

View file

@ -24,7 +24,7 @@ askama = { workspace = true, features = ["with-axum"] }
askama_axum = { workspace = true }
axum = { workspace = true }
axum-htmx = { workspace = true }
axum-extra = { version = "0.9.6", features = ["cookie"] }
axum-extra = { version = "0.9.6", features = ["cookie", "form"] }
axum-macros = "0.4.2"
axum-server = { version = "0.7.1", default-features = false }
bytes = { workspace = true }

View file

@ -3,7 +3,7 @@ use axum::routing::get;
use axum::Router;
use axum_htmx::HxRequestGuardLayer;
mod persons;
pub(crate) mod persons;
pub fn admin_router() -> Router<ServerState> {
let unguarded_router = Router::new()

View file

@ -1,3 +1,4 @@
use crate::https::errors::WebError;
use crate::https::extractors::{DomainInfo, VerifiedClientInformation};
use crate::https::middleware::KOpId;
use crate::https::views::errors::HtmxError;
@ -7,17 +8,15 @@ use crate::https::ServerState;
use askama::Template;
use axum::extract::{Path, State};
use axum::http::Uri;
use axum::response::{ErrorResponse, IntoResponse, Response};
use axum::response::{IntoResponse, Response};
use axum::Extension;
use axum_htmx::{HxPushUrl, HxRequest};
use futures_util::TryFutureExt;
use kanidm_proto::attribute::Attribute;
use kanidm_proto::internal::OperationError;
use kanidm_proto::scim_v1::client::ScimFilter;
use kanidm_proto::scim_v1::server::{ScimEffectiveAccess, ScimEntryKanidm, ScimPerson};
use kanidm_proto::scim_v1::ScimEntryGetQuery;
use kanidmd_lib::constants::EntryClass;
use kanidmd_lib::idm::server::DomainInfoRead;
use kanidmd_lib::idm::ClientAuthInfo;
use std::str::FromStr;
use uuid::Uuid;
@ -70,7 +69,7 @@ pub(crate) async fn view_person_view_get(
DomainInfo(domain_info): DomainInfo,
) -> axum::response::Result<Response> {
let (person, scim_effective_access) =
get_person_info(uuid, state, &kopid, client_auth_info, domain_info.clone()).await?;
get_person_info(uuid, state, &kopid, client_auth_info).await?;
let person_partial = PersonViewPartial {
person,
scim_effective_access,
@ -101,7 +100,7 @@ pub(crate) async fn view_persons_get(
DomainInfo(domain_info): DomainInfo,
VerifiedClientInformation(client_auth_info): VerifiedClientInformation,
) -> axum::response::Result<Response> {
let persons = get_persons_info(state, &kopid, client_auth_info, domain_info.clone()).await?;
let persons = get_persons_info(state, &kopid, client_auth_info).await?;
let persons_partial = PersonsPartialView { persons };
let push_url = HxPushUrl(Uri::from_static("/ui/admin/persons"));
@ -119,13 +118,12 @@ pub(crate) async fn view_persons_get(
})
}
async fn get_person_info(
pub async fn get_person_info(
uuid: Uuid,
state: ServerState,
kopid: &KOpId,
client_auth_info: ClientAuthInfo,
domain_info: DomainInfoRead,
) -> Result<(ScimPerson, ScimEffectiveAccess), ErrorResponse> {
) -> Result<(ScimPerson, ScimEffectiveAccess), WebError> {
let scim_entry: ScimEntryKanidm = state
.qe_r_ref
.scim_entry_id_get(
@ -138,13 +136,12 @@ async fn get_person_info(
ext_access_check: true,
},
)
.map_err(|op_err| HtmxError::new(kopid, op_err, domain_info.clone()))
.await?;
if let Some(personinfo_info) = scimentry_into_personinfo(scim_entry) {
Ok(personinfo_info)
} else {
Err(HtmxError::new(kopid, OperationError::InvalidState, domain_info.clone()).into())
Err(WebError::from(OperationError::InvalidState))
}
}
@ -152,8 +149,7 @@ async fn get_persons_info(
state: ServerState,
kopid: &KOpId,
client_auth_info: ClientAuthInfo,
domain_info: DomainInfoRead,
) -> Result<Vec<(ScimPerson, ScimEffectiveAccess)>, ErrorResponse> {
) -> Result<Vec<(ScimPerson, ScimEffectiveAccess)>, WebError> {
let filter = ScimFilter::Equal(Attribute::Class.into(), EntryClass::Person.into());
let base: Vec<ScimEntryKanidm> = state
@ -167,7 +163,6 @@ async fn get_persons_info(
ext_access_check: true,
},
)
.map_err(|op_err| HtmxError::new(kopid, op_err, domain_info.clone()))
.await?;
// TODO: inefficient to sort here

View file

@ -9,17 +9,17 @@ pub(crate) enum ProfileMenuItems {
UnixPassword,
}
pub(crate) enum UiMessage {
UnlockEdit,
}
impl std::fmt::Display for UiMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UiMessage::UnlockEdit => write!(f, "Unlock Edit 🔒"),
}
}
}
// pub(crate) enum UiMessage {
// UnlockEdit,
// }
//
// impl std::fmt::Display for UiMessage {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// match self {
// UiMessage::UnlockEdit => write!(f, "Unlock Edit 🔒"),
// }
// }
// }
pub(crate) enum Urls {
Apps,

View file

@ -56,6 +56,7 @@ pub fn view_router() -> Router<ServerState> {
.route("/reset", get(reset::view_reset_get))
.route("/update_credentials", get(reset::view_self_reset_get))
.route("/profile", get(profile::view_profile_get))
.route("/profile/diff", get(profile::view_profile_get))
.route("/profile/unlock", get(profile::view_profile_unlock_get))
.route("/logout", get(login::view_logout_get))
.route("/oauth2", get(oauth2::view_index_get));
@ -129,6 +130,18 @@ pub fn view_router() -> Router<ServerState> {
)
.route("/api/cu_cancel", post(reset::cancel_cred_update))
.route("/api/cu_commit", post(reset::commit))
.route(
"/api/user_settings/add_email",
get(profile::view_new_email_entry_partial),
)
.route(
"/api/user_settings/edit_profile",
post(profile::view_profile_diff_start_save_post),
)
.route(
"/api/user_settings/confirm_profile",
post(profile::view_profile_diff_confirm_save_post),
)
.layer(HxRequestGuardLayer::new("/ui"));
let admin_router = admin_router();

View file

@ -1,18 +1,34 @@
use super::constants::{ProfileMenuItems, Urls};
use super::errors::HtmxError;
use super::login::{LoginDisplayCtx, Reauth, ReauthPurpose};
use super::navbar::NavbarCtx;
use crate::https::errors::WebError;
use crate::https::extractors::{DomainInfo, VerifiedClientInformation};
use crate::https::middleware::KOpId;
use crate::https::ServerState;
use askama::Template;
use axum::extract::State;
use axum::response::Response;
use askama_axum::IntoResponse;
use axum::extract::{Query, State};
use axum::http::Uri;
use axum::response::{Redirect, Response};
use axum::Extension;
use axum_extra::extract::cookie::CookieJar;
use axum_extra::extract::Form;
use axum_htmx::{HxEvent, HxPushUrl, HxResponseTrigger};
use futures_util::TryFutureExt;
use kanidm_proto::attribute::Attribute;
use kanidm_proto::constants::{ATTR_DISPLAYNAME, ATTR_MAIL, ATTR_NAME};
use kanidm_proto::internal::UserAuthToken;
use super::constants::{ProfileMenuItems, UiMessage, Urls};
use super::errors::HtmxError;
use super::login::{LoginDisplayCtx, Reauth, ReauthPurpose};
use super::navbar::NavbarCtx;
use kanidm_proto::scim_v1::server::{ScimEffectiveAccess, ScimPerson};
use kanidm_proto::scim_v1::ScimMail;
use kanidmd_lib::filter::{f_id, Filter};
use kanidmd_lib::prelude::f_and;
use kanidmd_lib::prelude::FC;
use serde::Deserialize;
use serde::Serialize;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
#[derive(Template)]
#[template(path = "user_settings.html")]
@ -26,9 +42,68 @@ pub(crate) struct ProfileView {
struct ProfilePartialView {
menu_active_item: ProfileMenuItems,
can_rw: bool,
person: ScimPerson,
scim_effective_access: ScimEffectiveAccess,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct SaveProfileQuery {
#[serde(rename = "name")]
account_name: String,
#[serde(rename = "displayname")]
display_name: String,
#[serde(rename = "email_index")]
emails_indexes: Vec<u16>,
#[serde(rename = "emails[]")]
emails: Vec<String>,
// radio buttons are used to pick a primary index, remove causes holes, map back into [emails] using [emails_indexes]
primary_email_index: u16,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct CommitSaveProfileQuery {
#[serde(rename = "account_name")]
account_name: Option<String>,
#[serde(rename = "display_name")]
display_name: Option<String>,
#[serde(rename = "emails[]")]
emails: Vec<String>,
#[serde(rename = "new_primary_mail")]
new_primary_mail: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct ProfileAttributes {
account_name: String,
display_name: String,
email: Option<String>,
emails: Vec<ScimMail>,
}
#[derive(Template, Clone)]
#[template(path = "user_settings/profile_changes_partial.html")]
struct ProfileChangesPartialView {
menu_active_item: ProfileMenuItems,
can_rw: bool,
person: ScimPerson,
primary_mail: Option<String>,
new_attrs: ProfileAttributes,
new_primary_mail: Option<String>,
emails_are_same: bool,
}
#[derive(Template, Clone)]
#[template(path = "user_settings/form_email_entry_partial.html")]
pub(crate) struct FormEmailEntryListPartial {
can_edit: bool,
value: String,
primary: bool,
index: u16,
}
impl Display for ProfileAttributes {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
pub(crate) async fn view_profile_get(
@ -39,7 +114,16 @@ pub(crate) async fn view_profile_get(
) -> Result<ProfileView, WebError> {
let uat: UserAuthToken = state
.qe_r_ref
.handle_whoami_uat(client_auth_info, kopid.eventid)
.handle_whoami_uat(client_auth_info.clone(), kopid.eventid)
.await?;
let (scim_person, scim_effective_access) =
crate::https::views::admin::persons::get_person_info(
uat.uuid,
state,
&kopid,
client_auth_info.clone(),
)
.await?;
let time = time::OffsetDateTime::now_utc() + time::Duration::new(60, 0);
@ -52,13 +136,210 @@ pub(crate) async fn view_profile_get(
profile_partial: ProfilePartialView {
menu_active_item: ProfileMenuItems::UserProfile,
can_rw,
account_name: uat.name().to_string(),
display_name: uat.displayname.clone(),
email: uat.mail_primary.clone(),
person: scim_person,
scim_effective_access,
},
})
}
pub(crate) async fn view_profile_diff_start_save_post(
State(state): State<ServerState>,
Extension(kopid): Extension<KOpId>,
VerifiedClientInformation(client_auth_info): VerifiedClientInformation,
DomainInfo(domain_info): DomainInfo,
// Form must be the last parameter because it consumes the request body
Form(query): Form<SaveProfileQuery>,
) -> axum::response::Result<Response> {
let uat: UserAuthToken = state
.qe_r_ref
.handle_whoami_uat(client_auth_info.clone(), kopid.eventid)
.map_err(|op_err| HtmxError::new(&kopid, op_err, domain_info.clone()))
.await?;
let time = time::OffsetDateTime::now_utc() + time::Duration::new(60, 0);
let can_rw = uat.purpose_readwrite_active(time);
// TODO: A bit overkill to request scimEffectiveAccess here.
let (scim_person, _) = crate::https::views::admin::persons::get_person_info(
uat.uuid,
state,
&kopid,
client_auth_info.clone(),
)
.await?;
let primary_index = query
.emails_indexes
.iter()
.position(|ei| ei == &query.primary_email_index)
.unwrap_or(0);
let new_mails = query
.emails
.iter()
.enumerate()
.map(|(ei, email)| ScimMail {
primary: ei == primary_index,
value: email.to_string(),
})
.collect();
let old_primary_mail = scim_person
.mails
.iter()
.find(|sm| sm.primary)
.map(|sm| sm.value.clone());
let emails_are_same = scim_person.mails == new_mails;
let profile_view = ProfileChangesPartialView {
menu_active_item: ProfileMenuItems::UserProfile,
can_rw,
person: scim_person,
primary_mail: old_primary_mail,
new_attrs: ProfileAttributes {
account_name: query.account_name,
display_name: query.display_name,
emails: new_mails,
},
emails_are_same,
new_primary_mail: query.emails.get(primary_index).cloned(),
};
Ok((
HxPushUrl(Uri::from_static("/ui/profile/diff")),
profile_view,
)
.into_response())
}
pub(crate) async fn view_profile_diff_confirm_save_post(
State(state): State<ServerState>,
Extension(kopid): Extension<KOpId>,
VerifiedClientInformation(client_auth_info): VerifiedClientInformation,
DomainInfo(domain_info): DomainInfo,
// Form must be the last parameter because it consumes the request body
Form(query): Form<CommitSaveProfileQuery>,
) -> axum::response::Result<Response> {
let uat: UserAuthToken = state
.qe_r_ref
.handle_whoami_uat(client_auth_info.clone(), kopid.eventid)
.map_err(|op_err| HtmxError::new(&kopid, op_err, domain_info.clone()))
.await?;
let filter = filter_all!(f_and!([f_id(uat.uuid.to_string().as_str())]));
if let Some(account_name) = query.account_name {
state
.qe_w_ref
.handle_setattribute(
client_auth_info.clone(),
uat.uuid.to_string(),
ATTR_NAME.to_string(),
vec![account_name],
filter.clone(),
kopid.eventid,
)
.map_err(|op_err| HtmxError::new(&kopid, op_err, domain_info.clone()))
.await?;
}
if let Some(display_name) = query.display_name {
state
.qe_w_ref
.handle_setattribute(
client_auth_info.clone(),
uat.uuid.to_string(),
ATTR_DISPLAYNAME.to_string(),
vec![display_name],
filter.clone(),
kopid.eventid,
)
.map_err(|op_err| HtmxError::new(&kopid, op_err, domain_info.clone()))
.await?;
}
let mut emails = query.emails;
if let Some(primary) = query.new_primary_mail {
emails.insert(0, primary);
}
state
.qe_w_ref
.handle_setattribute(
client_auth_info.clone(),
uat.uuid.to_string(),
ATTR_MAIL.to_string(),
emails,
filter.clone(),
kopid.eventid,
)
.map_err(|op_err| HtmxError::new(&kopid, op_err, domain_info.clone()))
.await?;
// TODO: These are normally not permitted, user should be prevented from changing non modifiable fields in the UI though
// state
// .qe_w_ref
// .handle_setattribute(
// client_auth_info.clone(),
// uat.uuid.to_string(),
// ATTR_EMAIL.to_string(),
// vec![new_attrs.email.unwrap_or("".to_string())],
// filter.clone(),
// kopid.eventid,
// )
// .map_err(|op_err| HtmxError::new(&kopid, op_err))
// .await?;
//
// state
// .qe_w_ref
// .handle_setattribute(
// client_auth_info.clone(),
// uat.uuid.to_string(),
// ATTR_NAME.to_string(),
// vec![new_attrs.account_name],
// filter.clone(),
// kopid.eventid,
// )
// .map_err(|op_err| HtmxError::new(&kopid, op_err))
// .await?;
// TODO: Calling this here returns the old attributes
match view_profile_get(
State(state),
Extension(kopid),
VerifiedClientInformation(client_auth_info),
DomainInfo(domain_info),
)
.await
{
Ok(_) => Ok(Redirect::to(Urls::Profile.as_ref()).into_response()),
Err(e) => Ok(e.into_response()),
}
}
#[derive(Deserialize)]
pub(crate) struct AddEmailQuery {
// the last email index is passed so we can return an incremented id
email_index: Option<u16>,
}
// Sends the user a new email input to fill in :)
pub(crate) async fn view_new_email_entry_partial(
State(_state): State<ServerState>,
VerifiedClientInformation(_client_auth_info): VerifiedClientInformation,
Extension(_kopid): Extension<KOpId>,
Query(email_query): Query<AddEmailQuery>,
) -> axum::response::Result<Response> {
let add_email_trigger =
HxResponseTrigger::after_swap([HxEvent::new("addEmailSwapped".to_string())]);
Ok((
add_email_trigger,
FormEmailEntryListPartial {
can_edit: true,
value: "".to_string(),
primary: email_query.email_index.is_none(),
index: email_query.email_index.map(|i| i + 1).unwrap_or(0),
},
)
.into_response())
}
pub(crate) async fn view_profile_unlock_get(
State(state): State<ServerState>,
VerifiedClientInformation(client_auth_info): VerifiedClientInformation,

25
server/core/static/external/forms.js vendored Normal file
View file

@ -0,0 +1,25 @@
// This file will contain js helpers to have some interactivity on forms that we can't achieve with pure html.
function rehook_string_list_removers() {
const buttons = document.getElementsByClassName("kanidm-remove-list-entry");
for (let i = 0; i < buttons.length; i++) {
const button = buttons.item(i)
if (button.getAttribute("kanidm_hooked") !== null) continue
button.addEventListener("click", (e) => {
// Expected html nesting: div.email-entry > div.input-group > button.kanidm-remove-list-entry
let li = button.parentElement?.parentElement;
if (li && li.classList.contains("email-entry")) {
li.remove();
}
})
button.setAttribute("kanidm_hooked", "")
}
}
window.onload = function () {
rehook_string_list_removers();
document.body.addEventListener("addEmailSwapped", () => {
rehook_string_list_removers();
})
};

View file

@ -0,0 +1,34 @@
htmx.defineExtension("bs-validation", {
onEvent: function (name, evt) {
let form = evt.detail.elt;
// Htmx propagates attributes onto children like button, which would break those buttons, so we return if not a form.
if (form.tagName !== "FORM") return;
// check if trigger attribute and submit event exists
// for the form
if (!form.hasAttribute("hx-trigger")) {
// set trigger for custom event bs-send
form.setAttribute("hx-trigger", "bs-send");
// and attach the event only once
form.addEventListener("submit", function (event) {
if (form.checkValidity()) {
// trigger custom event hx-trigger="bs-send"
htmx.trigger(form, "bsSend");
}
// focus the first :invalid field
let invalidField = form.querySelector(":invalid");
if (invalidField) {
invalidField.focus();
}
console.log("prevented htmx send, form was invalid")
event.preventDefault()
event.stopPropagation()
form.classList.add("was-validated")
}, false)
}
}
});

View file

@ -29,6 +29,7 @@ body {
display: block !important;
}
/*
* Sidebar
*/
@ -206,3 +207,7 @@ footer {
height: var(--icon-size);
transform: rotate(35deg);
}
.cursor-pointer:hover {
cursor: pointer;
}

View file

@ -3,6 +3,8 @@
(% block title %)Profile(% endblock %)
(% block head %)
<script src="/pkg/external/forms.js"></script>
<script src="/pkg/external/htmx_bs_validation.js"></script>
(% endblock %)
(% block main %)

View file

@ -0,0 +1,17 @@
<div class="email-entry">
<input hidden class="email-index-state" type="text" name="email_index" value="((index))">
<div class="input-group mb-1">
<div class="input-group-text">
<input class="form-check-input mt-0" name="primary_email_index" type="radio" value="((index))" aria-label="Primary email radio button for following text input" (% if primary %) checked (% endif %)(% if !can_edit %) disabled (% endif %)>
</div>
(% if can_edit %)
<input type="email" aria-label="Email address input ((index))" class="form-control" name="emails[]" value="(( value ))" hx-validate="true" required>
<button type="button" class="btn btn-secondary kanidm-remove-list-entry">Remove</button>
(% else %)
<input type="email" aria-label="Email address input ((index))" class="form-control" name="emails[]" value="(( value ))" hx-validate="true" required disabled>
(% endif %)
</div>
<div class="invalid-feedback">Please enter a valid email address.</div>
</div>

View file

@ -0,0 +1,7 @@
<li class="mb-2">
<div class="input-group">
<input type="(( type ))" class="form-control" name="(( name ))" value="(( value ))" hx-validate="true" required>
(% if can_rw %)<button type="button" class="btn btn-secondary kanidm-remove-list-entry">Remove</button>(% endif %)
</div>
<div class="invalid-feedback">(( invalid_feedback ))</div>
</li>

View file

@ -0,0 +1,104 @@
(% extends "user_settings_partial_base.html" %)
(% block selected_setting_group %)
Profile Difference
(% endblock %)
(% block settings_vertical_point %)lg(% endblock %)
(% block settings_window %)
<form>
(% if person.name != new_attrs.account_name %)
<input type="hidden" name="account_name" value="(( new_attrs.account_name ))"/>
(% endif %)
(% if person.displayname != new_attrs.display_name %)
<input type="hidden" name="display_name" value="(( new_attrs.display_name ))"/>
(% endif %)
(% for email in new_attrs.emails %)
(% if !email.primary %)
<input type="hidden" name="emails[]" value="(( email.value ))"/>
(% endif %)
(% endfor %)
(% if let Some(new_primary_mail) = new_primary_mail %)
<input type="hidden" name="new_primary_mail" value="(( new_primary_mail ))"/>
(% endif %)
<table class="table table-bordered overflow-x-scroll">
<thead>
<tr>
<th scope="col">Attribute</th>
<th scope="col">Old value</th>
<th scope="col">New value</th>
</tr>
</thead>
(% if person.name != new_attrs.account_name %)
<tr>
<th scope="row">Username</th>
<td class="text-break">(( person.name ))</td>
<td class="text-break">(( new_attrs.account_name ))</td>
</tr>
(% endif %)
(% if person.displayname != new_attrs.display_name %)
<tr>
<th scope="row">Display name</th>
<td class="text-break">(( person.displayname ))</td>
<td class="text-break">(( new_attrs.display_name ))</td>
</tr>
(% endif %)
(% if !emails_are_same %)
<tr>
<th scope="row">Primary Emails</th>
<td class="text-nowrap">
(( primary_mail.clone().unwrap_or("none".to_string()) ))
</td>
<td class="text-nowrap">
(( new_primary_mail.clone().unwrap_or("none".to_string()) ))
</td>
</tr>
<tr>
<th scope="row">Secondary Emails</th>
<td class="text-break">
<ul class="ps-3">
(% for email in person.mails %)
(% if !email.primary %)
<li class="text-nowrap">(( email.value ))</li>
(% endif %)
(% endfor %)
</ul>
</td>
<td class="text-break">
<ul class="ps-3">
(% for email in new_attrs.emails %)
(% if !email.primary %)
<li class="text-nowrap">(( email.value ))</li>
(% endif %)
(% endfor %)
</ul>
</td>
</tr>
(% endif %)
</table>
<div class="pt-4" hx-target="#user_settings_container" hx-swap="outerHTML">
(% if can_rw %)
<button class="btn btn-danger" type="button" hx-get="/ui/profile" hx-target="body" hx-swap="outerHTML">Discard
Changes
</button>
<button class="btn btn-primary" type="button" hx-post="/ui/api/user_settings/confirm_profile" hx-target="body"
hx-swap="outerHTML">Confirm Changes
</button>
(% else %)
<a href="/ui/profile/unlock" hx-boost="false">
<!-- TODO: at the moment, session expiring here means progress is lost. Do we just show an error screen ? We can't pass the update state through the reauth session, and we don't have profile update sessions like cred update. -->
<button class="btn btn-primary" type="button">Unlock Confirm 🔓</button>
</a>
(% endif %)
</div>
</form>
(% endblock %)

View file

@ -4,40 +4,78 @@
Profile
(% endblock %)
(% macro string_attr(dispname, name, value, editable, attribute) %)
(% if scim_effective_access.search.check(attribute|as_ref) %)
<div class="row g-0 mt-3">
<label for="person(( name ))" class="col-12 col-md-3 col-lg-2 col-form-label fw-bold py-0">(( dispname ))</label>
<div class="col-12 col-md-8 col-lg-6">
(% if scim_effective_access.modify_present.check(attribute|as_ref) %)
<input class="form-control py-0" id="person(( name ))" name="(( name ))" value="(( value ))">
(% else %)
<input readonly class="form-control-plaintext py-0" id="person(( name ))" name="(( name ))" value="(( value ))">
(% endif %)
</div>
</div>
(% endif %)
(% endmacro %)
(% block settings_window %)
<form>
<div class="mb-2 row">
<label for="profileUserName" class="col-12 col-md-3 col-xl-2 col-form-label">User name</label>
<div class="col-12 col-md-6 col-lg-5">
<input type="text" readonly class="form-control-plaintext" id="profileUserName" value="(( account_name ))">
</div>
</div>
<form id="user_settings_container" class="needs-validation"
hx-post="/ui/api/user_settings/edit_profile"
hx-target="#main"
hx-swap="outerHTML"
hx-validate="true"
hx-ext="bs-validation"
novalidate>
(% call string_attr("Name", "name", person.name, true, Attribute::Name) %)
<div class="mb-2 row">
<label for="profileDisplayName" class="col-12 col-md-3 col-xl-2 col-form-label">Display name</label>
<div class="col-12 col-md-6 col-lg-5">
<input type="text" class="form-control-plaintext" id="profileDisplayName" value="(( display_name ))" disabled>
(% call string_attr("Displayname", "displayname", person.displayname, true, Attribute::DisplayName) %)
<div class="mb-2">
<div class="mt-3 mb-2 col-12 col-md-11 col-lg-8">
<label for="profileEmail" class="fw-bold">Email addresses (% if can_rw %)(selected => primary)(% else %)(select primary)(% endif %)</label>
(% if can_rw %)
<a class="cursor-pointer float-end"
hx-boost="true"
hx-get="/ui/api/user_settings/add_email"
hx-target="#emailAddresses"
hx-include="#emailAddresses :last-child .email-index-state"
hx-swap="beforeend">
<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bi bi-plus-square"
viewBox="0 0 16 16" width="20" height="20">
<path d="M14 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1zM2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2z"></path>
<path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4"></path>
</svg>
</a>
(% endif %)
</div>
</div>
<div class="mb-2 row">
<label for="profileEmail" class="col-12 col-md-3 col-xl-2 col-form-label">Email</label>
<div class="col-12 col-md-6 col-lg-5">
<input type="email" disabled class="form-control-plaintext" id="profileEmail" value="(( email.clone().unwrap_or("None configured".to_string())))">
<div>
<div class="row g-0">
<div class="col-12 col-md-11 col-lg-8" id="emailAddresses">
(% for (index, email) in person.mails.iter().enumerate() %)
(% let value = email.value.clone() %)
(% let primary = email.primary %)
(% let can_edit = scim_effective_access.modify_present.check(Attribute::Mail|as_ref) %)
(% include "user_settings/form_email_entry_partial.html" %)
(% endfor %)
</div>
</div>
</div>
</div>
<!-- Edit button -->
<!-- <div class="pt-4">
<div class="pt-4">
(% if can_rw %)
<button class="btn btn-primary" type="button" hx-post="/ui/api/user_settings/edit_profile" disabled>Edit (Currently Not Working!)</button>
<button class="btn btn-primary" type="submit">Save</button>
(% else %)
<a href=(Urls::ProfileUnlock) hx-boost="false">
<button class="btn btn-primary" type="button">((UiMessage::UnlockEdit))</button>
</a>
<a href="/ui/profile/unlock" hx-boost="false">
<button class="btn btn-primary" type="button">Unlock Edit 🔒</button>
</a>
(% endif %)
</div> -->
</div>
</form>
(% endblock %)

View file

@ -465,13 +465,13 @@ async fn start_daemon(opt: KanidmdParser, config: Configuration) -> ExitCode {
return ExitCode::FAILURE;
}
match &opt.commands {
let lock_was_setup = match &opt.commands {
// we aren't going to touch the DB so we can carry on
KanidmdOpt::ShowReplicationCertificate { .. }
| KanidmdOpt::RenewReplicationCertificate { .. }
| KanidmdOpt::RefreshReplicationConsumer { .. }
| KanidmdOpt::RecoverAccount { .. }
| KanidmdOpt::HealthCheck(_) => (),
| KanidmdOpt::HealthCheck(_) => None,
_ => {
// Okay - Lets now create our lock and go.
#[allow(clippy::expect_used)]
@ -482,24 +482,53 @@ async fn start_daemon(opt: KanidmdParser, config: Configuration) -> ExitCode {
let flock = match File::create(&klock_path) {
Ok(flock) => flock,
Err(e) => {
error!("ERROR: Refusing to start - unable to create kanidmd exclusive lock at {} - {:?}", klock_path.display(), e);
Err(err) => {
error!(
"ERROR: Refusing to start - unable to create kanidmd exclusive lock at {}",
klock_path.display()
);
error!(?err);
return ExitCode::FAILURE;
}
};
match flock.try_lock_exclusive() {
Ok(()) => debug!("Acquired kanidm exclusive lock"),
Err(e) => {
error!("ERROR: Refusing to start - unable to lock kanidmd exclusive lock at {} - {:?}", klock_path.display(), e);
Ok(true) => debug!("Acquired kanidm exclusive lock"),
Ok(false) => {
error!(
"ERROR: Refusing to start - unable to lock kanidmd exclusive lock at {}",
klock_path.display()
);
error!("Is another kanidmd process running?");
return ExitCode::FAILURE;
}
Err(err) => {
error!(
"ERROR: Refusing to start - unable to lock kanidmd exclusive lock at {}",
klock_path.display()
);
error!(?err);
return ExitCode::FAILURE;
}
};
Some(klock_path)
}
};
let result_code = kanidm_main(config, opt).await;
if let Some(klock_path) = lock_was_setup {
if let Err(reason) = std::fs::remove_file(&klock_path) {
warn!(
?reason,
"WARNING: Unable to clean up kanidmd exclusive lock at {}",
klock_path.display()
);
}
}
kanidm_main(config, opt).await
result_code
}
fn main() -> ExitCode {

View file

@ -165,10 +165,10 @@ impl ReplEntryV1 {
// but for now, if it's an empty set in any capacity, we map
// to None and just send the Cid since they have the same result
// on how the entry/attr state looks at each end.
if maybe.len() > 0 {
Some(maybe.to_db_valueset_v2())
} else {
if maybe.is_empty() {
None
} else {
Some(maybe.to_db_valueset_v2())
}
);
@ -298,10 +298,10 @@ impl ReplIncrementalEntryV1 {
let live_attr = live_attrs.get(attr_name);
let cid = cid.into();
let attr = live_attr.and_then(|maybe| {
if maybe.len() > 0 {
Some(maybe.to_db_valueset_v2())
} else {
if maybe.is_empty() {
None
} else {
Some(maybe.to_db_valueset_v2())
}
});

View file

@ -83,7 +83,7 @@ impl ActorReader {
// Is this a design flaw? We probably need to know what the state was that we
// requested to move to?
match (&self.state, action, result) {
(State::Unauthenticated { .. }, TransitionAction::Login, TransitionResult::Ok) => {
(State::Unauthenticated, TransitionAction::Login, TransitionResult::Ok) => {
self.state = State::Authenticated;
}
(State::Authenticated, TransitionAction::ReadSelfMemberOf, TransitionResult::Ok) => {

View file

@ -14,6 +14,8 @@ repository = { workspace = true }
[features]
default = ["unix"]
unix = []
selinux = ["dep:selinux"]
tpm = []
[lib]
name = "kanidm_unix_common"
@ -35,6 +37,11 @@ tokio-util = { workspace = true, features = ["codec"] }
toml = { workspace = true }
tracing = { workspace = true }
selinux = { workspace = true, optional = true }
[target.'cfg(not(target_family = "windows"))'.dependencies]
kanidm_utils_users = { workspace = true }
[build-dependencies]
kanidm_build_profiles = { workspace = true }

View file

@ -26,3 +26,6 @@ pub mod unix_config;
pub mod unix_passwd;
#[cfg(target_family = "unix")]
pub mod unix_proto;
#[cfg(all(target_family = "unix", feature = "selinux"))]
pub mod selinux_util;

View file

@ -1,13 +1,24 @@
//! This is configuration definitions and parser for the various unix integration
//! tools and services. This needs to support a number of use cases like pam/nss
//! modules parsing the config quickly and the unix daemon which has to connect to
//! various backend sources.
//!
//! To achieve this the configuration has two main sections - the configuration
//! specification which will be parsed by the tools, then the configuration as
//! relevant to that tool.
use std::env;
use std::fmt::{Display, Formatter};
use std::fs::File;
use std::io::{ErrorKind, Read};
use std::path::Path;
use std::path::{Path, PathBuf};
#[cfg(all(target_family = "unix", feature = "selinux"))]
use crate::selinux_util;
use crate::unix_passwd::UnixIntegrationError;
use serde::Deserialize;
use crate::constants::*;
use serde::Deserialize;
#[derive(Debug, Copy, Clone)]
pub enum HomeAttr {
@ -49,35 +60,539 @@ impl Display for UidAttr {
}
}
#[derive(Debug, Clone, Default)]
pub enum HsmType {
#[cfg_attr(not(feature = "tpm"), default)]
Soft,
#[cfg_attr(feature = "tpm", default)]
TpmIfPossible,
Tpm,
}
impl Display for HsmType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
HsmType::Soft => write!(f, "Soft"),
HsmType::TpmIfPossible => write!(f, "Tpm if possible"),
HsmType::Tpm => write!(f, "Tpm"),
}
}
}
// Allowed as the large enum is only short lived at startup to the true config
#[allow(clippy::large_enum_variant)]
// This bit of magic lets us deserialise the old config and the new versions.
#[derive(Debug, Deserialize)]
struct ConfigInt {
#[serde(untagged)]
enum ConfigUntagged {
Versioned(ConfigVersion),
Legacy(ConfigInt),
}
#[derive(Debug, Deserialize)]
#[serde(tag = "version")]
enum ConfigVersion {
#[serde(rename = "2")]
V2 {
#[serde(flatten)]
values: ConfigV2,
},
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
/// This is the version 2 of the JSON configuration specification for the unixd suite.
struct ConfigV2 {
cache_db_path: Option<String>,
sock_path: Option<String>,
task_sock_path: Option<String>,
cache_timeout: Option<u64>,
default_shell: Option<String>,
home_prefix: Option<String>,
home_mount_prefix: Option<String>,
home_attr: Option<String>,
home_alias: Option<String>,
use_etc_skel: Option<bool>,
uid_attr_map: Option<String>,
gid_attr_map: Option<String>,
selinux: Option<bool>,
hsm_pin_path: Option<String>,
hsm_type: Option<String>,
tpm_tcti_name: Option<String>,
kanidm: Option<KanidmConfigV2>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct GroupMap {
pub local: String,
pub with: String,
}
#[derive(Debug, Deserialize)]
struct KanidmConfigV2 {
conn_timeout: Option<u64>,
request_timeout: Option<u64>,
pam_allowed_login_groups: Option<Vec<String>>,
#[serde(default)]
map_group: Vec<GroupMap>,
}
#[derive(Debug, Deserialize)]
/// This is the version 1 of the JSON configuration specification for the unixd suite.
struct ConfigInt {
db_path: Option<String>,
sock_path: Option<String>,
task_sock_path: Option<String>,
conn_timeout: Option<u64>,
request_timeout: Option<u64>,
cache_timeout: Option<u64>,
pam_allowed_login_groups: Option<Vec<String>>,
default_shell: Option<String>,
home_prefix: Option<String>,
home_mount_prefix: Option<String>,
home_attr: Option<String>,
home_alias: Option<String>,
use_etc_skel: Option<bool>,
uid_attr_map: Option<String>,
gid_attr_map: Option<String>,
selinux: Option<bool>,
#[serde(default)]
allow_local_account_override: Vec<String>,
hsm_pin_path: Option<String>,
hsm_type: Option<String>,
tpm_tcti_name: Option<String>,
// Detect and warn on values in these places - this is to catch
// when someone is using a v2 value on a v1 config.
#[serde(default)]
cache_db_path: Option<toml::value::Value>,
#[serde(default)]
kanidm: Option<toml::value::Value>,
}
// ========================================================================
#[derive(Debug)]
/// This is the parsed Kanidm provider configuration that the Unixd resolver
/// will use to connect to Kanidm.
pub struct KanidmConfig {
pub conn_timeout: u64,
pub request_timeout: u64,
pub pam_allowed_login_groups: Vec<String>,
pub map_group: Vec<GroupMap>,
}
#[derive(Debug)]
pub struct KanidmUnixdConfig {
/// This is the parsed configuration for the Unixd resolver.
pub struct UnixdConfig {
pub cache_db_path: String,
pub sock_path: String,
pub task_sock_path: String,
pub cache_timeout: u64,
pub unix_sock_timeout: u64,
pub default_shell: String,
pub home_prefix: PathBuf,
pub home_mount_prefix: Option<PathBuf>,
pub home_attr: HomeAttr,
pub home_alias: Option<HomeAttr>,
pub use_etc_skel: bool,
pub uid_attr_map: UidAttr,
pub gid_attr_map: UidAttr,
pub selinux: bool,
pub hsm_type: HsmType,
pub hsm_pin_path: String,
pub tpm_tcti_name: String,
pub kanidm_config: Option<KanidmConfig>,
}
impl Default for UnixdConfig {
fn default() -> Self {
UnixdConfig::new()
}
}
impl Display for UnixdConfig {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "cache_db_path: {}", &self.cache_db_path)?;
writeln!(f, "sock_path: {}", self.sock_path)?;
writeln!(f, "task_sock_path: {}", self.task_sock_path)?;
writeln!(f, "unix_sock_timeout: {}", self.unix_sock_timeout)?;
writeln!(f, "cache_timeout: {}", self.cache_timeout)?;
writeln!(f, "default_shell: {}", self.default_shell)?;
writeln!(f, "home_prefix: {:?}", self.home_prefix)?;
match self.home_mount_prefix.as_deref() {
Some(val) => writeln!(f, "home_mount_prefix: {:?}", val)?,
None => writeln!(f, "home_mount_prefix: unset")?,
}
writeln!(f, "home_attr: {}", self.home_attr)?;
match self.home_alias {
Some(val) => writeln!(f, "home_alias: {}", val)?,
None => writeln!(f, "home_alias: unset")?,
}
writeln!(f, "uid_attr_map: {}", self.uid_attr_map)?;
writeln!(f, "gid_attr_map: {}", self.gid_attr_map)?;
writeln!(f, "hsm_type: {}", self.hsm_type)?;
writeln!(f, "tpm_tcti_name: {}", self.tpm_tcti_name)?;
writeln!(f, "selinux: {}", self.selinux)?;
if let Some(kconfig) = &self.kanidm_config {
writeln!(f, "kanidm: enabled")?;
writeln!(
f,
"kanidm pam_allowed_login_groups: {:#?}",
kconfig.pam_allowed_login_groups
)?;
writeln!(f, "kanidm conn_timeout: {}", kconfig.conn_timeout)?;
writeln!(f, "kanidm request_timeout: {}", kconfig.request_timeout)?;
} else {
writeln!(f, "kanidm: disabled")?;
};
Ok(())
}
}
impl UnixdConfig {
pub fn new() -> Self {
let cache_db_path = match env::var("KANIDM_CACHE_DB_PATH") {
Ok(val) => val,
Err(_) => DEFAULT_CACHE_DB_PATH.into(),
};
let hsm_pin_path = match env::var("KANIDM_HSM_PIN_PATH") {
Ok(val) => val,
Err(_) => DEFAULT_HSM_PIN_PATH.into(),
};
UnixdConfig {
cache_db_path,
sock_path: DEFAULT_SOCK_PATH.to_string(),
task_sock_path: DEFAULT_TASK_SOCK_PATH.to_string(),
unix_sock_timeout: DEFAULT_CONN_TIMEOUT * 2,
cache_timeout: DEFAULT_CACHE_TIMEOUT,
default_shell: DEFAULT_SHELL.to_string(),
home_prefix: DEFAULT_HOME_PREFIX.into(),
home_mount_prefix: None,
home_attr: DEFAULT_HOME_ATTR,
home_alias: DEFAULT_HOME_ALIAS,
use_etc_skel: DEFAULT_USE_ETC_SKEL,
uid_attr_map: DEFAULT_UID_ATTR_MAP,
gid_attr_map: DEFAULT_GID_ATTR_MAP,
selinux: DEFAULT_SELINUX,
hsm_pin_path,
hsm_type: HsmType::default(),
tpm_tcti_name: DEFAULT_TPM_TCTI_NAME.to_string(),
kanidm_config: None,
}
}
pub fn read_options_from_optional_config<P: AsRef<Path> + std::fmt::Debug>(
self,
config_path: P,
) -> Result<Self, UnixIntegrationError> {
debug!("Attempting to load configuration from {:#?}", &config_path);
let mut f = match File::open(&config_path) {
Ok(f) => {
debug!("Successfully opened configuration file {:#?}", &config_path);
f
}
Err(e) => {
match e.kind() {
ErrorKind::NotFound => {
debug!(
"Configuration file {:#?} not found, skipping.",
&config_path
);
}
ErrorKind::PermissionDenied => {
warn!(
"Permission denied loading configuration file {:#?}, skipping.",
&config_path
);
}
_ => {
debug!(
"Unable to open config file {:#?} [{:?}], skipping ...",
&config_path, e
);
}
};
return Ok(self);
}
};
let mut contents = String::new();
f.read_to_string(&mut contents).map_err(|e| {
error!("{:?}", e);
UnixIntegrationError
})?;
let config: ConfigUntagged = toml::from_str(contents.as_str()).map_err(|e| {
error!("{:?}", e);
UnixIntegrationError
})?;
match config {
ConfigUntagged::Legacy(config) => self.apply_from_config_legacy(config),
ConfigUntagged::Versioned(ConfigVersion::V2 { values }) => {
self.apply_from_config_v2(values)
}
}
}
fn apply_from_config_legacy(self, config: ConfigInt) -> Result<Self, UnixIntegrationError> {
if config.kanidm.is_some() || config.cache_db_path.is_some() {
error!("You are using version=\"2\" options in a legacy config. THESE WILL NOT WORK.");
return Err(UnixIntegrationError);
}
let map_group = config
.allow_local_account_override
.iter()
.map(|name| GroupMap {
local: name.clone(),
with: name.clone(),
})
.collect();
let kanidm_config = Some(KanidmConfig {
conn_timeout: config.conn_timeout.unwrap_or(DEFAULT_CONN_TIMEOUT),
request_timeout: config.request_timeout.unwrap_or(DEFAULT_CONN_TIMEOUT * 2),
pam_allowed_login_groups: config.pam_allowed_login_groups.unwrap_or_default(),
map_group,
});
// Now map the values into our config.
Ok(UnixdConfig {
cache_db_path: config.db_path.unwrap_or(self.cache_db_path),
sock_path: config.sock_path.unwrap_or(self.sock_path),
task_sock_path: config.task_sock_path.unwrap_or(self.task_sock_path),
unix_sock_timeout: DEFAULT_CONN_TIMEOUT * 2,
cache_timeout: config.cache_timeout.unwrap_or(self.cache_timeout),
default_shell: config.default_shell.unwrap_or(self.default_shell),
home_prefix: config
.home_prefix
.map(|p| p.into())
.unwrap_or(self.home_prefix.clone()),
home_mount_prefix: config.home_mount_prefix.map(|p| p.into()),
home_attr: config
.home_attr
.and_then(|v| match v.as_str() {
"uuid" => Some(HomeAttr::Uuid),
"spn" => Some(HomeAttr::Spn),
"name" => Some(HomeAttr::Name),
_ => {
warn!("Invalid home_attr configured, using default ...");
None
}
})
.unwrap_or(self.home_attr),
home_alias: config
.home_alias
.and_then(|v| match v.as_str() {
"none" => Some(None),
"uuid" => Some(Some(HomeAttr::Uuid)),
"spn" => Some(Some(HomeAttr::Spn)),
"name" => Some(Some(HomeAttr::Name)),
_ => {
warn!("Invalid home_alias configured, using default ...");
None
}
})
.unwrap_or(self.home_alias),
use_etc_skel: config.use_etc_skel.unwrap_or(self.use_etc_skel),
uid_attr_map: config
.uid_attr_map
.and_then(|v| match v.as_str() {
"spn" => Some(UidAttr::Spn),
"name" => Some(UidAttr::Name),
_ => {
warn!("Invalid uid_attr_map configured, using default ...");
None
}
})
.unwrap_or(self.uid_attr_map),
gid_attr_map: config
.gid_attr_map
.and_then(|v| match v.as_str() {
"spn" => Some(UidAttr::Spn),
"name" => Some(UidAttr::Name),
_ => {
warn!("Invalid gid_attr_map configured, using default ...");
None
}
})
.unwrap_or(self.gid_attr_map),
selinux: match config.selinux.unwrap_or(self.selinux) {
#[cfg(all(target_family = "unix", feature = "selinux"))]
true => selinux_util::supported(),
_ => false,
},
hsm_pin_path: config.hsm_pin_path.unwrap_or(self.hsm_pin_path),
hsm_type: config
.hsm_type
.and_then(|v| match v.as_str() {
"soft" => Some(HsmType::Soft),
"tpm_if_possible" => Some(HsmType::TpmIfPossible),
"tpm" => Some(HsmType::Tpm),
_ => {
warn!("Invalid hsm_type configured, using default ...");
None
}
})
.unwrap_or(self.hsm_type),
tpm_tcti_name: config
.tpm_tcti_name
.unwrap_or(DEFAULT_TPM_TCTI_NAME.to_string()),
kanidm_config,
})
}
fn apply_from_config_v2(self, config: ConfigV2) -> Result<Self, UnixIntegrationError> {
let kanidm_config = if let Some(kconfig) = config.kanidm {
match &kconfig.pam_allowed_login_groups {
None => {
error!("You have a 'kanidm' section in the config but an empty pam_allowed_login_groups set. USERS CANNOT AUTH.")
}
Some(groups) => {
if groups.is_empty() {
error!("You have a 'kanidm' section in the config but an empty pam_allowed_login_groups set. USERS CANNOT AUTH.");
}
}
}
Some(KanidmConfig {
conn_timeout: kconfig.conn_timeout.unwrap_or(DEFAULT_CONN_TIMEOUT),
request_timeout: kconfig.request_timeout.unwrap_or(DEFAULT_CONN_TIMEOUT * 2),
pam_allowed_login_groups: kconfig.pam_allowed_login_groups.unwrap_or_default(),
map_group: kconfig.map_group,
})
} else {
error!(
"You are using a version 2 config without a 'kanidm' section. USERS CANNOT AUTH."
);
None
};
// Now map the values into our config.
Ok(UnixdConfig {
cache_db_path: config.cache_db_path.unwrap_or(self.cache_db_path),
sock_path: config.sock_path.unwrap_or(self.sock_path),
task_sock_path: config.task_sock_path.unwrap_or(self.task_sock_path),
unix_sock_timeout: DEFAULT_CONN_TIMEOUT * 2,
cache_timeout: config.cache_timeout.unwrap_or(self.cache_timeout),
default_shell: config.default_shell.unwrap_or(self.default_shell),
home_prefix: config
.home_prefix
.map(|p| p.into())
.unwrap_or(self.home_prefix.clone()),
home_mount_prefix: config.home_mount_prefix.map(|p| p.into()),
home_attr: config
.home_attr
.and_then(|v| match v.as_str() {
"uuid" => Some(HomeAttr::Uuid),
"spn" => Some(HomeAttr::Spn),
"name" => Some(HomeAttr::Name),
_ => {
warn!("Invalid home_attr configured, using default ...");
None
}
})
.unwrap_or(self.home_attr),
home_alias: config
.home_alias
.and_then(|v| match v.as_str() {
"none" => Some(None),
"uuid" => Some(Some(HomeAttr::Uuid)),
"spn" => Some(Some(HomeAttr::Spn)),
"name" => Some(Some(HomeAttr::Name)),
_ => {
warn!("Invalid home_alias configured, using default ...");
None
}
})
.unwrap_or(self.home_alias),
use_etc_skel: config.use_etc_skel.unwrap_or(self.use_etc_skel),
uid_attr_map: config
.uid_attr_map
.and_then(|v| match v.as_str() {
"spn" => Some(UidAttr::Spn),
"name" => Some(UidAttr::Name),
_ => {
warn!("Invalid uid_attr_map configured, using default ...");
None
}
})
.unwrap_or(self.uid_attr_map),
gid_attr_map: config
.gid_attr_map
.and_then(|v| match v.as_str() {
"spn" => Some(UidAttr::Spn),
"name" => Some(UidAttr::Name),
_ => {
warn!("Invalid gid_attr_map configured, using default ...");
None
}
})
.unwrap_or(self.gid_attr_map),
selinux: match config.selinux.unwrap_or(self.selinux) {
#[cfg(all(target_family = "unix", feature = "selinux"))]
true => selinux_util::supported(),
_ => false,
},
hsm_pin_path: config.hsm_pin_path.unwrap_or(self.hsm_pin_path),
hsm_type: config
.hsm_type
.and_then(|v| match v.as_str() {
"soft" => Some(HsmType::Soft),
"tpm_if_possible" => Some(HsmType::TpmIfPossible),
"tpm" => Some(HsmType::Tpm),
_ => {
warn!("Invalid hsm_type configured, using default ...");
None
}
})
.unwrap_or(self.hsm_type),
tpm_tcti_name: config
.tpm_tcti_name
.unwrap_or(DEFAULT_TPM_TCTI_NAME.to_string()),
kanidm_config,
})
}
}
#[derive(Debug)]
/// This is the parsed configuration that will be used by pam/nss tools that need fast access to
/// only the socket and timeout information related to the resolver.
pub struct PamNssConfig {
pub sock_path: String,
// pub conn_timeout: u64,
pub unix_sock_timeout: u64,
}
impl Default for KanidmUnixdConfig {
impl Default for PamNssConfig {
fn default() -> Self {
KanidmUnixdConfig::new()
PamNssConfig::new()
}
}
impl Display for KanidmUnixdConfig {
impl Display for PamNssConfig {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "sock_path: {}", self.sock_path)?;
writeln!(f, "unix_sock_timeout: {}", self.unix_sock_timeout)
}
}
impl KanidmUnixdConfig {
impl PamNssConfig {
pub fn new() -> Self {
KanidmUnixdConfig {
PamNssConfig {
sock_path: DEFAULT_SOCK_PATH.to_string(),
unix_sock_timeout: DEFAULT_CONN_TIMEOUT * 2,
}
@ -124,22 +639,45 @@ impl KanidmUnixdConfig {
UnixIntegrationError
})?;
let config: ConfigInt = toml::from_str(contents.as_str()).map_err(|e| {
let config: ConfigUntagged = toml::from_str(contents.as_str()).map_err(|e| {
error!("{:?}", e);
UnixIntegrationError
})?;
match config {
ConfigUntagged::Legacy(config) => self.apply_from_config_legacy(config),
ConfigUntagged::Versioned(ConfigVersion::V2 { values }) => {
self.apply_from_config_v2(values)
}
}
}
fn apply_from_config_legacy(self, config: ConfigInt) -> Result<Self, UnixIntegrationError> {
let unix_sock_timeout = config
.conn_timeout
.map(|v| v * 2)
.unwrap_or(self.unix_sock_timeout);
// Now map the values into our config.
Ok(KanidmUnixdConfig {
Ok(PamNssConfig {
sock_path: config.sock_path.unwrap_or(self.sock_path),
unix_sock_timeout,
})
}
fn apply_from_config_v2(self, config: ConfigV2) -> Result<Self, UnixIntegrationError> {
let kanidm_conn_timeout = config
.kanidm
.as_ref()
.and_then(|k_config| k_config.conn_timeout)
.map(|timeout| timeout * 2);
// Now map the values into our config.
Ok(PamNssConfig {
sock_path: config.sock_path.unwrap_or(self.sock_path),
unix_sock_timeout: kanidm_conn_timeout.unwrap_or(self.unix_sock_timeout),
})
}
}
#[cfg(test)]
@ -165,9 +703,12 @@ mod tests {
if filename.starts_with("unixd") {
print!("Checking that {} parses as a valid config...", filename);
KanidmUnixdConfig::new()
UnixdConfig::new()
.read_options_from_optional_config(file.path())
.expect("Failed to parse");
.inspect_err(|e| {
println!("Failed to parse: {:?}", e);
})
.expect("Failed to parse!");
println!("OK");
}
}

View file

@ -1,5 +1,5 @@
use kanidm_unix_common::client_sync::DaemonClientBlocking;
use kanidm_unix_common::unix_config::KanidmUnixdConfig;
use kanidm_unix_common::unix_config::PamNssConfig;
use kanidm_unix_common::unix_passwd::{
read_etc_group_file, read_etc_passwd_file, EtcGroup, EtcUser,
};
@ -36,7 +36,7 @@ impl RequestOptions {
fn connect_to_daemon(self) -> Source {
match self {
RequestOptions::Main { config_path } => {
let maybe_client = KanidmUnixdConfig::new()
let maybe_client = PamNssConfig::new()
.read_options_from_optional_config(config_path)
.ok()
.and_then(|cfg| {

View file

@ -2,7 +2,7 @@ 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_config::PamNssConfig;
use kanidm_unix_common::unix_passwd::{
read_etc_passwd_file, read_etc_shadow_file, EtcShadow, EtcUser,
};
@ -44,7 +44,7 @@ impl RequestOptions {
fn connect_to_daemon(self) -> Source {
match self {
RequestOptions::Main { config_path } => {
let maybe_client = KanidmUnixdConfig::new()
let maybe_client = PamNssConfig::new()
.read_options_from_optional_config(config_path)
.ok()
.and_then(|cfg| {

View file

@ -36,7 +36,7 @@ use std::convert::TryFrom;
use std::ffi::CStr;
use kanidm_unix_common::constants::DEFAULT_CONFIG_PATH;
use kanidm_unix_common::unix_config::KanidmUnixdConfig;
use kanidm_unix_common::unix_config::PamNssConfig;
use crate::core::{self, RequestOptions};
use crate::pam::constants::*;
@ -50,8 +50,8 @@ use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::fmt;
use tracing_subscriber::prelude::*;
pub fn get_cfg() -> Result<KanidmUnixdConfig, PamResultCode> {
KanidmUnixdConfig::new()
pub fn get_cfg() -> Result<PamNssConfig, PamResultCode> {
PamNssConfig::new()
.read_options_from_optional_config(DEFAULT_CONFIG_PATH)
.map_err(|_| PamResultCode::PAM_SERVICE_ERR)
}

View file

@ -14,8 +14,8 @@ repository = { workspace = true }
[features]
default = ["unix"]
unix = []
selinux = ["dep:selinux"]
tpm = ["kanidm-hsm-crypto/tpm"]
selinux = ["dep:selinux", "kanidm_unix_common/selinux"]
tpm = ["kanidm-hsm-crypto/tpm", "kanidm_unix_common/tpm"]
[[bin]]
name = "kanidm_unixd"

View file

@ -18,7 +18,7 @@ use std::process::ExitCode;
use clap::Parser;
use kanidm_unix_common::client::DaemonClient;
use kanidm_unix_common::constants::DEFAULT_CONFIG_PATH;
use kanidm_unix_common::unix_config::KanidmUnixdConfig;
use kanidm_unix_common::unix_config::PamNssConfig;
use kanidm_unix_common::unix_proto::{
ClientRequest, ClientResponse, PamAuthRequest, PamAuthResponse, PamServiceInfo,
};
@ -28,8 +28,7 @@ include!("../opt/tool.rs");
macro_rules! setup_client {
() => {{
let Ok(cfg) =
KanidmUnixdConfig::new().read_options_from_optional_config(DEFAULT_CONFIG_PATH)
let Ok(cfg) = PamNssConfig::new().read_options_from_optional_config(DEFAULT_CONFIG_PATH)
else {
error!("Failed to parse {}", DEFAULT_CONFIG_PATH);
return ExitCode::FAILURE;

View file

@ -19,7 +19,7 @@ use std::process::ExitCode;
use clap::Parser;
use kanidm_unix_common::client::DaemonClient;
use kanidm_unix_common::constants::DEFAULT_CONFIG_PATH;
use kanidm_unix_common::unix_config::KanidmUnixdConfig;
use kanidm_unix_common::unix_config::PamNssConfig;
use kanidm_unix_common::unix_proto::{ClientRequest, ClientResponse};
include!("../opt/ssh_authorizedkeys.rs");
@ -44,8 +44,7 @@ async fn main() -> ExitCode {
debug!("Starting authorized keys tool ...");
let cfg = match KanidmUnixdConfig::new().read_options_from_optional_config(DEFAULT_CONFIG_PATH)
{
let cfg = match PamNssConfig::new().read_options_from_optional_config(DEFAULT_CONFIG_PATH) {
Ok(c) => c,
Err(e) => {
error!("Failed to parse {}: {:?}", DEFAULT_CONFIG_PATH, e);

View file

@ -18,6 +18,7 @@ use kanidm_hsm_crypto::{soft::SoftTpm, AuthValue, BoxedDynTpm, Tpm};
use kanidm_proto::constants::DEFAULT_CLIENT_CONFIG_PATH;
use kanidm_proto::internal::OperationError;
use kanidm_unix_common::constants::DEFAULT_CONFIG_PATH;
use kanidm_unix_common::unix_config::{HsmType, UnixdConfig};
use kanidm_unix_common::unix_passwd::EtcDb;
use kanidm_unix_common::unix_proto::{
ClientRequest, ClientResponse, TaskRequest, TaskRequestFrame, TaskResponse,
@ -27,7 +28,6 @@ use kanidm_unix_resolver::idprovider::interface::IdProvider;
use kanidm_unix_resolver::idprovider::kanidm::KanidmProvider;
use kanidm_unix_resolver::idprovider::system::SystemProvider;
use kanidm_unix_resolver::resolver::Resolver;
use kanidm_unix_resolver::unix_config::{HsmType, UnixdConfig};
use kanidm_utils_users::{get_current_gid, get_current_uid, get_effective_gid, get_effective_uid};
use libc::umask;
use sketching::tracing::span;

View file

@ -13,11 +13,11 @@
use bytes::{BufMut, BytesMut};
use futures::{SinkExt, StreamExt};
use kanidm_unix_common::constants::DEFAULT_CONFIG_PATH;
use kanidm_unix_common::unix_config::UnixdConfig;
use kanidm_unix_common::unix_passwd::{parse_etc_group, parse_etc_passwd, parse_etc_shadow, EtcDb};
use kanidm_unix_common::unix_proto::{
HomeDirectoryInfo, TaskRequest, TaskRequestFrame, TaskResponse,
};
use kanidm_unix_resolver::unix_config::UnixdConfig;
use kanidm_utils_users::{get_effective_gid, get_effective_uid};
use libc::{lchown, umask};
use notify_debouncer_full::notify::RecommendedWatcher;
@ -43,7 +43,7 @@ use tokio_util::codec::{Decoder, Encoder, Framed};
use walkdir::WalkDir;
#[cfg(all(target_family = "unix", feature = "selinux"))]
use kanidm_unix_resolver::selinux_util;
use kanidm_unix_common::selinux_util;
struct TaskCodec;

View file

@ -1,24 +1,22 @@
use crate::db::KeyStoreTxn;
use crate::unix_config::{GroupMap, KanidmConfig};
use async_trait::async_trait;
use hashbrown::HashMap;
use kanidm_client::{ClientError, KanidmClient, StatusCode};
use kanidm_proto::internal::OperationError;
use kanidm_proto::v1::{UnixGroupToken, UnixUserToken};
use std::collections::BTreeSet;
use std::time::{Duration, SystemTime};
use tokio::sync::{broadcast, Mutex};
use kanidm_lib_crypto::CryptoPolicy;
use kanidm_lib_crypto::DbPasswordV1;
use kanidm_lib_crypto::Password;
use super::interface::{
tpm::{self, HmacKey, Tpm},
AuthCredHandler, AuthRequest, AuthResult, GroupToken, GroupTokenState, Id, IdProvider,
IdpError, ProviderOrigin, UserToken, UserTokenState,
};
use crate::db::KeyStoreTxn;
use async_trait::async_trait;
use hashbrown::HashMap;
use kanidm_client::{ClientError, KanidmClient, StatusCode};
use kanidm_lib_crypto::CryptoPolicy;
use kanidm_lib_crypto::DbPasswordV1;
use kanidm_lib_crypto::Password;
use kanidm_proto::internal::OperationError;
use kanidm_proto::v1::{UnixGroupToken, UnixUserToken};
use kanidm_unix_common::unix_config::{GroupMap, KanidmConfig};
use kanidm_unix_common::unix_proto::PamAuthRequest;
use std::collections::BTreeSet;
use std::time::{Duration, SystemTime};
use tokio::sync::{broadcast, Mutex};
const KANIDM_HMAC_KEY: &str = "kanidm-hmac-key";
const KANIDM_PWV1_KEY: &str = "kanidm-pw-v1";

View file

@ -23,7 +23,3 @@ pub mod db;
pub mod idprovider;
#[cfg(target_family = "unix")]
pub mod resolver;
#[cfg(all(target_family = "unix", feature = "selinux"))]
pub mod selinux_util;
#[cfg(target_family = "unix")]
pub mod unix_config;

View file

@ -1,18 +1,4 @@
// use async_trait::async_trait;
use hashbrown::HashMap;
use std::fmt::Display;
use std::num::NonZeroUsize;
use std::ops::DerefMut;
use std::path::{Path, PathBuf};
use std::string::ToString;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use lru::LruCache;
use time::OffsetDateTime;
use tokio::sync::Mutex;
use uuid::Uuid;
use crate::db::{Cache, Db};
use crate::idprovider::interface::{
AuthCredHandler,
@ -30,13 +16,25 @@ use crate::idprovider::interface::{
use crate::idprovider::system::{
Shadow, SystemAuthResult, SystemProvider, SystemProviderAuthInit, SystemProviderSession,
};
use crate::unix_config::{HomeAttr, UidAttr};
use hashbrown::HashMap;
use kanidm_unix_common::constants::DEFAULT_SHELL_SEARCH_PATHS;
use kanidm_unix_common::unix_config::{HomeAttr, UidAttr};
use kanidm_unix_common::unix_passwd::{EtcGroup, EtcShadow, EtcUser};
use kanidm_unix_common::unix_proto::{
HomeDirectoryInfo, NssGroup, NssUser, PamAuthRequest, PamAuthResponse, PamServiceInfo,
ProviderStatus,
};
use lru::LruCache;
use std::fmt::Display;
use std::num::NonZeroUsize;
use std::ops::DerefMut;
use std::path::{Path, PathBuf};
use std::string::ToString;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use time::OffsetDateTime;
use tokio::sync::Mutex;
use uuid::Uuid;
use kanidm_hsm_crypto::BoxedDynTpm;

View file

@ -1,538 +0,0 @@
use std::env;
use std::fmt::{Display, Formatter};
use std::fs::File;
use std::io::{ErrorKind, Read};
use std::path::{Path, PathBuf};
#[cfg(all(target_family = "unix", feature = "selinux"))]
use crate::selinux_util;
use kanidm_unix_common::unix_passwd::UnixIntegrationError;
pub(crate) use kanidm_unix_common::unix_config::{HomeAttr, UidAttr};
use serde::Deserialize;
use kanidm_unix_common::constants::*;
// Allowed as the large enum is only short lived at startup to the true config
#[allow(clippy::large_enum_variant)]
// This bit of magic lets us deserialise the old config and the new versions.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum ConfigUntagged {
Versioned(ConfigVersion),
Legacy(ConfigInt),
}
#[derive(Debug, Deserialize)]
#[serde(tag = "version")]
enum ConfigVersion {
#[serde(rename = "2")]
V2 {
#[serde(flatten)]
values: ConfigV2,
},
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ConfigV2 {
cache_db_path: Option<String>,
sock_path: Option<String>,
task_sock_path: Option<String>,
cache_timeout: Option<u64>,
default_shell: Option<String>,
home_prefix: Option<String>,
home_mount_prefix: Option<String>,
home_attr: Option<String>,
home_alias: Option<String>,
use_etc_skel: Option<bool>,
uid_attr_map: Option<String>,
gid_attr_map: Option<String>,
selinux: Option<bool>,
hsm_pin_path: Option<String>,
hsm_type: Option<String>,
tpm_tcti_name: Option<String>,
kanidm: Option<KanidmConfigV2>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct GroupMap {
pub local: String,
pub with: String,
}
#[derive(Debug, Deserialize)]
struct KanidmConfigV2 {
conn_timeout: Option<u64>,
request_timeout: Option<u64>,
pam_allowed_login_groups: Option<Vec<String>>,
#[serde(default)]
map_group: Vec<GroupMap>,
}
#[derive(Debug, Deserialize)]
struct ConfigInt {
db_path: Option<String>,
sock_path: Option<String>,
task_sock_path: Option<String>,
conn_timeout: Option<u64>,
request_timeout: Option<u64>,
cache_timeout: Option<u64>,
pam_allowed_login_groups: Option<Vec<String>>,
default_shell: Option<String>,
home_prefix: Option<String>,
home_mount_prefix: Option<String>,
home_attr: Option<String>,
home_alias: Option<String>,
use_etc_skel: Option<bool>,
uid_attr_map: Option<String>,
gid_attr_map: Option<String>,
selinux: Option<bool>,
#[serde(default)]
allow_local_account_override: Vec<String>,
hsm_pin_path: Option<String>,
hsm_type: Option<String>,
tpm_tcti_name: Option<String>,
// Detect and warn on values in these places.
#[serde(default)]
cache_db_path: Option<toml::value::Value>,
#[serde(default)]
kanidm: Option<toml::value::Value>,
}
#[derive(Debug, Clone, Default)]
pub enum HsmType {
#[cfg_attr(not(feature = "tpm"), default)]
Soft,
#[cfg_attr(feature = "tpm", default)]
TpmIfPossible,
Tpm,
}
impl Display for HsmType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
HsmType::Soft => write!(f, "Soft"),
HsmType::TpmIfPossible => write!(f, "Tpm if possible"),
HsmType::Tpm => write!(f, "Tpm"),
}
}
}
#[derive(Debug)]
pub struct UnixdConfig {
pub cache_db_path: String,
pub sock_path: String,
pub task_sock_path: String,
pub cache_timeout: u64,
pub unix_sock_timeout: u64,
pub default_shell: String,
pub home_prefix: PathBuf,
pub home_mount_prefix: Option<PathBuf>,
pub home_attr: HomeAttr,
pub home_alias: Option<HomeAttr>,
pub use_etc_skel: bool,
pub uid_attr_map: UidAttr,
pub gid_attr_map: UidAttr,
pub selinux: bool,
pub hsm_type: HsmType,
pub hsm_pin_path: String,
pub tpm_tcti_name: String,
pub kanidm_config: Option<KanidmConfig>,
}
#[derive(Debug)]
pub struct KanidmConfig {
pub conn_timeout: u64,
pub request_timeout: u64,
pub pam_allowed_login_groups: Vec<String>,
pub map_group: Vec<GroupMap>,
}
impl Default for UnixdConfig {
fn default() -> Self {
UnixdConfig::new()
}
}
impl Display for UnixdConfig {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "cache_db_path: {}", &self.cache_db_path)?;
writeln!(f, "sock_path: {}", self.sock_path)?;
writeln!(f, "task_sock_path: {}", self.task_sock_path)?;
writeln!(f, "unix_sock_timeout: {}", self.unix_sock_timeout)?;
writeln!(f, "cache_timeout: {}", self.cache_timeout)?;
writeln!(f, "default_shell: {}", self.default_shell)?;
writeln!(f, "home_prefix: {:?}", self.home_prefix)?;
match self.home_mount_prefix.as_deref() {
Some(val) => writeln!(f, "home_mount_prefix: {:?}", val)?,
None => writeln!(f, "home_mount_prefix: unset")?,
}
writeln!(f, "home_attr: {}", self.home_attr)?;
match self.home_alias {
Some(val) => writeln!(f, "home_alias: {}", val)?,
None => writeln!(f, "home_alias: unset")?,
}
writeln!(f, "uid_attr_map: {}", self.uid_attr_map)?;
writeln!(f, "gid_attr_map: {}", self.gid_attr_map)?;
writeln!(f, "hsm_type: {}", self.hsm_type)?;
writeln!(f, "tpm_tcti_name: {}", self.tpm_tcti_name)?;
writeln!(f, "selinux: {}", self.selinux)?;
if let Some(kconfig) = &self.kanidm_config {
writeln!(f, "kanidm: enabled")?;
writeln!(
f,
"kanidm pam_allowed_login_groups: {:#?}",
kconfig.pam_allowed_login_groups
)?;
writeln!(f, "kanidm conn_timeout: {}", kconfig.conn_timeout)?;
writeln!(f, "kanidm request_timeout: {}", kconfig.request_timeout)?;
} else {
writeln!(f, "kanidm: disabled")?;
};
Ok(())
}
}
impl UnixdConfig {
pub fn new() -> Self {
let cache_db_path = match env::var("KANIDM_CACHE_DB_PATH") {
Ok(val) => val,
Err(_) => DEFAULT_CACHE_DB_PATH.into(),
};
let hsm_pin_path = match env::var("KANIDM_HSM_PIN_PATH") {
Ok(val) => val,
Err(_) => DEFAULT_HSM_PIN_PATH.into(),
};
UnixdConfig {
cache_db_path,
sock_path: DEFAULT_SOCK_PATH.to_string(),
task_sock_path: DEFAULT_TASK_SOCK_PATH.to_string(),
unix_sock_timeout: DEFAULT_CONN_TIMEOUT * 2,
cache_timeout: DEFAULT_CACHE_TIMEOUT,
default_shell: DEFAULT_SHELL.to_string(),
home_prefix: DEFAULT_HOME_PREFIX.into(),
home_mount_prefix: None,
home_attr: DEFAULT_HOME_ATTR,
home_alias: DEFAULT_HOME_ALIAS,
use_etc_skel: DEFAULT_USE_ETC_SKEL,
uid_attr_map: DEFAULT_UID_ATTR_MAP,
gid_attr_map: DEFAULT_GID_ATTR_MAP,
selinux: DEFAULT_SELINUX,
hsm_pin_path,
hsm_type: HsmType::default(),
tpm_tcti_name: DEFAULT_TPM_TCTI_NAME.to_string(),
kanidm_config: None,
}
}
pub fn read_options_from_optional_config<P: AsRef<Path> + std::fmt::Debug>(
self,
config_path: P,
) -> Result<Self, UnixIntegrationError> {
debug!("Attempting to load configuration from {:#?}", &config_path);
let mut f = match File::open(&config_path) {
Ok(f) => {
debug!("Successfully opened configuration file {:#?}", &config_path);
f
}
Err(e) => {
match e.kind() {
ErrorKind::NotFound => {
debug!(
"Configuration file {:#?} not found, skipping.",
&config_path
);
}
ErrorKind::PermissionDenied => {
warn!(
"Permission denied loading configuration file {:#?}, skipping.",
&config_path
);
}
_ => {
debug!(
"Unable to open config file {:#?} [{:?}], skipping ...",
&config_path, e
);
}
};
return Ok(self);
}
};
let mut contents = String::new();
f.read_to_string(&mut contents).map_err(|e| {
error!("{:?}", e);
UnixIntegrationError
})?;
let config: ConfigUntagged = toml::from_str(contents.as_str()).map_err(|e| {
error!("{:?}", e);
UnixIntegrationError
})?;
match config {
ConfigUntagged::Legacy(config) => self.apply_from_config_legacy(config),
ConfigUntagged::Versioned(ConfigVersion::V2 { values }) => {
self.apply_from_config_v2(values)
}
}
}
fn apply_from_config_legacy(self, config: ConfigInt) -> Result<Self, UnixIntegrationError> {
if config.kanidm.is_some() || config.cache_db_path.is_some() {
error!("You are using version=\"2\" options in a legacy config. THESE WILL NOT WORK.");
return Err(UnixIntegrationError);
}
let map_group = config
.allow_local_account_override
.iter()
.map(|name| GroupMap {
local: name.clone(),
with: name.clone(),
})
.collect();
let kanidm_config = Some(KanidmConfig {
conn_timeout: config.conn_timeout.unwrap_or(DEFAULT_CONN_TIMEOUT),
request_timeout: config.request_timeout.unwrap_or(DEFAULT_CONN_TIMEOUT * 2),
pam_allowed_login_groups: config.pam_allowed_login_groups.unwrap_or_default(),
map_group,
});
// Now map the values into our config.
Ok(UnixdConfig {
cache_db_path: config.db_path.unwrap_or(self.cache_db_path),
sock_path: config.sock_path.unwrap_or(self.sock_path),
task_sock_path: config.task_sock_path.unwrap_or(self.task_sock_path),
unix_sock_timeout: DEFAULT_CONN_TIMEOUT * 2,
cache_timeout: config.cache_timeout.unwrap_or(self.cache_timeout),
default_shell: config.default_shell.unwrap_or(self.default_shell),
home_prefix: config
.home_prefix
.map(|p| p.into())
.unwrap_or(self.home_prefix.clone()),
home_mount_prefix: config.home_mount_prefix.map(|p| p.into()),
home_attr: config
.home_attr
.and_then(|v| match v.as_str() {
"uuid" => Some(HomeAttr::Uuid),
"spn" => Some(HomeAttr::Spn),
"name" => Some(HomeAttr::Name),
_ => {
warn!("Invalid home_attr configured, using default ...");
None
}
})
.unwrap_or(self.home_attr),
home_alias: config
.home_alias
.and_then(|v| match v.as_str() {
"none" => Some(None),
"uuid" => Some(Some(HomeAttr::Uuid)),
"spn" => Some(Some(HomeAttr::Spn)),
"name" => Some(Some(HomeAttr::Name)),
_ => {
warn!("Invalid home_alias configured, using default ...");
None
}
})
.unwrap_or(self.home_alias),
use_etc_skel: config.use_etc_skel.unwrap_or(self.use_etc_skel),
uid_attr_map: config
.uid_attr_map
.and_then(|v| match v.as_str() {
"spn" => Some(UidAttr::Spn),
"name" => Some(UidAttr::Name),
_ => {
warn!("Invalid uid_attr_map configured, using default ...");
None
}
})
.unwrap_or(self.uid_attr_map),
gid_attr_map: config
.gid_attr_map
.and_then(|v| match v.as_str() {
"spn" => Some(UidAttr::Spn),
"name" => Some(UidAttr::Name),
_ => {
warn!("Invalid gid_attr_map configured, using default ...");
None
}
})
.unwrap_or(self.gid_attr_map),
selinux: match config.selinux.unwrap_or(self.selinux) {
#[cfg(all(target_family = "unix", feature = "selinux"))]
true => selinux_util::supported(),
_ => false,
},
hsm_pin_path: config.hsm_pin_path.unwrap_or(self.hsm_pin_path),
hsm_type: config
.hsm_type
.and_then(|v| match v.as_str() {
"soft" => Some(HsmType::Soft),
"tpm_if_possible" => Some(HsmType::TpmIfPossible),
"tpm" => Some(HsmType::Tpm),
_ => {
warn!("Invalid hsm_type configured, using default ...");
None
}
})
.unwrap_or(self.hsm_type),
tpm_tcti_name: config
.tpm_tcti_name
.unwrap_or(DEFAULT_TPM_TCTI_NAME.to_string()),
kanidm_config,
})
}
fn apply_from_config_v2(self, config: ConfigV2) -> Result<Self, UnixIntegrationError> {
let kanidm_config = if let Some(kconfig) = config.kanidm {
Some(KanidmConfig {
conn_timeout: kconfig.conn_timeout.unwrap_or(DEFAULT_CONN_TIMEOUT),
request_timeout: kconfig.request_timeout.unwrap_or(DEFAULT_CONN_TIMEOUT * 2),
pam_allowed_login_groups: kconfig.pam_allowed_login_groups.unwrap_or_default(),
map_group: kconfig.map_group,
})
} else {
None
};
// Now map the values into our config.
Ok(UnixdConfig {
cache_db_path: config.cache_db_path.unwrap_or(self.cache_db_path),
sock_path: config.sock_path.unwrap_or(self.sock_path),
task_sock_path: config.task_sock_path.unwrap_or(self.task_sock_path),
unix_sock_timeout: DEFAULT_CONN_TIMEOUT * 2,
cache_timeout: config.cache_timeout.unwrap_or(self.cache_timeout),
default_shell: config.default_shell.unwrap_or(self.default_shell),
home_prefix: config
.home_prefix
.map(|p| p.into())
.unwrap_or(self.home_prefix.clone()),
home_mount_prefix: config.home_mount_prefix.map(|p| p.into()),
home_attr: config
.home_attr
.and_then(|v| match v.as_str() {
"uuid" => Some(HomeAttr::Uuid),
"spn" => Some(HomeAttr::Spn),
"name" => Some(HomeAttr::Name),
_ => {
warn!("Invalid home_attr configured, using default ...");
None
}
})
.unwrap_or(self.home_attr),
home_alias: config
.home_alias
.and_then(|v| match v.as_str() {
"none" => Some(None),
"uuid" => Some(Some(HomeAttr::Uuid)),
"spn" => Some(Some(HomeAttr::Spn)),
"name" => Some(Some(HomeAttr::Name)),
_ => {
warn!("Invalid home_alias configured, using default ...");
None
}
})
.unwrap_or(self.home_alias),
use_etc_skel: config.use_etc_skel.unwrap_or(self.use_etc_skel),
uid_attr_map: config
.uid_attr_map
.and_then(|v| match v.as_str() {
"spn" => Some(UidAttr::Spn),
"name" => Some(UidAttr::Name),
_ => {
warn!("Invalid uid_attr_map configured, using default ...");
None
}
})
.unwrap_or(self.uid_attr_map),
gid_attr_map: config
.gid_attr_map
.and_then(|v| match v.as_str() {
"spn" => Some(UidAttr::Spn),
"name" => Some(UidAttr::Name),
_ => {
warn!("Invalid gid_attr_map configured, using default ...");
None
}
})
.unwrap_or(self.gid_attr_map),
selinux: match config.selinux.unwrap_or(self.selinux) {
#[cfg(all(target_family = "unix", feature = "selinux"))]
true => selinux_util::supported(),
_ => false,
},
hsm_pin_path: config.hsm_pin_path.unwrap_or(self.hsm_pin_path),
hsm_type: config
.hsm_type
.and_then(|v| match v.as_str() {
"soft" => Some(HsmType::Soft),
"tpm_if_possible" => Some(HsmType::TpmIfPossible),
"tpm" => Some(HsmType::Tpm),
_ => {
warn!("Invalid hsm_type configured, using default ...");
None
}
})
.unwrap_or(self.hsm_type),
tpm_tcti_name: config
.tpm_tcti_name
.unwrap_or(DEFAULT_TPM_TCTI_NAME.to_string()),
kanidm_config,
})
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
#[test]
fn test_load_example_configs() {
// Test the various included configs
let examples_dir = env!("CARGO_MANIFEST_DIR").to_string() + "/../../examples/";
for file in PathBuf::from(&examples_dir)
.canonicalize()
.expect(&format!("Can't find examples dir at {}", examples_dir))
.read_dir()
.expect("Can't read examples dir!")
{
let file = file.unwrap();
let filename = file.file_name().into_string().unwrap();
if filename.starts_with("unixd") {
print!("Checking that {} parses as a valid config...", filename);
UnixdConfig::new()
.read_options_from_optional_config(file.path())
.inspect_err(|e| {
println!("Failed to parse: {:?}", e);
})
.expect("Failed to parse!");
println!("OK");
}
}
}
}

View file

@ -12,13 +12,13 @@ use kanidm_unix_common::constants::{
DEFAULT_GID_ATTR_MAP, DEFAULT_HOME_ALIAS, DEFAULT_HOME_ATTR, DEFAULT_HOME_PREFIX,
DEFAULT_SHELL, DEFAULT_UID_ATTR_MAP,
};
use kanidm_unix_common::unix_config::{GroupMap, KanidmConfig};
use kanidm_unix_common::unix_passwd::{CryptPw, EtcGroup, EtcShadow, EtcUser};
use kanidm_unix_resolver::db::{Cache, Db};
use kanidm_unix_resolver::idprovider::interface::Id;
use kanidm_unix_resolver::idprovider::kanidm::KanidmProvider;
use kanidm_unix_resolver::idprovider::system::SystemProvider;
use kanidm_unix_resolver::resolver::Resolver;
use kanidm_unix_resolver::unix_config::{GroupMap, KanidmConfig};
use kanidmd_core::config::{Configuration, IntegrationTestConfig, ServerRole};
use kanidmd_core::create_server_core;
use kanidmd_testkit::{is_free_port, PORT_ALLOC};