updates for active directory now with docs, noiw with microsoft AD sync

This commit is contained in:
Mark Gregory
2026-11-12 12:36:38 +00:00
parent 77b92027df
commit 9404c7a210
18 changed files with 884 additions and 3 deletions
+115
View File
@@ -0,0 +1,115 @@
APP_NAME=AD_Testrig
APP_ENV=local
APP_KEY=base64:2T9x1AAYIEjGQNr3Ihkj0UprtsSwv44phhKgLyIsRn8=
APP_DEBUG=true
APP_URL=https://adtest.vm
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE="ad_testing"
DB_USERNAME=root
DB_PASSWORD=987400Kmh
AD_HOST=192.168.122.50
AD_PORT=389
AD_BASE_DN="DC=ad,DC=test"
AD_USERNAME="[email protected]"
AD_PASSWORD="987400Kmh"
AD_USE_SSL=false
AD_USE_TLS=false
#Microsoft
#LDAP_HOST=192.168.122.50
#LDAP_PORT=636
LDAP_SSL=true
#LDAP_TLS=false
#LDAP_BASE_DN="DC=ad,DC=test"
LDAP_LOGGING=true
#LDAP_CONNECTION=default
#LDAP_HOST=127.0.0.1
#LDAP_PORT=1636
#LDAP_BASE_DN="DC=ad,DC=test"
#LDAP_USERNAME="CN=svc-laravel-sync,CN=Users,DC=ad,DC=test"
#LDAP_PASSWORD="aB1!mfOJfB2VVwks2dTCSlgwlQz7c3yBDxhcpVu4YSzhoT2f"
LDAP_TIMEOUT=5
#LDAP_SSL=false
#LDAP_TLS=true
#LDAP_TLS_CA_CERT="/Users/markgregory/Developer/Sites/Testing/AD_Testing/storage/app/private/ldap-samba-ca.pem"
LDAP_USERNAME="[email protected]"
LDAP_PASSWORD="987400Kmh"
LDAP_HOST=dc01.ad.test
LDAP_PORT=636
LDAP_TLS=true
LDAP_STARTTLS=false
LDAP_CONNECTION=default
#LDAP_HOST=dc01.ad.test
#LDAP_PORT=636
LDAP_BASE_DN="DC=ad,DC=test"
#LDAP_USERNAME="[email protected]"
#LDAP_TLS=true
#LDAP_STARTTLS=false
LDAP_SASL=false
LDAP_TLS_CA_CERT=certs/dc01-ad-test.pem
SESSION_DRIVER=redis
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=redis
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=predis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"
STYLIST_DEFAULT_THEME=backend
STYLIST_BACKEND_THEME=backend
STYLIST_FRONTEND_THEME=frontend
AD_SYNC_BASE_DN="OU=LaravelSync,DC=ad,DC=test"
AD_SYNC_SCHEDULED=true
AD_SYNC_ADMIN_ID=3
@@ -0,0 +1,141 @@
<?php
namespace Modules\ActiveDirectory\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Modules\ActiveDirectory\Services\ActiveDirectory;
use Modules\ActiveDirectory\Services\DirectorySyncHistory;
use Modules\ActiveDirectory\Services\DirectorySyncRejected;
use Modules\ActiveDirectory\Services\SyncDirectoryUsers;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
class SyncActiveDirectory extends Command
{
protected $signature = 'ad:sync {--email : Match directory accounts against existing Laravel user emails}
{--create-missing : Explicitly create users absent from Laravel}
{--dry-run : Preview changes without saving users}
{--debug : Print the LDAP account attributes returned by the sync search}
{--d|dump-ad : Print AD account properties returned by LDAP (-dd)}
{--deactivate-missing : Disable managed users absent from the snapshot}
{--reviewed-missing= : Apply only the missing users from the reviewed preview}';
protected $description = 'Synchronize local user records from Active Directory';
public function handle(SyncDirectoryUsers $sync, DirectorySyncHistory $history): int
{
$started = hrtime(true);
$context = [
'run_id' => (string) Str::uuid(),
'dry_run' => (bool) $this->option('dry-run'),
'deactivate_missing' => (bool) $this->option('deactivate-missing'),
'email' => (bool) $this->option('email'),
'create_missing' => (bool) $this->option('create-missing'),
];
$duration = fn (): int => (int) ((hrtime(true) - $started) / 1_000_000);
$review = $this->option('reviewed-missing');
$record = fn (string $status, ?array $counts = null, ?string $failure = null) => $history->record(
$context['run_id'], $status, $context['dry_run'], $context['deactivate_missing'], $duration(), $counts, $failure,
);
Log::info('Active Directory sync started.', $context);
$this->writeDetails('Sync options', $context, OutputInterface::VERBOSITY_VERBOSE);
try {
if ($review !== null && (! $context['deactivate_missing'] || $context['dry_run'])) {
throw new DirectorySyncRejected('A reviewed apply requires a live missing-user run.');
}
$lock = Cache::lock('ad:sync', 3600);
if (! $lock->get()) {
throw new DirectorySyncRejected('A directory sync is already running.');
}
try {
$result = $sync->run(
$context['dry_run'],
$context['deactivate_missing'],
$review,
$context['email'],
$context['create_missing'],
($this->option('debug') || $this->option('dump-ad')) ? $this->dumpDirectory(...) : null,
includeProperties: (bool) $this->option('dump-ad'),
);
} finally {
$lock->release();
}
} catch (DirectorySyncRejected $exception) {
Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage(), 'duration_ms' => $duration()]);
$record('rejected', failure: $exception->getMessage());
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
Log::error('Active Directory sync failed.', $context + [
'exception_type' => $exception::class,
'exception_code' => $exception->getCode(),
'duration_ms' => $duration(),
]);
$record('failed', failure: 'Directory or database error');
$this->error('Sync stopped due to a directory or database error.');
$this->writeDetails('Error', [
'type' => $exception::class,
'code' => $exception->getCode(),
], OutputInterface::VERBOSITY_DEBUG);
return self::FAILURE;
}
foreach ($result['changes'] as $change) {
Log::info('Active Directory sync user change.', $context + $change);
if ($this->output->isDebug()) {
$this->writeDetails('User change', $change, OutputInterface::VERBOSITY_DEBUG);
} else {
$this->writeDetails('User change', [
'action' => $change['action'],
'ad_guid' => $change['ad_guid'],
'changed_fields' => $change['changed_fields'],
], OutputInterface::VERBOSITY_VERY_VERBOSE);
}
}
$counts = $result['counts'];
Log::info('Active Directory sync completed.', $context + $counts + ['duration_ms' => $duration()]);
$record($review === null ? 'completed' : 'review_applied', $counts);
$this->writeDetails('Run duration', ['milliseconds' => $duration()], OutputInterface::VERBOSITY_VERBOSE);
$summary = [];
foreach ($counts as $key => $value) {
$summary[] = "$key=$value";
}
$this->info(($context['dry_run'] ? 'Dry run: ' : '').implode(' ', $summary));
return self::SUCCESS;
}
private function dumpDirectory(array $users): void
{
$debug = $this->option('debug');
if ($debug) {
$this->writeDetails('AD snapshot', ['base_dn' => ActiveDirectory::baseDn(), 'accounts' => count($users)]);
}
foreach ($users as $user) {
if ($this->option('dump-ad')) {
$this->writeDetails('AD properties', $user['ad_properties']);
}
if ($debug) {
unset($user['ad_properties']);
$this->writeDetails('AD account', $user);
}
}
}
private function writeDetails(string $label, array $details, int $verbosity = OutputInterface::VERBOSITY_NORMAL): void
{
if ($this->output->getVerbosity() >= $verbosity) {
$this->output->writeln($label.' '.json_encode($details, JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR), OutputInterface::OUTPUT_RAW);
}
}
}
@@ -0,0 +1,144 @@
<?php
namespace Modules\ActiveDirectory\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Modules\ActiveDirectory\Services\ActiveDirectory;
use Modules\ActiveDirectory\Services\DirectorySyncHistory;
use Modules\ActiveDirectory\Services\DirectorySyncRejected;
use Modules\ActiveDirectory\Services\SyncDirectoryUsers;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
class SyncActiveDirectory extends Command
{
protected $signature = 'ad:sync {--email : Match directory accounts against existing Laravel user emails}
{--create-missing : Explicitly create users absent from Laravel}
{--dry-run : Preview changes without saving users}
{--debug : Print the LDAP account attributes returned by the sync search}
{--d|dump-ad : Print AD account properties returned by LDAP (-dd)}
{--deactivate-missing : Disable managed users absent from the snapshot}
{--reviewed-missing= : Apply only the missing users from the reviewed preview}';
protected $description = 'Synchronize local user records from Active Directory';
public function handle(SyncDirectoryUsers $sync, DirectorySyncHistory $history): int
{
$started = hrtime(true);
$context = [
'run_id' => (string) Str::uuid(),
'dry_run' => (bool) $this->option('dry-run'),
'deactivate_missing' => (bool) $this->option('deactivate-missing'),
'email' => (bool) $this->option('email'),
'create_missing' => (bool) $this->option('create-missing'),
];
$duration = fn (): int => (int) ((hrtime(true) - $started) / 1_000_000);
$review = $this->option('reviewed-missing');
$record = fn (string $status, ?array $counts = null, ?string $failure = null) => $history->record(
$context['run_id'], $status, $context['dry_run'], $context['deactivate_missing'], $duration(), $counts, $failure,
);
Log::info('Active Directory sync started.', $context);
$this->writeDetails('Sync options', $context, OutputInterface::VERBOSITY_VERBOSE);
try {
if ($review !== null && (! $context['deactivate_missing'] || $context['dry_run'])) {
throw new DirectorySyncRejected('A reviewed apply requires a live missing-user run.');
}
$lock = Cache::lock('ad:sync', 3600);
if (! $lock->get()) {
throw new DirectorySyncRejected('A directory sync is already running.');
}
try {
$result = $sync->run(
$context['dry_run'],
$context['deactivate_missing'],
$review,
$context['email'],
$context['create_missing'],
($this->option('debug') || $this->option('dump-ad')) ? $this->dumpDirectory(...) : null,
includeProperties: (bool) $this->option('dump-ad'),
);
} finally {
$lock->release();
}
} catch (DirectorySyncRejected $exception) {
Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage(), 'duration_ms' => $duration()]);
$record('rejected', failure: $exception->getMessage());
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
Log::error('Active Directory sync failed.', $context + [
'exception_type' => $exception::class,
'exception_code' => $exception->getCode(),
'exception_message' => $exception->getMessage(),
'exception_file' => $exception->getFile(),
'exception_line' => $exception->getLine(),
'duration_ms' => $duration(),
]);
$record('failed', failure: 'Directory or database error');
$this->error('Sync stopped due to a directory or database error.');
$this->writeDetails('Error', [
'type' => $exception::class,
'code' => $exception->getCode(),
], OutputInterface::VERBOSITY_DEBUG);
return self::FAILURE;
}
foreach ($result['changes'] as $change) {
Log::info('Active Directory sync user change.', $context + $change);
if ($this->output->isDebug()) {
$this->writeDetails('User change', $change, OutputInterface::VERBOSITY_DEBUG);
} else {
$this->writeDetails('User change', [
'action' => $change['action'],
'ad_guid' => $change['ad_guid'],
'changed_fields' => $change['changed_fields'],
], OutputInterface::VERBOSITY_VERY_VERBOSE);
}
}
$counts = $result['counts'];
Log::info('Active Directory sync completed.', $context + $counts + ['duration_ms' => $duration()]);
$record($review === null ? 'completed' : 'review_applied', $counts);
$this->writeDetails('Run duration', ['milliseconds' => $duration()], OutputInterface::VERBOSITY_VERBOSE);
$summary = [];
foreach ($counts as $key => $value) {
$summary[] = "$key=$value";
}
$this->info(($context['dry_run'] ? 'Dry run: ' : '').implode(' ', $summary));
return self::SUCCESS;
}
private function dumpDirectory(array $users): void
{
$debug = $this->option('debug');
if ($debug) {
$this->writeDetails('AD snapshot', ['base_dn' => ActiveDirectory::baseDn(), 'accounts' => count($users)]);
}
foreach ($users as $user) {
if ($this->option('dump-ad')) {
$this->writeDetails('AD properties', $user['ad_properties']);
}
if ($debug) {
unset($user['ad_properties']);
$this->writeDetails('AD account', $user);
}
}
}
private function writeDetails(string $label, array $details, int $verbosity = OutputInterface::VERBOSITY_NORMAL): void
{
if ($this->output->getVerbosity() >= $verbosity) {
$this->output->writeln($label.' '.json_encode($details, JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR), OutputInterface::OUTPUT_RAW);
}
}
}
@@ -37,12 +37,20 @@ class ActiveDirectory
$cookie = '';
do {
$result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $attributes, controls: [[
$result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user)(mail=*))', $attributes, controls: [[
'oid' => LDAP_CONTROL_PAGEDRESULTS,
'iscritical' => true,
'value' => ['size' => 500, 'cookie' => $cookie],
]]);
if ($result === false) {
throw new RuntimeException(sprintf(
'Active Directory LDAP paged search failed (LDAP error %s: %s).',
(string) $ldap->errNo(),
ldap_err2str((int) $ldap->errNo())
));
}
try {
$response = $ldap->parseResult($result);
$next = $response ? ($response->controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? null) : null;
@@ -0,0 +1,103 @@
<?php
namespace Modules\ActiveDirectory\Services;
use LdapRecord\LdapInterface;
use LdapRecord\Models\ActiveDirectory\User;
use Modules\ActiveDirectory\Constants\AccountControl;
use RuntimeException;
class ActiveDirectory
{
private const ATTRIBUTES = ['objectguid', 'mail', 'displayname', 'cn', 'useraccountcontrol'];
private const DIAGNOSTIC_ATTRIBUTES = [
'distinguishedname', 'samaccountname', 'userprincipalname', 'givenname', 'sn',
'objectclass', 'memberof', 'whencreated', 'whenchanged', 'pwdlastset', 'lastlogontimestamp',
];
public static function baseDn(): string
{
$connection = config('ldap.default');
return trim((string) (config('ad-sync.base-dn') ?: config("ldap.connections.{$connection}.base_dn")));
}
/** @return list<array{guid: ?string, email: string, name: string, enabled: bool}> */
public function users(bool $includeProperties = false): array
{
$baseDn = self::baseDn();
if ($baseDn === '') {
throw new RuntimeException('An LDAP search base is required.');
}
return User::resolveConnection(config('ldap.default'))->run(function (LdapInterface $ldap) use ($baseDn, $includeProperties): array {
$attributes = $includeProperties ? [...self::ATTRIBUTES, ...self::DIAGNOSTIC_ATTRIBUTES] : self::ATTRIBUTES;
$entries = [];
$cookie = '';
do {
$result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $attributes, controls: [[
'oid' => LDAP_CONTROL_PAGEDRESULTS,
'iscritical' => true,
'value' => ['size' => 500, 'cookie' => $cookie],
]]);
try {
$response = $ldap->parseResult($result);
$next = $response ? ($response->controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? null) : null;
if (! $response || $response->failed() || $response->referrals || ! is_string($next)) {
throw new RuntimeException('LDAP returned an incomplete page.');
}
$page = $ldap->getEntries($result);
$count = $page['count'] ?? null;
if (! is_int($count) || $count !== count($page) - 1 || ($count === 0 && $next !== '')) {
throw new RuntimeException('LDAP returned invalid page entries.');
}
for ($index = 0; $index < $count; $index++) {
$user = (new User)->setRawAttributes($page[$index]);
$entry = $this->entry($user);
if ($includeProperties) {
$entry['ad_properties'] = ['objectguid' => $entry['guid']];
foreach (array_diff($attributes, ['objectguid']) as $attribute) {
$values = $user->getAttribute($attribute);
if ($values !== null) {
$entry['ad_properties'][$attribute] = $values;
}
}
}
$entries[] = $entry;
}
$cookie = $next;
} finally {
$ldap->freeResult($result);
}
} while ($cookie !== '');
return $entries;
});
}
/** @return array{guid: ?string, email: string, name: string, enabled: bool} */
private function entry(User $user): array
{
$flags = filter_var($user->getFirstAttribute('useraccountcontrol'), FILTER_VALIDATE_INT, [
'options' => ['min_range' => 0],
]);
if ($flags === false) {
throw new RuntimeException('Missing or invalid userAccountControl.');
}
return [
'guid' => $user->getConvertedGuid(),
'email' => (string) $user->getFirstAttribute('mail'),
'name' => (string) ($user->getFirstAttribute('displayname') ?: $user->getFirstAttribute('cn')),
'enabled' => ($flags & AccountControl::ACCOUNTDISABLE) === 0,
'account_control' => $flags,
'account_flags' => AccountControl::flags($flags),
];
}
}
@@ -0,0 +1,109 @@
<?php
namespace Modules\ActiveDirectory\Services;
use LdapRecord\LdapInterface;
use LdapRecord\Models\ActiveDirectory\User;
use Modules\ActiveDirectory\Constants\AccountControl;
use RuntimeException;
class ActiveDirectory
{
private const ATTRIBUTES = ['objectguid', 'mail', 'displayname', 'cn', 'useraccountcontrol'];
private const DIAGNOSTIC_ATTRIBUTES = [
'distinguishedname', 'samaccountname', 'userprincipalname', 'givenname', 'sn',
'objectclass', 'memberof', 'whencreated', 'whenchanged', 'pwdlastset', 'lastlogontimestamp',
];
public static function baseDn(): string
{
$connection = config('ldap.default');
return trim((string) (config('ad-sync.base-dn') ?: config("ldap.connections.{$connection}.base_dn")));
}
/** @return list<array{guid: ?string, email: string, name: string, enabled: bool}> */
public function users(bool $includeProperties = false): array
{
$baseDn = self::baseDn();
if ($baseDn === '') {
throw new RuntimeException('An LDAP search base is required.');
}
return User::resolveConnection(config('ldap.default'))->run(function (LdapInterface $ldap) use ($baseDn, $includeProperties): array {
$attributes = $includeProperties ? [...self::ATTRIBUTES, ...self::DIAGNOSTIC_ATTRIBUTES] : self::ATTRIBUTES;
$entries = [];
$cookie = '';
do {
$result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $attributes, controls: [[
'oid' => LDAP_CONTROL_PAGEDRESULTS,
'iscritical' => true,
'value' => ['size' => 500, 'cookie' => $cookie],
]]);
if ($result === false) {
throw new RuntimeException(
'Active Directory LDAP paged search failed before returning a result.'
);
}
try {
$response = $ldap->parseResult($result);
$next = $response ? ($response->controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? null) : null;
if (! $response || $response->failed() || $response->referrals || ! is_string($next)) {
throw new RuntimeException('LDAP returned an incomplete page.');
}
$page = $ldap->getEntries($result);
$count = $page['count'] ?? null;
if (! is_int($count) || $count !== count($page) - 1 || ($count === 0 && $next !== '')) {
throw new RuntimeException('LDAP returned invalid page entries.');
}
for ($index = 0; $index < $count; $index++) {
$user = (new User)->setRawAttributes($page[$index]);
$entry = $this->entry($user);
if ($includeProperties) {
$entry['ad_properties'] = ['objectguid' => $entry['guid']];
foreach (array_diff($attributes, ['objectguid']) as $attribute) {
$values = $user->getAttribute($attribute);
if ($values !== null) {
$entry['ad_properties'][$attribute] = $values;
}
}
}
$entries[] = $entry;
}
$cookie = $next;
} finally {
$ldap->freeResult($result);
}
} while ($cookie !== '');
return $entries;
});
}
/** @return array{guid: ?string, email: string, name: string, enabled: bool} */
private function entry(User $user): array
{
$flags = filter_var($user->getFirstAttribute('useraccountcontrol'), FILTER_VALIDATE_INT, [
'options' => ['min_range' => 0],
]);
if ($flags === false) {
throw new RuntimeException('Missing or invalid userAccountControl.');
}
return [
'guid' => $user->getConvertedGuid(),
'email' => (string) $user->getFirstAttribute('mail'),
'name' => (string) ($user->getFirstAttribute('displayname') ?: $user->getFirstAttribute('cn')),
'enabled' => ($flags & AccountControl::ACCOUNTDISABLE) === 0,
'account_control' => $flags,
'account_flags' => AccountControl::flags($flags),
];
}
}
@@ -0,0 +1,111 @@
<?php
namespace Modules\ActiveDirectory\Services;
use LdapRecord\LdapInterface;
use LdapRecord\Models\ActiveDirectory\User;
use Modules\ActiveDirectory\Constants\AccountControl;
use RuntimeException;
class ActiveDirectory
{
private const ATTRIBUTES = ['objectguid', 'mail', 'displayname', 'cn', 'useraccountcontrol'];
private const DIAGNOSTIC_ATTRIBUTES = [
'distinguishedname', 'samaccountname', 'userprincipalname', 'givenname', 'sn',
'objectclass', 'memberof', 'whencreated', 'whenchanged', 'pwdlastset', 'lastlogontimestamp',
];
public static function baseDn(): string
{
$connection = config('ldap.default');
return trim((string) (config('ad-sync.base-dn') ?: config("ldap.connections.{$connection}.base_dn")));
}
/** @return list<array{guid: ?string, email: string, name: string, enabled: bool}> */
public function users(bool $includeProperties = false): array
{
$baseDn = self::baseDn();
if ($baseDn === '') {
throw new RuntimeException('An LDAP search base is required.');
}
return User::resolveConnection(config('ldap.default'))->run(function (LdapInterface $ldap) use ($baseDn, $includeProperties): array {
$attributes = $includeProperties ? [...self::ATTRIBUTES, ...self::DIAGNOSTIC_ATTRIBUTES] : self::ATTRIBUTES;
$entries = [];
$cookie = '';
do {
$result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $attributes, controls: [[
'oid' => LDAP_CONTROL_PAGEDRESULTS,
'iscritical' => true,
'value' => ['size' => 500, 'cookie' => $cookie],
]]);
if ($result === false) {
throw new RuntimeException(sprintf(
'Active Directory LDAP paged search failed (LDAP error %s: %s).',
(string) $ldap->errNo(),
(string) $ldap->errMsg()
));
}
try {
$response = $ldap->parseResult($result);
$next = $response ? ($response->controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? null) : null;
if (! $response || $response->failed() || $response->referrals || ! is_string($next)) {
throw new RuntimeException('LDAP returned an incomplete page.');
}
$page = $ldap->getEntries($result);
$count = $page['count'] ?? null;
if (! is_int($count) || $count !== count($page) - 1 || ($count === 0 && $next !== '')) {
throw new RuntimeException('LDAP returned invalid page entries.');
}
for ($index = 0; $index < $count; $index++) {
$user = (new User)->setRawAttributes($page[$index]);
$entry = $this->entry($user);
if ($includeProperties) {
$entry['ad_properties'] = ['objectguid' => $entry['guid']];
foreach (array_diff($attributes, ['objectguid']) as $attribute) {
$values = $user->getAttribute($attribute);
if ($values !== null) {
$entry['ad_properties'][$attribute] = $values;
}
}
}
$entries[] = $entry;
}
$cookie = $next;
} finally {
$ldap->freeResult($result);
}
} while ($cookie !== '');
return $entries;
});
}
/** @return array{guid: ?string, email: string, name: string, enabled: bool} */
private function entry(User $user): array
{
$flags = filter_var($user->getFirstAttribute('useraccountcontrol'), FILTER_VALIDATE_INT, [
'options' => ['min_range' => 0],
]);
if ($flags === false) {
throw new RuntimeException('Missing or invalid userAccountControl.');
}
return [
'guid' => $user->getConvertedGuid(),
'email' => (string) $user->getFirstAttribute('mail'),
'name' => (string) ($user->getFirstAttribute('displayname') ?: $user->getFirstAttribute('cn')),
'enabled' => ($flags & AccountControl::ACCOUNTDISABLE) === 0,
'account_control' => $flags,
'account_flags' => AccountControl::flags($flags),
];
}
}
@@ -0,0 +1,111 @@
<?php
namespace Modules\ActiveDirectory\Services;
use LdapRecord\LdapInterface;
use LdapRecord\Models\ActiveDirectory\User;
use Modules\ActiveDirectory\Constants\AccountControl;
use RuntimeException;
class ActiveDirectory
{
private const ATTRIBUTES = ['objectguid', 'mail', 'displayname', 'cn', 'useraccountcontrol'];
private const DIAGNOSTIC_ATTRIBUTES = [
'distinguishedname', 'samaccountname', 'userprincipalname', 'givenname', 'sn',
'objectclass', 'memberof', 'whencreated', 'whenchanged', 'pwdlastset', 'lastlogontimestamp',
];
public static function baseDn(): string
{
$connection = config('ldap.default');
return trim((string) (config('ad-sync.base-dn') ?: config("ldap.connections.{$connection}.base_dn")));
}
/** @return list<array{guid: ?string, email: string, name: string, enabled: bool}> */
public function users(bool $includeProperties = false): array
{
$baseDn = self::baseDn();
if ($baseDn === '') {
throw new RuntimeException('An LDAP search base is required.');
}
return User::resolveConnection(config('ldap.default'))->run(function (LdapInterface $ldap) use ($baseDn, $includeProperties): array {
$attributes = $includeProperties ? [...self::ATTRIBUTES, ...self::DIAGNOSTIC_ATTRIBUTES] : self::ATTRIBUTES;
$entries = [];
$cookie = '';
do {
$result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $attributes, controls: [[
'oid' => LDAP_CONTROL_PAGEDRESULTS,
'iscritical' => true,
'value' => ['size' => 500, 'cookie' => $cookie],
]]);
if ($result === false) {
throw new RuntimeException(sprintf(
'Active Directory LDAP paged search failed (LDAP error %s: %s).',
(string) $ldap->errNo(),
ldap_err2str((int) $ldap->errNo())
));
}
try {
$response = $ldap->parseResult($result);
$next = $response ? ($response->controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? null) : null;
if (! $response || $response->failed() || $response->referrals || ! is_string($next)) {
throw new RuntimeException('LDAP returned an incomplete page.');
}
$page = $ldap->getEntries($result);
$count = $page['count'] ?? null;
if (! is_int($count) || $count !== count($page) - 1 || ($count === 0 && $next !== '')) {
throw new RuntimeException('LDAP returned invalid page entries.');
}
for ($index = 0; $index < $count; $index++) {
$user = (new User)->setRawAttributes($page[$index]);
$entry = $this->entry($user);
if ($includeProperties) {
$entry['ad_properties'] = ['objectguid' => $entry['guid']];
foreach (array_diff($attributes, ['objectguid']) as $attribute) {
$values = $user->getAttribute($attribute);
if ($values !== null) {
$entry['ad_properties'][$attribute] = $values;
}
}
}
$entries[] = $entry;
}
$cookie = $next;
} finally {
$ldap->freeResult($result);
}
} while ($cookie !== '');
return $entries;
});
}
/** @return array{guid: ?string, email: string, name: string, enabled: bool} */
private function entry(User $user): array
{
$flags = filter_var($user->getFirstAttribute('useraccountcontrol'), FILTER_VALIDATE_INT, [
'options' => ['min_range' => 0],
]);
if ($flags === false) {
throw new RuntimeException('Missing or invalid userAccountControl.');
}
return [
'guid' => $user->getConvertedGuid(),
'email' => (string) $user->getFirstAttribute('mail'),
'name' => (string) ($user->getFirstAttribute('displayname') ?: $user->getFirstAttribute('cn')),
'enabled' => ($flags & AccountControl::ACCOUNTDISABLE) === 0,
'account_control' => $flags,
'account_flags' => AccountControl::flags($flags),
];
}
}
View File
Binary file not shown.
+19
View File
@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDITCCAgmgAwIBAgIQc2XGX1J6urtEu+UtVJjFXjANBgkqhkiG9w0BAQsFADAX
MRUwEwYDVQQDDAxkYzAxLmFkLnRlc3QwHhcNMjYxMTEyMTIwNTU2WhcNMjgxMTEy
MTIxNTU2WjAXMRUwEwYDVQQDDAxkYzAxLmFkLnRlc3QwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQDY6YNEyNgk53cuC9Kk4+boQZepfty7kmH5MG+44opy
iWgXGjr+mHTIGi8YGXGs6Fg/jmE7G7TuZ03MBGU5uVNBQwfh7QzHqqSE7V2meCtc
oHEVMkQGwzpHo9gDyQBT+BNL1aAzbVJQjGBM0L1m3LmLm5ol2V5ER4h4ar0vHLnL
8VOhuh/gIsC/5OKyyQTncBVAwWRrfk5qaev2pe0r391c75K0gq+MaVCGESJKJjPF
Bd+xVBc3kVw1PfOJeVSQcZFVSxhE6XCzmzo3+G9dHelpMjcqoZnVGpO5w2VQLtD5
xxJwlzprS/isC8kB7GFn3++rUvuf1QlHb8pKFfU0MqY1AgMBAAGjaTBnMA4GA1Ud
DwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwEwFwYDVR0R
BBAwDoIMZGMwMS5hZC50ZXN0MB0GA1UdDgQWBBRjYK6oUS3LqCAS0pG058zr8ryH
dTANBgkqhkiG9w0BAQsFAAOCAQEAwITKFsODns4GH4oX3vOyCVwvs0grWRKMuz+a
OulXkWkZXTFi9Z7ZeZTRsRRQkcVfG6kJ/WlYq86eXGdGtfb09hcF69ZUFckQMCxV
hq1TsT7jQuJkqrv4+RjB3cSjhTroM2FYYLgX24sppCGsns7UKz8YkTpxI+Qkc6K+
whAbbh8I+zvQzZl41/+7Ll+IZ3arwtXLkVKIK1Bremou3oym/qw7VgFGUabr+9ye
0MF8KUMz5N80nRTepJv1zag1BNffzcMqzMrAVIxMDf36jFzGuhLXeUHYq+b/qQgH
iF0oTa/tYLYa2IO9SRuKIyY5h0lRA9dfuc9nDn8XuNzHWL2ajw==
-----END CERTIFICATE-----
@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDITCCAgmgAwIBAgIQYzJXD5ybIp9A+XNv+4UBvzANBgkqhkiG9w0BAQsFADAX
MRUwEwYDVQQDDAxkYzAxLmFkLnRlc3QwHhcNMjYxMTEyMTk1MTQ4WhcNMjgxMTEy
MjAwMTQ4WjAXMRUwEwYDVQQDDAxkYzAxLmFkLnRlc3QwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQCWGs0jzoGYGgL4bjMuaBeyF1oyCQrLL754RtxxyC/N
S7YApYHOlCrfvSGu91lPQX00u/96CtmQvuk4IwTUSZtUOSL6FymzFoHh9A9F6QRz
wqY4uxlEF2X8mxa61sOjpbxHUfVUqdiOXYYit0Th6ddbN2o7KnG0OugYK3av8ve+
pdhKUYXMpa2oh+lpMjFgei5LXvXIf7RMQ5RMTlo1Yy8oS4FNoc5uixhj5TESDZDY
slrxEPNtQNW4tVgFtIkdHmPBMmfVwbhRZ5s9gYoHnNhnf3pKogQJh+Bhy/7+d/+c
d5J84etsF/fNi6hwqgI5UJaroE3RNtwXwKeCWSdMkR/VAgMBAAGjaTBnMA4GA1Ud
DwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwEwFwYDVR0R
BBAwDoIMZGMwMS5hZC50ZXN0MB0GA1UdDgQWBBRiCD6Iv9prOPIks3Mr0Igm44C0
/TANBgkqhkiG9w0BAQsFAAOCAQEAgX+xNQNLcMyGPpRyrmiFt97vbjsnLoBm9Hk8
Eo/JPZ8Yak/uurw+PyacLM30ikMrVeP1a+SJfmVvcbPFaqDLQ3IJQ0scYt2I65n/
33cESDCq8bDmARNrkHV6XR+zOT/79O1PscSw/asCjNwssz+d4ep3WIh15Eu5zbVE
PchERvww9lDnxzBj93BmCKKRYd79Lg0Kvn9bUl0zC5KA+b9wB3lyY39wIrK4lvVg
FtlgVP1WTcQcTahSFUoIP9Kt8dJDCdnRKWiMH2aCsaICkumbMETq/MUY1bAT99Ht
JopEDIO88iZ0ceRiSBFVmujFwSnqbt4NPL1d15ocCCsFO4t6dg==
-----END CERTIFICATE-----
+1 -1
View File
@@ -49,7 +49,7 @@
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/",
"Modules\\ActiveDirectory\\Tests\\": "Modules/ActiveDirectory/tests/"
"Modules\\ActiveDirectory\\Tests\\": "Modules/ActiveDirectory/Tests/"
}
},
"repositories": [
+1
View File
@@ -10,6 +10,7 @@
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
<directory>Modules/ActiveDirectory/Tests/Feature</directory>
</testsuite>
</testsuites>
<source>
+1 -1
View File
@@ -16,7 +16,7 @@ use Tests\TestCase;
pest()->extend(TestCase::class)
->use(RefreshDatabase::class)
->in('Feature');
->in('Feature', '../Modules/ActiveDirectory/Tests/Feature');
/*
|--------------------------------------------------------------------------