[ 'user_filter' => '(&(objectCategory=person)(objectClass=user)(|(sAMAccountName={username})(userPrincipalName={username})(mail={username})))', 'uid_attribute' => 'objectGUID', 'photo_attribute' => 'thumbnailPhoto', 'group_filter' => '(&(objectClass=group)(member:1.2.840.113556.1.4.1941:={dn}))', ], 'openldap' => [ 'user_filter' => '(&(objectClass=inetOrgPerson)(|(uid={username})(mail={username})))', 'uid_attribute' => 'entryUUID', 'photo_attribute' => 'jpegPhoto', 'group_filter' => '(|(&(objectClass=groupOfNames)(member={dn}))(&(objectClass=groupOfUniqueNames)(uniqueMember={dn}))(&(objectClass=posixGroup)(memberUid={username})))', ], ]; public const DEFAULT_MAPS = [ 'ad' => [ 'first_name' => 'givenName', 'last_name' => 'sn', 'email' => 'mail', 'job_title' => 'title', 'department' => 'department', 'location' => 'physicalDeliveryOfficeName', 'phone' => 'telephoneNumber', 'mobile' => 'mobile', ], 'openldap' => [ 'first_name' => 'givenName', 'last_name' => 'sn', 'email' => 'mail', 'job_title' => 'title', 'department' => 'ou', 'location' => 'l', 'phone' => 'telephoneNumber', 'mobile' => 'mobile', ], ]; /** Attribute, die nie als Text gespeichert oder angezeigt werden. */ private const BINARY = ['objectguid', 'objectsid', 'thumbnailphoto', 'jpegphoto', 'usercertificate', 'msexchmailboxguid', 'msexchmailboxsecuritydescriptor']; private const SECRET = ['userpassword', 'unicodepwd', 'ntpassword', 'lmpassword']; public function __construct(private readonly LdapConnector $connector) {} public function authenticate(IdentityProvider $provider, string $username, string $password): ExternalUser { $username = trim($username); if ($username === '' || $password === '' || str_contains($username, "\0")) { throw new IdentityException('Benutzername oder Passwort ist falsch.'); } $connection = $this->connectAsService($provider); $entry = $this->findUser($connection, $provider, $username); // Leeres Passwort wäre eine anonyme Anmeldung – oben ausgeschlossen. if (! $entry || ! $connection->bind($entry['dn'], $password)) { throw new IdentityException('Benutzername oder Passwort ist falsch.'); } if ($this->isDisabled($entry)) { throw new IdentityException('Ihr Konto ist im Verzeichnis deaktiviert. Bitte wenden Sie sich an die Administration.'); } // Für Gruppen und Vorgesetzte wieder als Dienstkonto. $this->bindService($connection, $provider); return $this->toExternal($connection, $provider, $entry, $username); } /** * Für „Verbindung testen“ im Admin: Dienstkonto prüfen und optional eine Person * nachschlagen (ohne Passwort). * * @return array{user: ?ExternalUser, dn: ?string} */ public function test(IdentityProvider $provider, ?string $username): array { $connection = $this->connectAsService($provider); if ($username === null || trim($username) === '') { return ['user' => null, 'dn' => null]; } $entry = $this->findUser($connection, $provider, trim($username)); if (! $entry) { throw new IdentityException('Verbindung in Ordnung, aber „'.trim($username).'“ wurde mit dem Suchfilter nicht gefunden.'); } return ['user' => $this->toExternal($connection, $provider, $entry, trim($username)), 'dn' => $entry['dn']]; } public function connectAsService(IdentityProvider $provider): LdapConnection { $hosts = preg_split('/[\s,;]+/', (string) $provider->setting('hosts'), -1, PREG_SPLIT_NO_EMPTY) ?: []; if ($hosts === [] || trim((string) $provider->setting('base_dn')) === '') { throw new IdentityException('Die LDAP-Anmeldung ist nicht vollständig eingerichtet.'); } $connection = $this->connector->connect([ 'hosts' => $hosts, 'port' => ((int) $provider->setting('port')) ?: null, 'encryption' => (string) $provider->setting('encryption', 'ldaps'), 'verify_tls' => (bool) $provider->setting('verify_tls', true), 'timeout' => 8, ]); $this->bindService($connection, $provider); return $connection; } /** * @return array{dn: string, attributes: array>}|null */ public function findUser(LdapConnection $connection, IdentityProvider $provider, string $username): ?array { $filter = str_replace('{username}', self::escape($username), $this->setting($provider, 'user_filter')); $entries = $connection->search((string) $provider->setting('base_dn'), $filter, ['*', '+', $this->setting($provider, 'uid_attribute')], 2); // Mehrdeutige Treffer nie anmelden. return count($entries) === 1 ? $entries[0] : null; } public function setting(IdentityProvider $provider, string $key): string { $value = trim((string) $provider->setting($key)); return $value !== '' ? $value : (self::PRESETS[$this->schema($provider)][$key] ?? ''); } public function schema(IdentityProvider $provider): string { return $provider->setting('schema') === 'openldap' ? 'openldap' : 'ad'; } /** * Wert für einen LDAP-Filter maskieren (RFC 4515). */ public static function escape(string $value): string { return strtr($value, ['\\' => '\5c', '*' => '\2a', '(' => '\28', ')' => '\29', "\0" => '\00']); } /** * objectGUID (binär, gemischte Byte-Reihenfolge) als Text. */ public static function guid(string $binary): string { if (strlen($binary) !== 16) { return $binary; } $hex = unpack('Va/v2b/n2c/Nd', $binary); return sprintf('%08x-%04x-%04x-%04x-%04x%08x', $hex['a'], $hex['b1'], $hex['b2'], $hex['c1'], $hex['c2'], $hex['d']); } private function bindService(LdapConnection $connection, IdentityProvider $provider): void { $dn = trim((string) $provider->setting('bind_dn')); if (! $connection->bind($dn !== '' ? $dn : null, $dn !== '' ? (string) $provider->setting('bind_password') : null)) { throw new IdentityException('Das Dienstkonto für das Verzeichnis wurde abgelehnt. Bitte wenden Sie sich an die Administration.'); } } /** * @param array{dn: string, attributes: array>} $entry */ private function isDisabled(array $entry): bool { $control = (int) ($entry['attributes']['useraccountcontrol'][0] ?? 0); return ($control & 2) === 2; } /** * @param array{dn: string, attributes: array>} $entry */ private function subject(IdentityProvider $provider, array $entry): string { $attribute = strtolower($this->setting($provider, 'uid_attribute')); $value = $entry['attributes'][$attribute][0] ?? null; if ($value === null || $value === '') { throw new IdentityException('Im Verzeichnis fehlt die eindeutige Kennung („'.$this->setting($provider, 'uid_attribute').'“).'); } return $attribute === 'objectguid' ? self::guid($value) : $value; } /** * @param array{dn: string, attributes: array>} $entry */ private function toExternal(LdapConnection $connection, IdentityProvider $provider, array $entry, string $username): ExternalUser { $attributes = array_diff_key($entry['attributes'], array_flip(self::SECRET)); $text = array_diff_key($attributes, array_flip(self::BINARY)); $text['dn'] = [$entry['dn']]; $profile = AttributeProfile::build($provider, $text, [ 'display_name' => 'displayName', 'first_name' => 'givenName', 'last_name' => 'sn', 'email' => 'mail', ]); if ($provider->syncsManager()) { $profile['manager_subject'] = $this->managerSubject($connection, $provider, $attributes['manager'][0] ?? null); } $photo = false; if ($provider->setting('sync_photo', false)) { $photo = $attributes[strtolower($this->setting($provider, 'photo_attribute'))][0] ?? null; } return new ExternalUser( subject: $this->subject($provider, $entry), profile: $profile, groups: $this->groups($connection, $provider, $entry, $username), attributes: $text, photo: $photo, ); } /** * Gruppen-DNs: direkt aus memberOf und – falls eingestellt – über eine Gruppensuche * (AD: inklusive verschachtelter Gruppen). * * @param array{dn: string, attributes: array>} $entry * @return list */ private function groups(LdapConnection $connection, IdentityProvider $provider, array $entry, string $username): array { $groups = $entry['attributes']['memberof'] ?? []; if ($provider->setting('group_search', true)) { $filter = strtr($this->setting($provider, 'group_filter'), [ '{dn}' => self::escape($entry['dn']), '{username}' => self::escape($username), ]); $base = trim((string) $provider->setting('group_base_dn')) ?: (string) $provider->setting('base_dn'); try { foreach ($connection->search($base, $filter, ['dn'], 1000) as $group) { $groups[] = $group['dn']; } } catch (IdentityException $e) { logger()->warning('LDAP-Gruppensuche fehlgeschlagen: '.$e->getMessage()); } } $unique = []; foreach ($groups as $dn) { $unique[strtolower($dn)] ??= $dn; } return array_values($unique); } private function managerSubject(LdapConnection $connection, IdentityProvider $provider, ?string $managerDn): ?string { if (! $managerDn) { return null; } $entry = $connection->read($managerDn, [$this->setting($provider, 'uid_attribute')]); try { return $entry ? $this->subject($provider, $entry) : null; } catch (IdentityException) { return null; } } }