The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Validate LDAP server certificates and normalize synced attributes (#81039)
bryan72987c24bc46
diff --git a/e2e/test/scenarios/admin-2/sso/ldap.cy.spec.js b/e2e/test/scenarios/admin-2/sso/ldap.cy.spec.jsindex 6581655f553..a6db5fbb49b 100644--- a/e2e/test/scenarios/admin-2/sso/ldap.cy.spec.js+++ b/e2e/test/scenarios/admin-2/sso/ldap.cy.spec.js@@ -203,6 +203,10 @@ describe(it("should allow user login on EE when LDAP is enabled", () => {H.setupLdap();+ // Only allowlisted directory attributes are synced, so name the ones this test checks.+ cy.request("PUT", "/api/setting/ldap-sync-user-attributes-allowlist", {+ value: "uid,homedirectory",+ });cy.signOut();cy.visit("/auth/login");cy.findByLabelText("Username or email address").type(diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/ldap.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/ldap.cljindex 7129db8c15f..67d9265dab0 100644--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/ldap.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/ldap.clj@@ -14,9 +14,23 @@[:merge sso/LDAPUserInfo[:map [:attributes [:maybe [:map-of :string :any]]]]])-(defn- syncable-user-attributes [m]+(defn- syncable-user-attributes+ "Directory attributes to sync onto the user. Only attributes named in the allowlist are kept, so an+ empty allowlist syncs nothing; `:objectclass` and the configured blacklist are always dropped.+ Surviving attributes are normalized by+ [[metabase-enterprise.sso.integrations.sso-utils/stringify-valid-attributes]]."+ [m](when (ee.sso.settings/ldap-sync-user-attributes)- (apply dissoc m :objectclass (map (comp keyword u/lower-case-en) (ee.sso.settings/ldap-sync-user-attributes-blacklist)))))+ (let [allowlist (set (map u/lower-case-en (ee.sso.settings/ldap-sync-user-attributes-allowlist)))+ blocked (into #{:objectclass}+ (map (comp keyword u/lower-case-en))+ (ee.sso.settings/ldap-sync-user-attributes-blacklist))]+ (->> m+ (remove (fn [[k _]]+ (let [k-lower (u/lower-case-en (name k))]+ (or (contains? blocked (keyword k-lower))+ (not (contains? allowlist k-lower))))))+ sso-utils/stringify-valid-attributes))))(defenterprise-schema find-user :- [:maybe EEUserInfo]"Get user information for the supplied username."@@ -30,7 +44,7 @@resultsettings(ee.sso.settings/ldap-group-membership-filter))]- (assoc user-info :attributes (some-> (syncable-user-attributes result) (update-keys name))))))+ (assoc user-info :attributes (syncable-user-attributes result)))))(defenterprise check-provision-ldap"Throw if creating new users from ldap is disallowed."diff --git a/enterprise/backend/src/metabase_enterprise/sso/settings.clj b/enterprise/backend/src/metabase_enterprise/sso/settings.cljindex 9ad8c227fd0..a168ce71b78 100644--- a/enterprise/backend/src/metabase_enterprise/sso/settings.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/settings.clj@@ -349,6 +349,14 @@ on your IdP, this usually looks something like `http://www.example.com/141xkex60:type :csv:audit :getter)+(defsetting ldap-sync-user-attributes-allowlist+ (deferred-tru "Comma-separated list of user attributes to sync for LDAP users. Only these attributes are synced; leave blank to sync none.")+ :encryption :no+ :default ""+ :type :csv+ :export? false+ :audit :getter)+(defsetting ldap-group-membership-filter(deferred-tru "Group membership lookup filter. The placeholders '{dn}' and '{uid}' will be replaced by the user''s Distinguished Name and UID, respectively."):encryption :when-encryption-key-setdiff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.cljindex 864e5fa76dd..8e89ccee7b3 100644--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.sso.integrations.ldap-test(:require[clojure.test :refer :all]+ [metabase-enterprise.sso.integrations.ldap :as ee.ldap][metabase-enterprise.sso.settings :as sso-settings][metabase.appearance.settings :as appearance.settings][metabase.auth-identity.core :as auth-identity]@@ -13,6 +14,7 @@(use-fixtures :once (fixtures/initialize :db :test-users))(deftest find-test+ ;; No attribute allowlist is configured, so `:attributes` is empty for every user.(mt/with-premium-features #{:sso-ldap}(ldap.test/with-ldap-server!(testing "find by username"@@ -20,11 +22,7 @@:first-name "John":last-name "Smith":email "[email protected]"- :attributes {"uid" "jsmith1"- "mail" "[email protected]"- "givenname" "John"- "sn" "Smith"- "cn" "John Smith"}+ :attributes {}:groups ["cn=Accounting,ou=Groups,dc=metabase,dc=com"]}(ldap/find-user "jsmith1"))))(testing "find by email"@@ -32,11 +30,7 @@:first-name "John":last-name "Smith":email "[email protected]"- :attributes {"uid" "jsmith1"- "mail" "[email protected]"- "givenname" "John"- "sn" "Smith"- "cn" "John Smith"}+ :attributes {}:groups ["cn=Accounting,ou=Groups,dc=metabase,dc=com"]}(ldap/find-user "[email protected]"))))(testing "find by email, no groups"@@ -44,10 +38,7 @@:first-name "Fred":last-name "Taylor":email "[email protected]"- :attributes {"mail" "[email protected]"- "cn" "Fred Taylor"- "givenname" "Fred"- "sn" "Taylor"}+ :attributes {}:groups ["cn=Accounting,ou=Groups,dc=metabase,dc=com"]}(ldap/find-user "[email protected]"))))(testing "find by email, no givenName"@@ -55,10 +46,7 @@:first-name nil:last-name "Miller":email "[email protected]"- :attributes {"uid" "jmiller"- "mail" "[email protected]"- "cn" "Jane Miller"- "sn" "Miller"}+ :attributes {}:groups []}(ldap/find-user "[email protected]"))))(mt/with-temporary-setting-values [ldap-group-membership-filter "memberUid={uid}"]@@ -67,11 +55,7 @@:first-name "Sally":last-name "Brown":email "[email protected]"- :attributes {"uid" "sbrown20"- "mail" "[email protected]"- "givenname" "Sally"- "sn" "Brown"- "cn" "Sally Brown"}+ :attributes {}:groups ["cn=Engineering,ou=Groups,dc=metabase,dc=com"]}(ldap/find-user "sbrown20"))))(testing "find by email with custom group membership filter"@@ -79,32 +63,65 @@:first-name "Sally":last-name "Brown":email "[email protected]"- :attributes {"uid" "sbrown20"- "mail" "[email protected]"- "givenname" "Sally"- "sn" "Brown"- "cn" "Sally Brown"}+ :attributes {}:groups ["cn=Engineering,ou=Groups,dc=metabase,dc=com"]}(ldap/find-user "[email protected]"))))))))+(deftest syncable-user-attributes-test+ (testing "with an empty allowlist no attributes are synced"+ (mt/with-temporary-setting-values [ldap-sync-user-attributes true+ ldap-sync-user-attributes-blacklist ["userPassword" "dn" "distinguishedName"]+ ldap-sync-user-attributes-allowlist []]+ (is (= {}+ (#'ee.ldap/syncable-user-attributes+ {:objectclass ["top" "person"] :mail "[email protected]" :extra "x" :role "admin"})))))+ (testing "allowlisted directory attributes are filtered and normalized like SAML/JWT attributes"+ (mt/with-temporary-setting-values [ldap-sync-user-attributes true+ ldap-sync-user-attributes-blacklist ["userPassword" "dn" "distinguishedName"]+ ldap-sync-user-attributes-allowlist ["mail" "extra" "userPassword"]]+ (testing "objectclass and blacklisted keys are dropped (blacklist match is case-insensitive)"+ (is (= {"mail" "[email protected]" "extra" "x"}+ (#'ee.ldap/syncable-user-attributes+ {:objectclass ["top" "person"] :userpassword "secret" :mail "[email protected]" :extra "x"})))))+ (mt/with-temporary-setting-values [ldap-sync-user-attributes true+ ldap-sync-user-attributes-blacklist []+ ldap-sync-user-attributes-allowlist ["multi" "single" "blank" "nested" "@reserved"]]+ (testing "multi-value attributes are joined; nil/map values are dropped; @-prefixed keys are reserved"+ (is (= {"multi" "a,b" "single" "s"}+ (#'ee.ldap/syncable-user-attributes+ {:multi ["a" "b"] :single "s" :blank nil :nested {:k 1} (keyword "@reserved") "x"}))))))+ (testing "an allowlist restricts syncing to named keys (allowlist match is case-insensitive)"+ (mt/with-temporary-setting-values [ldap-sync-user-attributes true+ ldap-sync-user-attributes-blacklist []+ ldap-sync-user-attributes-allowlist ["Mail"]]+ (is (= {"mail" "[email protected]"}+ (#'ee.ldap/syncable-user-attributes {:mail "[email protected]" :other "nope"})))))+ (testing "when attribute sync is disabled nothing is returned"+ (mt/with-temporary-setting-values [ldap-sync-user-attributes false]+ (is (nil? (#'ee.ldap/syncable-user-attributes {:mail "[email protected]"}))))))+(deftest attribute-sync-test(mt/with-premium-features #{:sso-ldap}(ldap.test/with-ldap-server!- (testing "find by email/username should return other attributes as well"- (is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com"- :first-name "Lucky"- :last-name "Pigeon"- :email "[email protected]"- :attributes {"uid" "lucky"- "mail" "[email protected]"- "title" "King Pigeon"- "givenname" "Lucky"- "sn" "Pigeon"- "cn" "Lucky Pigeon"}- :groups []}- (ldap/find-user "lucky"))))- (testing "ignored attributes should not be returned"- (mt/with-temporary-setting-values [ldap-sync-user-attributes-blacklist+ (testing "find by email/username should return allowlisted attributes as well"+ (mt/with-temporary-setting-values [ldap-sync-user-attributes-allowlist+ ["uid" "mail" "title" "givenName" "sn" "cn"]]+ (is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com"+ :first-name "Lucky"+ :last-name "Pigeon"+ :email "[email protected]"+ :attributes {"uid" "lucky"+ "mail" "[email protected]"+ "title" "King Pigeon"+ "givenname" "Lucky"+ "sn" "Pigeon"+ "cn" "Lucky Pigeon"}+ :groups []}+ (ldap/find-user "lucky")))))+ (testing "blacklisted attributes should not be returned even when allowlisted"+ (mt/with-temporary-setting-values [ldap-sync-user-attributes-allowlist+ ["uid" "mail" "title" "givenName" "sn" "cn"]+ ldap-sync-user-attributes-blacklist(cons "title" (sso-settings/ldap-sync-user-attributes-blacklist))](is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com":first-name "Lucky"@@ -117,6 +134,16 @@"cn" "Lucky Pigeon"}:groups []}(ldap/find-user "lucky")))))+ (testing "when an allowlist is set, only allowlisted attributes are returned"+ (mt/with-temporary-setting-values [ldap-sync-user-attributes-allowlist ["uid" "mail"]]+ (is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com"+ :first-name "Lucky"+ :last-name "Pigeon"+ :email "[email protected]"+ :attributes {"uid" "lucky"+ "mail" "[email protected]"}+ :groups []}+ (ldap/find-user "lucky")))))(testing "if attribute sync is disabled, no attributes should come back at all"(mt/with-temporary-setting-values [ldap-sync-user-attributes false](is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com"@@ -131,27 +158,29 @@(mt/with-premium-features #{:sso-ldap}(mt/with-model-cleanup [:model/User](ldap.test/with-ldap-server!- (testing "when creating a new user via provider/login!, user attributes should get synced"- (let [result (auth-identity/login! :provider/ldap- {:username "jsmith1"- :password "strongpassword"- :device-info {:device_id "test-device"- :device_description "Test Device"- :ip_address "127.0.0.1"- :embedded false- :token_exchange false}})]- (is (true? (:success? result)))- (is (= {:first_name "John"- :last_name "Smith"- :email "[email protected]"- :login_attributes {"uid" "jsmith1"- "mail" "[email protected]"- "givenname" "John"- "sn" "Smith"- "cn" "John Smith"}- :common_name "John Smith"}- (into {} (t2/select-one [:model/User :first_name :last_name :email :login_attributes]- :email "[email protected]"))))))))))+ (testing "when creating a new user via provider/login!, allowlisted user attributes should get synced"+ (mt/with-temporary-setting-values [ldap-sync-user-attributes-allowlist+ ["uid" "mail" "givenName" "sn" "cn"]]+ (let [result (auth-identity/login! :provider/ldap+ {:username "jsmith1"+ :password "strongpassword"+ :device-info {:device_id "test-device"+ :device_description "Test Device"+ :ip_address "127.0.0.1"+ :embedded false+ :token_exchange false}})]+ (is (true? (:success? result)))+ (is (= {:first_name "John"+ :last_name "Smith"+ :email "[email protected]"+ :login_attributes {"uid" "jsmith1"+ "mail" "[email protected]"+ "givenname" "John"+ "sn" "Smith"+ "cn" "John Smith"}+ :common_name "John Smith"}+ (into {} (t2/select-one [:model/User :first_name :last_name :email :login_attributes]+ :email "[email protected]")))))))))))(deftest new-user-attributes-not-synced-when-disabled-test(mt/with-premium-features #{:sso-ldap}@@ -180,36 +209,38 @@(mt/with-premium-features #{:sso-ldap}(mt/with-model-cleanup [:model/User](ldap.test/with-ldap-server!- (testing "Existing user's attributes are updated via provider/login!"- (let [result1 (auth-identity/login! :provider/ldap- {:username "jsmith1"- :password "strongpassword"- :device-info {:device_id "test-device"- :device_description "Test Device"- :ip_address "127.0.0.1"- :embedded false- :token_exchange false}})- result2 (auth-identity/login! :provider/ldap- {:username "jsmith1"- :password "strongpassword"- :device-info {:device_id "test-device"- :device_description "Test Device"- :ip_address "127.0.0.1"- :embedded false- :token_exchange false}})]- (is (true? (:success? result1)))- (is (true? (:success? result2)))- (is (= {:first_name "John"- :last_name "Smith"- :common_name "John Smith"- :email "[email protected]"- :login_attributes {"uid" "jsmith1"- "mail" "[email protected]"- "givenname" "John"- "sn" "Smith"- "cn" "John Smith"}}- (into {} (t2/select-one [:model/User :first_name :last_name :email :login_attributes]- :email "[email protected]"))))))))))+ (testing "Existing user's allowlisted attributes are updated via provider/login!"+ (mt/with-temporary-setting-values [ldap-sync-user-attributes-allowlist+ ["uid" "mail" "givenName" "sn" "cn"]]+ (let [result1 (auth-identity/login! :provider/ldap+ {:username "jsmith1"+ :password "strongpassword"+ :device-info {:device_id "test-device"+ :device_description "Test Device"+ :ip_address "127.0.0.1"+ :embedded false+ :token_exchange false}})+ result2 (auth-identity/login! :provider/ldap+ {:username "jsmith1"+ :password "strongpassword"+ :device-info {:device_id "test-device"+ :device_description "Test Device"+ :ip_address "127.0.0.1"+ :embedded false+ :token_exchange false}})]+ (is (true? (:success? result1)))+ (is (true? (:success? result2)))+ (is (= {:first_name "John"+ :last_name "Smith"+ :common_name "John Smith"+ :email "[email protected]"+ :login_attributes {"uid" "jsmith1"+ "mail" "[email protected]"+ "givenname" "John"+ "sn" "Smith"+ "cn" "John Smith"}}+ (into {} (t2/select-one [:model/User :first_name :last_name :email :login_attributes]+ :email "[email protected]")))))))))))(deftest update-attributes-disabled-test(mt/with-premium-features #{:sso-ldap}diff --git a/src/metabase/sso/ldap.clj b/src/metabase/sso/ldap.cljindex 2f0cfb6b511..7c392b44838 100644--- a/src/metabase/sso/ldap.clj+++ b/src/metabase/sso/ldap.clj@@ -1,6 +1,7 @@(ns metabase.sso.ldap(:require[clj-ldap.client :as ldap]+ [clojure.string :as str][diehard.core :as dh][metabase.settings.core :as setting][metabase.sso.ldap.default-implementation :as default-impl]@@ -9,7 +10,10 @@[metabase.util.malli :as mu][metabase.util.malli.schema :as ms])(:import- (com.unboundid.ldap.sdk LDAPConnectionPool LDAPException)))+ (com.unboundid.ldap.sdk LDAPConnection LDAPConnectionOptions LDAPConnectionPool LDAPException+ SimpleBindRequest StartTLSPostConnectProcessor)+ (com.unboundid.ldap.sdk.extensions StartTLSExtendedRequest)+ (com.unboundid.util.ssl HostNameSSLSocketVerifier SSLUtil TrustAllTrustManager TrustStoreTrustManager)))(set! *warn-on-reflection* true)@@ -28,19 +32,33 @@:ldap-group-sync :group-sync:ldap-group-base :group-base})+(defn- default-trust-store-path+ "Path to the JVM's default CA trust store, honoring the standard+ `javax.net.ssl.trustStore` system property and otherwise falling back to+ `$JAVA_HOME/lib/security/cacerts`."+ []+ (or (not-empty (System/getProperty "javax.net.ssl.trustStore"))+ (str/join java.io.File/separator+ [(System/getProperty "java.home") "lib" "security" "cacerts"])))+(defn- details->ldap-options [{:keys [host port bind-dn password security]}](let [security (keyword security)port (if (string? port)(Integer/parseInt port)- port)]+ port)+ tls? (contains? #{:ssl :starttls} security)];; Connecting via IPv6 requires us to use this form for :host, otherwise;; clj-ldap will find the first : and treat it as an IPv4 and port number- {:host {:address host- :port port}- :bind-dn bind-dn- :password password- :ssl? (= security :ssl)- :startTLS? (= security :starttls)}))+ (cond-> {:host {:address host+ :port port}+ :bind-dn bind-dn+ :password password+ :ssl? (= security :ssl)+ :startTLS? (= security :starttls)}+ ;; Validate the server certificate against the operator-configured CA+ ;; store when set, otherwise the JVM default trust store.+ tls? (assoc :trust-store (or (sso.settings/ldap-trust-store)+ (default-trust-store-path))))))(defn- settings->ldap-options [](details->ldap-options {:host (sso.settings/ldap-host)@@ -49,6 +67,48 @@:password (sso.settings/ldap-password):security (sso.settings/ldap-security)}))+(defn- trust-manager+ ^javax.net.ssl.X509TrustManager [trust-store]+ (if trust-store+ (TrustStoreTrustManager. ^String trust-store)+ (TrustAllTrustManager.)))++(defn- ldap-connection-options+ "`LDAPConnectionOptions` configured to verify that the server certificate matches the host we+ connected to."+ ^LDAPConnectionOptions []+ (doto (LDAPConnectionOptions.)+ (.setSSLSocketVerifier (HostNameSSLSocketVerifier. true))))++(defn- connect-tls+ "Build a single-connection `LDAPConnectionPool` over SSL or StartTLS. Sets a hostname-verifying+ connection option so the server certificate is checked against the connected host in addition to+ being validated against the trust store."+ ^LDAPConnectionPool [{:keys [host bind-dn password ssl? startTLS? trust-store]}]+ (let [{:keys [address port]} host+ opt (ldap-connection-options)+ conn (if ssl?+ (LDAPConnection. (.createSSLSocketFactory (SSLUtil. (trust-manager trust-store)))+ opt ^String address (int (or port 636)))+ (doto (LDAPConnection. opt ^String address (int (or port 389)))+ (.processExtendedOperation+ (StartTLSExtendedRequest. (.createSSLContext (SSLUtil. (trust-manager trust-store)))))))+ bind-req (if bind-dn+ (SimpleBindRequest. ^String bind-dn ^String password)+ (SimpleBindRequest.))+ pcp (when startTLS?+ (StartTLSPostConnectProcessor. (.createSSLContext (SSLUtil. (trust-manager trust-store)))))]+ (.bind conn bind-req)+ (LDAPConnectionPool. conn 1 1 pcp)))++(defn- connect+ "Open an `LDAPConnectionPool` from an options map. TLS connections are built here so the server+ hostname is verified; plaintext connections are delegated to clj-ldap unchanged."+ ^LDAPConnectionPool [{:keys [ssl? startTLS?] :as options}]+ (if (or ssl? startTLS?)+ (connect-tls options)+ (ldap/connect options)))+(defn- get-connection"Connects to LDAP with the currently set settings and returns the connection."^LDAPConnectionPool@@ -56,7 +116,7 @@(let [options (settings->ldap-options)](log/debug "Opening LDAP connection")(try- (ldap/connect options)+ (connect options)(catch LDAPException e(log/errorf "Failed to obtain LDAP connection: %s" (.getMessage e))(throw e)))))@@ -92,7 +152,7 @@:group-base \"ou=Groups,dc=metabase,dc=com\"}"[{:keys [user-base group-base], :as details}](try- (with-open [^LDAPConnectionPool conn (ldap/connect (details->ldap-options details))]+ (with-open [^LDAPConnectionPool conn (connect (details->ldap-options details))](or(try(when-not (ldap/get conn user-base)diff --git a/src/metabase/sso/settings.clj b/src/metabase/sso/settings.cljindex f70da58c965..8e7f5c6a7a8 100644--- a/src/metabase/sso/settings.clj+++ b/src/metabase/sso/settings.clj@@ -35,6 +35,12 @@(assert (#{:none :ssl :starttls} (keyword new-value))))(setting/set-value-of-type! :keyword :ldap-security new-value)))+(defsetting ldap-trust-store+ (deferred-tru "Path to a JKS trust store of CA certificates used to validate the LDAP server''s TLS certificate. Leave blank to use the JVM default trust store.")+ :encryption :when-encryption-key-set+ :export? false+ :audit :getter)+(defsetting ldap-bind-dn(deferred-tru "The Distinguished Name to bind as (if any), this user will be used to lookup information about other users."):encryption :when-encryption-key-setdiff --git a/test/metabase/sso/ldap_tls_test.clj b/test/metabase/sso/ldap_tls_test.cljnew file mode 100644index 00000000000..3f8a4424d30--- /dev/null+++ b/test/metabase/sso/ldap_tls_test.clj@@ -0,0 +1,100 @@+(ns metabase.sso.ldap-tls-test+ "LDAPS/StartTLS connections validate the directory server's certificate against a trust store."+ (:require+ [clojure.java.io :as io]+ [clojure.test :refer :all]+ [metabase.sso.ldap :as ldap]+ [metabase.test :as mt])+ (:import+ (com.unboundid.ldap.listener InMemoryDirectoryServer+ InMemoryDirectoryServerConfig+ InMemoryListenerConfig+ SelfSignedCertificateGenerator)+ (com.unboundid.ldap.sdk LDAPConnectionOptions)+ (com.unboundid.util ObjectPair)+ (com.unboundid.util.ssl HostNameSSLSocketVerifier KeyStoreKeyManager SSLUtil TrustAllTrustManager)+ (java.io File)+ (java.security KeyStore Security)))++(set! *warn-on-reflection* true)++(defn- self-signed-keystore+ "Generate a temporary keystore holding a self-signed `localhost` certificate. Returns the+ UnboundID pair of [keystore-file password]. Uses the JVM default keystore type so the same file+ can back both the listener's key manager and a client trust store."+ []+ (SelfSignedCertificateGenerator/generateTemporarySelfSignedCertificate "localhost" (KeyStore/getDefaultType)))++(defn- start-ldaps-server!+ "Start an in-memory LDAPS directory whose listener presents `pair`'s self-signed certificate."+ ^InMemoryDirectoryServer [^ObjectPair pair]+ (let [key-mgr (KeyStoreKeyManager. ^File (.getFirst pair) ^chars (.getSecond pair))+ server-ssl (SSLUtil. key-mgr (TrustAllTrustManager.))+ client-ssl (SSLUtil. (TrustAllTrustManager.))+ listener (InMemoryListenerConfig/createLDAPSConfig+ "LDAPS" nil (int 0)+ (.createSSLServerSocketFactory server-ssl)+ (.createSSLSocketFactory client-ssl))+ base-dns ^"[Ljava.lang.String;" (into-array String ["dc=example,dc=com"])+ listeners ^"[Lcom.unboundid.ldap.listener.InMemoryListenerConfig;" (into-array InMemoryListenerConfig [listener])+ cfg (doto (InMemoryDirectoryServerConfig. base-dns)+ (.setListenerConfigs listeners))]+ (doto (InMemoryDirectoryServer. cfg)+ (.startListening))))++(defn- trust-store-with-cert!+ "Write a temp trust store whose only trusted entry is the certificate held in `pair`'s keystore, so+ a client configured with it validates the matching server. The LDAP client reads the trust store+ with a null password (clj-ldap's `TrustStoreTrustManager`), and JDK PKCS12 encrypts certificate+ entries by default — which a null-password read can't decrypt. So store the cert unencrypted, the+ way the JVM `cacerts` file is stored. Returns the trust store path."+ ^String [^ObjectPair pair]+ (let [pw ^chars (.getSecond pair)+ src ^KeyStore (doto ^KeyStore (KeyStore/getInstance (KeyStore/getDefaultType))+ (.load (io/input-stream (.getFirst pair)) pw))+ cert (.getCertificate src (first (enumeration-seq (.aliases src))))+ trust ^KeyStore (doto ^KeyStore (KeyStore/getInstance "pkcs12")+ (.load nil nil)+ (.setCertificateEntry "ldap-ca" cert))+ out ^File (File/createTempFile "ldap-trust" ".ks")+ cert-alg (Security/getProperty "keystore.pkcs12.certProtectionAlgorithm")+ mac-alg (Security/getProperty "keystore.pkcs12.macAlgorithm")]+ (try+ (Security/setProperty "keystore.pkcs12.certProtectionAlgorithm" "NONE")+ (Security/setProperty "keystore.pkcs12.macAlgorithm" "NONE")+ (with-open [os (io/output-stream out)]+ (.store trust os (char-array 0)))+ (finally+ (Security/setProperty "keystore.pkcs12.certProtectionAlgorithm" (or cert-alg "PBEWithHmacSHA256AndAES_256"))+ (Security/setProperty "keystore.pkcs12.macAlgorithm" (or mac-alg "HmacPBESHA256"))))+ (.getPath out)))++(deftest ldaps-verifies-server-hostname-test+ (testing "TLS connections are configured to verify the server certificate matches the connected host"+ (let [^LDAPConnectionOptions opt (#'ldap/ldap-connection-options)]+ (is (instance? HostNameSSLSocketVerifier (.getSSLSocketVerifier opt))+ "a hostname verifier must be installed so a certificate issued for another host is rejected"))))++(deftest ldaps-validates-server-certificate-test+ (let [pair (self-signed-keystore)+ ds (start-ldaps-server! pair)]+ (try+ (let [port (.getListenPort ds "LDAPS")+ ks-path (trust-store-with-cert! pair)]+ (testing "a certificate absent from the trust store fails the TLS handshake"+ (mt/with-temporary-setting-values [ldap-host "localhost"+ ldap-port port+ ldap-security :ssl]+ (is (thrown? Exception+ (with-open [^java.lang.AutoCloseable _conn (#'ldap/get-connection)]))+ "a certificate outside the trust store must not complete the TLS handshake")))+ (testing "a certificate present in the configured trust store connects (positive control)"+ (mt/with-temporary-setting-values [ldap-host "localhost"+ ldap-port port+ ldap-security :ssl+ ldap-trust-store ks-path]+ (with-open [^java.lang.AutoCloseable conn (#'ldap/get-connection)]+ (is (some? conn)+ "a certificate in the trust store must complete the handshake and connect")))))+ (finally+ (.shutDown ds true)))))