public inbox for pdm-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Shannon Sterz <s.sterz@proxmox.com>
To: pdm-devel@lists.proxmox.com
Subject: [pdm-devel] [PATCH datacenter-manager 2/5] server: add ldap and active directory authenticators
Date: Tue, 16 Sep 2025 16:48:24 +0200	[thread overview]
Message-ID: <20250916144827.551806-9-s.sterz@proxmox.com> (raw)
In-Reply-To: <20250916144827.551806-1-s.sterz@proxmox.com>

so that these types of realms could be used to login.

Signed-off-by: Shannon Sterz <s.sterz@proxmox.com>
---
 lib/pdm-api-types/src/lib.rs |   7 ++
 server/Cargo.toml            |   1 +
 server/src/auth/ldap.rs      | 202 +++++++++++++++++++++++++++++++++++
 server/src/auth/mod.rs       |  17 ++-
 4 files changed, 226 insertions(+), 1 deletion(-)
 create mode 100644 server/src/auth/ldap.rs

diff --git a/lib/pdm-api-types/src/lib.rs b/lib/pdm-api-types/src/lib.rs
index a7eaa0d..a356614 100644
--- a/lib/pdm-api-types/src/lib.rs
+++ b/lib/pdm-api-types/src/lib.rs
@@ -349,8 +349,15 @@ pub enum RealmType {
     Pdm,
     /// An OpenID Connect realm
     OpenId,
+    /// An Active Directory realm
+    Ad,
+    /// An LDAP realm
+    Ldap,
 }
 
+serde_plain::derive_display_from_serialize!(RealmType);
+serde_plain::derive_fromstr_from_deserialize!(RealmType);
+
 #[api(
     properties: {
         realm: {
diff --git a/server/Cargo.toml b/server/Cargo.toml
index 9eefa0f..0dfcb6c 100644
--- a/server/Cargo.toml
+++ b/server/Cargo.toml
@@ -41,6 +41,7 @@ proxmox-base64.workspace = true
 proxmox-daemon.workspace = true
 proxmox-http = { workspace = true, features = [ "client-trait", "proxmox-async" ] } # pbs-client doesn't use these
 proxmox-lang.workspace = true
+proxmox-ldap.workspace = true
 proxmox-log.workspace = true
 proxmox-login.workspace = true
 proxmox-rest-server = { workspace = true, features = [ "templates" ] }
diff --git a/server/src/auth/ldap.rs b/server/src/auth/ldap.rs
new file mode 100644
index 0000000..8f2e57e
--- /dev/null
+++ b/server/src/auth/ldap.rs
@@ -0,0 +1,202 @@
+use std::future::Future;
+use std::net::IpAddr;
+use std::path::PathBuf;
+use std::pin::Pin;
+
+use anyhow::Error;
+use pdm_buildcfg::configdir;
+use proxmox_auth_api::api::Authenticator;
+use proxmox_ldap::types::{AdRealmConfig, LdapMode, LdapRealmConfig};
+use proxmox_ldap::{Config, Connection, ConnectionMode};
+use proxmox_router::http_bail;
+use serde_json::json;
+
+use pdm_api_types::UsernameRef;
+
+const LDAP_PASSWORDS_FILENAME: &str = configdir!("/ldap_passwords.json");
+
+#[allow(clippy::upper_case_acronyms)]
+pub(crate) struct LdapAuthenticator {
+    config: LdapRealmConfig,
+}
+
+impl LdapAuthenticator {
+    pub(crate) fn new(config: LdapRealmConfig) -> Self {
+        Self { config }
+    }
+}
+
+impl Authenticator for LdapAuthenticator {
+    /// Authenticate user in LDAP realm
+    fn authenticate_user<'a>(
+        &'a self,
+        username: &'a UsernameRef,
+        password: &'a str,
+        _client_ip: Option<&'a IpAddr>,
+    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'a>> {
+        Box::pin(async move {
+            let ldap_config = Self::api_type_to_config(&self.config)?;
+            let ldap = Connection::new(ldap_config);
+            ldap.authenticate_user(username.as_str(), password).await?;
+            Ok(())
+        })
+    }
+
+    fn store_password(
+        &self,
+        _username: &UsernameRef,
+        _password: &str,
+        _client_ip: Option<&IpAddr>,
+    ) -> Result<(), Error> {
+        http_bail!(
+            NOT_IMPLEMENTED,
+            "storing passwords is not implemented for LDAP realms"
+        );
+    }
+
+    fn remove_password(&self, _username: &UsernameRef) -> Result<(), Error> {
+        http_bail!(
+            NOT_IMPLEMENTED,
+            "removing passwords is not implemented for LDAP realms"
+        );
+    }
+}
+
+impl LdapAuthenticator {
+    pub fn api_type_to_config(config: &LdapRealmConfig) -> Result<Config, Error> {
+        Self::api_type_to_config_with_password(config, get_ldap_bind_password(&config.realm)?)
+    }
+
+    pub fn api_type_to_config_with_password(
+        config: &LdapRealmConfig,
+        password: Option<String>,
+    ) -> Result<Config, Error> {
+        let mut servers = vec![config.server1.clone()];
+        if let Some(server) = &config.server2 {
+            servers.push(server.clone());
+        }
+
+        let (ca_store, trusted_cert) = lookup_ca_store_or_cert_path(config.capath.as_deref());
+
+        Ok(Config {
+            servers,
+            port: config.port,
+            user_attr: config.user_attr.clone(),
+            base_dn: config.base_dn.clone(),
+            bind_dn: config.bind_dn.clone(),
+            bind_password: password,
+            tls_mode: ldap_to_conn_mode(config.mode.unwrap_or_default()),
+            verify_certificate: config.verify.unwrap_or_default(),
+            additional_trusted_certificates: trusted_cert,
+            certificate_store_path: ca_store,
+        })
+    }
+}
+
+pub struct AdAuthenticator {
+    config: AdRealmConfig,
+}
+
+impl AdAuthenticator {
+    pub(crate) fn new(config: AdRealmConfig) -> Self {
+        Self { config }
+    }
+
+    pub fn api_type_to_config(config: &AdRealmConfig) -> Result<Config, Error> {
+        Self::api_type_to_config_with_password(config, get_ldap_bind_password(&config.realm)?)
+    }
+
+    pub fn api_type_to_config_with_password(
+        config: &AdRealmConfig,
+        password: Option<String>,
+    ) -> Result<Config, Error> {
+        let mut servers = vec![config.server1.clone()];
+        if let Some(server) = &config.server2 {
+            servers.push(server.clone());
+        }
+
+        let (ca_store, trusted_cert) = lookup_ca_store_or_cert_path(config.capath.as_deref());
+
+        Ok(Config {
+            servers,
+            port: config.port,
+            user_attr: "sAMAccountName".to_owned(),
+            base_dn: config.base_dn.clone().unwrap_or_default(),
+            bind_dn: config.bind_dn.clone(),
+            bind_password: password,
+            tls_mode: ldap_to_conn_mode(config.mode.unwrap_or_default()),
+            verify_certificate: config.verify.unwrap_or_default(),
+            additional_trusted_certificates: trusted_cert,
+            certificate_store_path: ca_store,
+        })
+    }
+}
+
+impl Authenticator for AdAuthenticator {
+    /// Authenticate user in AD realm
+    fn authenticate_user<'a>(
+        &'a self,
+        username: &'a UsernameRef,
+        password: &'a str,
+        _client_ip: Option<&'a IpAddr>,
+    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'a>> {
+        Box::pin(async move {
+            let ldap_config = Self::api_type_to_config(&self.config)?;
+            let ldap = Connection::new(ldap_config);
+            ldap.authenticate_user(username.as_str(), password).await?;
+            Ok(())
+        })
+    }
+
+    fn store_password(
+        &self,
+        _username: &UsernameRef,
+        _password: &str,
+        _client_ip: Option<&IpAddr>,
+    ) -> Result<(), Error> {
+        http_bail!(
+            NOT_IMPLEMENTED,
+            "storing passwords is not implemented for Active Directory realms"
+        );
+    }
+
+    fn remove_password(&self, _username: &UsernameRef) -> Result<(), Error> {
+        http_bail!(
+            NOT_IMPLEMENTED,
+            "removing passwords is not implemented for Active Directory realms"
+        );
+    }
+}
+
+fn ldap_to_conn_mode(mode: LdapMode) -> ConnectionMode {
+    match mode {
+        LdapMode::Ldap => ConnectionMode::Ldap,
+        LdapMode::StartTls => ConnectionMode::StartTls,
+        LdapMode::Ldaps => ConnectionMode::Ldaps,
+    }
+}
+
+fn lookup_ca_store_or_cert_path(capath: Option<&str>) -> (Option<PathBuf>, Option<Vec<PathBuf>>) {
+    if let Some(capath) = capath {
+        let path = PathBuf::from(capath);
+        if path.is_dir() {
+            (Some(path), None)
+        } else {
+            (None, Some(vec![path]))
+        }
+    } else {
+        (None, None)
+    }
+}
+
+/// Retrieve stored LDAP bind password
+pub(super) fn get_ldap_bind_password(realm: &str) -> Result<Option<String>, Error> {
+    let data = proxmox_sys::fs::file_get_json(LDAP_PASSWORDS_FILENAME, Some(json!({})))?;
+
+    let password = data
+        .get(realm)
+        .and_then(|s| s.as_str())
+        .map(|s| s.to_owned());
+
+    Ok(password)
+}
diff --git a/server/src/auth/mod.rs b/server/src/auth/mod.rs
index a0e0a34..532350d 100644
--- a/server/src/auth/mod.rs
+++ b/server/src/auth/mod.rs
@@ -8,11 +8,13 @@ use std::sync::OnceLock;
 use anyhow::{bail, Error};
 
 use const_format::concatcp;
+use ldap::{AdAuthenticator, LdapAuthenticator};
 use proxmox_access_control::CachedUserInfo;
 use proxmox_auth_api::api::{Authenticator, LockedTfaConfig};
 use proxmox_auth_api::ticket::Ticket;
 use proxmox_auth_api::types::Authid;
 use proxmox_auth_api::{HMACKey, Keyring};
+use proxmox_ldap::types::{AdRealmConfig, LdapRealmConfig};
 use proxmox_rest_server::AuthError;
 use proxmox_router::UserInformation;
 use proxmox_tfa::api::{OpenUserChallengeData, TfaConfig};
@@ -22,6 +24,7 @@ use pdm_api_types::{RealmRef, Userid};
 pub mod certs;
 pub mod csrf;
 pub mod key;
+pub(crate) mod ldap;
 pub mod tfa;
 
 pub const TERM_PREFIX: &str = "PDMTERM";
@@ -182,7 +185,19 @@ pub(crate) fn lookup_authenticator(
             config_filename: pdm_buildcfg::configdir!("/access/shadow.json"),
             lock_filename: pdm_buildcfg::configdir!("/access/shadow.json.lock"),
         })),
-        realm => bail!("unknown realm '{}'", realm),
+        realm => {
+            if let Ok((domains, _digest)) = pdm_config::domains::config() {
+                if let Ok(config) = domains.lookup::<LdapRealmConfig>("ldap", realm) {
+                    return Ok(Box::new(LdapAuthenticator::new(config)));
+                }
+
+                if let Ok(config) = domains.lookup::<AdRealmConfig>("ad", realm) {
+                    return Ok(Box::new(AdAuthenticator::new(config)));
+                }
+            }
+
+            bail!("unknwon realm {realm}");
+        }
     }
 }
 
-- 
2.47.3



_______________________________________________
pdm-devel mailing list
pdm-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pdm-devel


  parent reply	other threads:[~2025-09-16 14:48 UTC|newest]

Thread overview: 13+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2025-09-16 14:48 [pdm-devel] [PATCH datacenter-manager/proxmox/yew-comp 00/11] Add LDAP and AD realm support to Proxmox Datacenter Manager Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH proxmox 1/1] ldap: add types and sync features Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH yew-comp 1/5] auth_view: add default column and allow setting ldap realms as default Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH yew-comp 2/5] utils: add pdm realm to `get_auth_domain_info` Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH yew-comp 3/5] auth_view/auth_edit_ldap: add support for active directory realms Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH yew-comp 4/5] auth_edit_ldap: add helpers to properly edit ad & ldap realms Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH yew-comp 5/5] auth_view: implement syncing ldap and ad realms Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH datacenter-manager 1/5] config: add domain config plugins for " Shannon Sterz
2025-09-16 14:48 ` Shannon Sterz [this message]
2025-09-16 14:48 ` [pdm-devel] [PATCH datacenter-manager 3/5] server: api: add api endpoints for configuring ldap & " Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH datacenter-manager 4/5] api/auth: add endpoint to start ldap sync jobs Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH datacenter-manager 5/5] ui: add a panel to allow handling realms Shannon Sterz
2025-09-19 10:02 ` [pdm-devel] [PATCH datacenter-manager/proxmox/yew-comp 00/11] Add LDAP and AD realm support to Proxmox Datacenter Manager Christoph Heiss

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20250916144827.551806-9-s.sterz@proxmox.com \
    --to=s.sterz@proxmox.com \
    --cc=pdm-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal