LDAPService   F
last analyzed

Complexity

Total Complexity 175

Size/Duplication

Total Lines 1214
Duplicated Lines 0 %

Importance

Changes 6
Bugs 0 Features 2
Metric Value
eloc 449
c 6
b 0
f 2
dl 0
loc 1214
rs 2
wmc 175

36 Methods

Rating   Name   Duplication   Size   Complexity  
B getGroups() 0 28 9
A getNodes() 0 17 4
A getNestedGroups() 0 17 5
A __construct() 0 3 1
A enabled() 0 4 1
A getUserByDN() 0 7 4
A getUsernameByEmail() 0 8 2
A getUserByUsername() 0 12 4
A getUserByEmail() 0 7 4
A getGateway() 0 3 1
A getGroupByDN() 0 7 4
A get_cache() 0 3 1
A getGroupByGUID() 0 7 4
B authenticate() 0 35 7
A setGateway() 0 3 1
A getLDAPGroupMembers() 0 12 4
A getUsers() 0 17 5
A flush() 0 5 1
A getUserByGUID() 0 7 4
A passwordHistoryWorkaround() 0 7 1
A getLogger() 0 3 1
B updateGroupFromLDAP() 0 34 6
A delete() 0 3 1
A update() 0 3 1
A deleteLDAPMember() 0 17 5
F updateLDAPGroupsForMember() 0 71 18
B createLDAPUser() 0 41 6
A addLDAPUserToGroup() 0 15 3
B setPassword() 0 42 6
A move() 0 3 1
B createLDAPGroup() 0 42 6
A add() 0 3 1
B updateLDAPFromMember() 0 57 10
D updateMemberGroups() 0 74 18
C updateMemberFromLDAP() 0 103 17
B processThumbnailPhoto() 0 59 8

How to fix   Complexity   

Complex Class

Complex classes like LDAPService often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use LDAPService, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace SilverStripe\LDAP\Services;
4
5
use Exception;
6
use Psr\Log\LoggerInterface;
7
use Psr\SimpleCache\CacheInterface;
8
use SilverStripe\Assets\File;
9
use SilverStripe\Assets\Folder;
10
use SilverStripe\Assets\Image;
11
use SilverStripe\Assets\Storage\AssetStore;
12
use SilverStripe\Core\Config\Config;
13
use SilverStripe\Core\Config\Configurable;
14
use SilverStripe\Core\Extensible;
15
use SilverStripe\Core\Flushable;
16
use SilverStripe\Core\Injector\Injectable;
17
use SilverStripe\Core\Injector\Injector;
18
use SilverStripe\LDAP\Model\LDAPGateway;
19
use SilverStripe\LDAP\Model\LDAPGroupMapping;
20
use SilverStripe\ORM\DataQuery;
21
use SilverStripe\ORM\FieldType\DBDatetime;
22
use SilverStripe\ORM\ValidationException;
23
use SilverStripe\ORM\ValidationResult;
24
use SilverStripe\Security\Group;
25
use SilverStripe\Security\Member;
26
use SilverStripe\Security\RandomGenerator;
27
use Zend\Ldap\Ldap;
28
29
/**
30
 * Class LDAPService
31
 *
32
 * Provides LDAP operations expressed in terms of the SilverStripe domain.
33
 * All other modules should access LDAP through this class.
34
 *
35
 * This class builds on top of LDAPGateway's detailed code by adding:
36
 * - caching
37
 * - data aggregation and restructuring from multiple lower-level calls
38
 * - error handling
39
 *
40
 * LDAPService relies on Zend LDAP module's data structures for some parameters and some return values.
41
 */
42
class LDAPService implements Flushable
43
{
44
    use Injectable;
45
    use Extensible;
46
    use Configurable;
47
48
    /**
49
     * @var array
50
     */
51
    private static $dependencies = [
52
        'gateway' => '%$' . LDAPGateway::class
53
    ];
54
55
    /**
56
     * If configured, only user objects within these locations will be exposed to this service.
57
     *
58
     * @var array
59
     * @config
60
     */
61
    private static $users_search_locations = [];
62
63
    /**
64
     * If configured, only group objects within these locations will be exposed to this service.
65
     * @var array
66
     *
67
     * @config
68
     */
69
    private static $groups_search_locations = [];
70
71
    /**
72
     * Location to create new users in (distinguished name).
73
     * @var string
74
     *
75
     * @config
76
     */
77
    private static $new_users_dn;
78
79
    /**
80
     * Location to create new groups in (distinguished name).
81
     * @var string
82
     *
83
     * @config
84
     */
85
    private static $new_groups_dn;
86
87
    /**
88
     * @var array
89
     */
90
    private static $_cache_nested_groups = [];
91
92
    /**
93
     * If this is configured to a "Code" value of a {@link Group} in SilverStripe, the user will always
94
     * be added to this group's membership when imported, regardless of any sort of group mappings.
95
     *
96
     * @var string
97
     * @config
98
     */
99
    private static $default_group;
100
101
    /**
102
     * For samba4 directory, there is no way to enforce password history on password resets.
103
     * This only happens with changePassword (which requires the old password).
104
     * This works around it by making the old password up and setting it administratively.
105
     *
106
     * A cleaner fix would be to use the LDAP_SERVER_POLICY_HINTS_OID connection flag,
107
     * but it's not implemented in samba https://bugzilla.samba.org/show_bug.cgi?id=12020
108
     *
109
     * @var bool
110
     */
111
    private static $password_history_workaround = false;
112
113
    /**
114
     * Get the cache object used for LDAP results. Note that the default lifetime set here
115
     * is 8 hours, but you can change that by adding configuration:
116
     *
117
     * <code>
118
     * SilverStripe\Core\Injector\Injector:
119
     *   Psr\SimpleCache\CacheInterface.ldap:
120
     *     constructor:
121
     *       defaultLifetime: 3600 # time in seconds
122
     * </code>
123
     *
124
     * @return Psr\SimpleCache\CacheInterface
0 ignored issues
show
Bug introduced by
The type SilverStripe\LDAP\Servic...pleCache\CacheInterface was not found. Did you mean Psr\SimpleCache\CacheInterface? If so, make sure to prefix the type with \.
Loading history...
125
     */
126
    public static function get_cache()
127
    {
128
        return Injector::inst()->get(CacheInterface::class . '.ldap');
129
    }
130
131
    /**
132
     * Flushes out the LDAP results cache when flush=1 is called.
133
     */
134
    public static function flush()
135
    {
136
        /** @var CacheInterface $cache */
137
        $cache = self::get_cache();
138
        $cache->clear();
139
    }
140
141
    /**
142
     * @var LDAPGateway
143
     */
144
    public $gateway;
145
146
    public function __construct()
147
    {
148
        $this->constructExtensions();
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\LDAP\Servic...::constructExtensions() has been deprecated: 4.0.0:5.0.0 Extensions and methods are now lazy-loaded ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

148
        /** @scrutinizer ignore-deprecated */ $this->constructExtensions();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
149
    }
150
151
    /**
152
     * Setter for gateway. Useful for overriding the gateway with a fake for testing.
153
     * @var LDAPGateway
154
     */
155
    public function setGateway($gateway)
156
    {
157
        $this->gateway = $gateway;
158
    }
159
160
    /**
161
     * Return the LDAP gateway currently in use. Can be strung together to access the underlying Zend\Ldap instance, or
162
     * the PHP ldap resource itself. For example:
163
     * - Get the Zend\Ldap object: $service->getGateway()->getLdap() // Zend\Ldap\Ldap object
164
     * - Get the underlying PHP ldap resource: $service->getGateway()->getLdap()->getResource() // php resource
165
     *
166
     * @return LDAPGateway
167
     */
168
    public function getGateway()
169
    {
170
        return $this->gateway;
171
    }
172
173
    /**
174
     * Checkes whether or not the service is enabled.
175
     *
176
     * @return bool
177
     */
178
    public function enabled()
179
    {
180
        $options = Config::inst()->get(LDAPGateway::class, 'options');
181
        return !empty($options);
182
    }
183
184
    /**
185
     * Authenticate the given username and password with LDAP.
186
     *
187
     * @param string $username
188
     * @param string $password
189
     *
190
     * @return array
191
     */
192
    public function authenticate($username, $password)
193
    {
194
        $result = $this->getGateway()->authenticate($username, $password);
195
        $messages = $result->getMessages();
196
197
        // all messages beyond the first one are for debugging and
198
        // not suitable to display to the user.
199
        foreach ($messages as $i => $message) {
200
            if ($i > 0) {
201
                $this->getLogger()->debug(str_replace("\n", "\n  ", $message));
202
            }
203
        }
204
205
        $message = $messages[0]; // first message is user readable, suitable for showing on login form
206
207
        // show better errors than the defaults for various status codes returned by LDAP
208
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_ACCOUNT_LOCKED_OUT') !== false) {
209
            $message = _t(
210
                __CLASS__ . '.ACCOUNTLOCKEDOUT',
211
                'Your account has been temporarily locked because of too many failed login attempts. ' .
212
                'Please try again later.'
213
            );
214
        }
215
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_LOGON_FAILURE') !== false) {
216
            $message = _t(
217
                __CLASS__ . '.INVALIDCREDENTIALS',
218
                'The provided details don\'t seem to be correct. Please try again.'
219
            );
220
        }
221
222
        return [
223
            'success' => $result->getCode() === 1,
224
            'identity' => $result->getIdentity(),
225
            'message' => $message,
226
            'code' => $result->getCode()
227
        ];
228
    }
229
230
    /**
231
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
232
     *
233
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
234
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
235
     * @return array
236
     */
237
    public function getNodes($cached = true, $attributes = [])
238
    {
239
        $cache = self::get_cache();
240
        $cacheKey = 'nodes' . md5(implode('', $attributes));
241
        $results = $cache->has($cacheKey);
242
243
        if (!$results || !$cached) {
244
            $results = [];
245
            $records = $this->getGateway()->getNodes(null, Ldap::SEARCH_SCOPE_SUB, $attributes);
246
            foreach ($records as $record) {
247
                $results[$record['dn']] = $record;
248
            }
249
250
            $cache->set($cacheKey, $results);
251
        }
252
253
        return $results;
254
    }
255
256
    /**
257
     * Return all AD groups in configured search locations, including all nested groups.
258
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
259
     * to use the default baseDn defined in the connection.
260
     *
261
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
262
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
263
     * @param string $indexBy Attribute to use as an index.
264
     * @return array
265
     */
266
    public function getGroups($cached = true, $attributes = [], $indexBy = 'dn')
267
    {
268
        $searchLocations = $this->config()->groups_search_locations ?: [null];
269
        $cache = self::get_cache();
270
        $cacheKey = 'groups' . md5(implode('', array_merge($searchLocations, $attributes)));
271
        $results = $cache->has($cacheKey);
272
273
        if (!$results || !$cached) {
274
            $results = [];
275
            foreach ($searchLocations as $searchLocation) {
276
                $records = $this->getGateway()->getGroups($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
277
                if (!$records) {
278
                    continue;
279
                }
280
281
                foreach ($records as $record) {
282
                    $results[$record[$indexBy]] = $record;
283
                }
284
            }
285
286
            $cache->set($cacheKey, $results);
287
        }
288
289
        if ($cached && $results === true) {
290
            $results = $cache->get($cacheKey);
291
        }
292
293
        return $results;
294
    }
295
296
    /**
297
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
298
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
299
     *
300
     * @param string $dn
301
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
302
     * @return array
303
     */
304
    public function getNestedGroups($dn, $attributes = [])
305
    {
306
        if (isset(self::$_cache_nested_groups[$dn])) {
307
            return self::$_cache_nested_groups[$dn];
308
        }
309
310
        $searchLocations = $this->config()->groups_search_locations ?: [null];
311
        $results = [];
312
        foreach ($searchLocations as $searchLocation) {
313
            $records = $this->getGateway()->getNestedGroups($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
314
            foreach ($records as $record) {
315
                $results[$record['dn']] = $record;
316
            }
317
        }
318
319
        self::$_cache_nested_groups[$dn] = $results;
320
        return $results;
321
    }
322
323
    /**
324
     * Get a particular AD group's data given a GUID.
325
     *
326
     * @param string $guid
327
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
328
     * @return array
329
     */
330
    public function getGroupByGUID($guid, $attributes = [])
331
    {
332
        $searchLocations = $this->config()->groups_search_locations ?: [null];
333
        foreach ($searchLocations as $searchLocation) {
334
            $records = $this->getGateway()->getGroupByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
335
            if ($records) {
336
                return $records[0];
337
            }
338
        }
339
    }
340
341
    /**
342
     * Get a particular AD group's data given a DN.
343
     *
344
     * @param string $dn
345
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
346
     * @return array
347
     */
348
    public function getGroupByDN($dn, $attributes = [])
349
    {
350
        $searchLocations = $this->config()->groups_search_locations ?: [null];
351
        foreach ($searchLocations as $searchLocation) {
352
            $records = $this->getGateway()->getGroupByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
353
            if ($records) {
354
                return $records[0];
355
            }
356
        }
357
    }
358
359
    /**
360
     * Return all AD users in configured search locations, including all users in nested groups.
361
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
362
     * to use the default baseDn defined in the connection.
363
     *
364
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
365
     * @return array
366
     */
367
    public function getUsers($attributes = [])
368
    {
369
        $searchLocations = $this->config()->users_search_locations ?: [null];
370
        $results = [];
371
372
        foreach ($searchLocations as $searchLocation) {
373
            $records = $this->getGateway()->getUsersWithIterator($searchLocation, $attributes);
374
            if (!$records) {
375
                continue;
376
            }
377
378
            foreach ($records as $record) {
379
                $results[$record['objectguid']] = $record;
380
            }
381
        }
382
383
        return $results;
384
    }
385
386
    /**
387
     * Get a specific AD user's data given a GUID.
388
     *
389
     * @param string $guid
390
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
391
     * @return array
392
     */
393
    public function getUserByGUID($guid, $attributes = [])
394
    {
395
        $searchLocations = $this->config()->users_search_locations ?: [null];
396
        foreach ($searchLocations as $searchLocation) {
397
            $records = $this->getGateway()->getUserByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
398
            if ($records) {
399
                return $records[0];
400
            }
401
        }
402
    }
403
404
    /**
405
     * Get a specific AD user's data given a DN.
406
     *
407
     * @param string $dn
408
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
409
     *
410
     * @return array
411
     */
412
    public function getUserByDN($dn, $attributes = [])
413
    {
414
        $searchLocations = $this->config()->users_search_locations ?: [null];
415
        foreach ($searchLocations as $searchLocation) {
416
            $records = $this->getGateway()->getUserByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
417
            if ($records) {
418
                return $records[0];
419
            }
420
        }
421
    }
422
423
    /**
424
     * Get a specific user's data given an email.
425
     *
426
     * @param string $email
427
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
428
     * @return array
429
     */
430
    public function getUserByEmail($email, $attributes = [])
431
    {
432
        $searchLocations = $this->config()->users_search_locations ?: [null];
433
        foreach ($searchLocations as $searchLocation) {
434
            $records = $this->getGateway()->getUserByEmail($email, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
435
            if ($records) {
436
                return $records[0];
437
            }
438
        }
439
    }
440
441
    /**
442
     * Get a specific user's data given a username.
443
     *
444
     * @param string $username
445
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
446
     * @return array
447
     */
448
    public function getUserByUsername($username, $attributes = [])
449
    {
450
        $searchLocations = $this->config()->users_search_locations ?: [null];
451
        foreach ($searchLocations as $searchLocation) {
452
            $records = $this->getGateway()->getUserByUsername(
453
                $username,
454
                $searchLocation,
455
                Ldap::SEARCH_SCOPE_SUB,
456
                $attributes
457
            );
458
            if ($records) {
459
                return $records[0];
460
            }
461
        }
462
    }
463
464
    /**
465
     * Get a username for an email.
466
     *
467
     * @param string $email
468
     * @return string|null
469
     */
470
    public function getUsernameByEmail($email)
471
    {
472
        $data = $this->getUserByEmail($email);
473
        if (empty($data)) {
474
            return null;
475
        }
476
477
        return $this->getGateway()->getCanonicalUsername($data);
478
    }
479
480
    /**
481
     * Given a group DN, get the group membership data in LDAP.
482
     *
483
     * @param string $dn
484
     * @return array
485
     */
486
    public function getLDAPGroupMembers($dn)
487
    {
488
        $groupObj = Group::get()->filter('DN', $dn)->first();
489
        $groupData = $this->getGroupByGUID($groupObj->GUID);
490
        $members = !empty($groupData['member']) ? $groupData['member'] : [];
491
        // If a user belongs to a single group, this comes through as a string.
492
        // Normalise to a array so it's consistent.
493
        if ($members && is_string($members)) {
494
            $members = [$members];
495
        }
496
497
        return $members;
498
    }
499
500
    /**
501
     * Update the current Member record with data from LDAP.
502
     *
503
     * It's allowed to pass an unwritten Member record here, because it's not always possible to satisfy
504
     * field constraints without importing data from LDAP (for example if the application requires Username
505
     * through a Validator). Even though unwritten, it still must have the GUID set.
506
     *
507
     * Constraints:
508
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
509
     *
510
     * @param Member $member
511
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
512
     *            If not given, the data will be looked up by the user's GUID.
513
     * @param bool $updateGroups controls whether to run the resource-intensive group update function as well. This is
514
     *                          skipped during login to reduce load.
515
     * @return bool
516
     * @internal param $Member
517
     */
518
    public function updateMemberFromLDAP(Member $member, $data = null, $updateGroups = true)
519
    {
520
        if (!$this->enabled()) {
521
            return false;
522
        }
523
524
        if (!$member->GUID) {
525
            $this->getLogger()->debug(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
526
            return false;
527
        }
528
529
        if (!$data) {
530
            $data = $this->getUserByGUID($member->GUID);
531
            if (!$data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
532
                $this->getLogger()->debug(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID));
533
                return false;
534
            }
535
        }
536
537
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
538
        $member->LastSynced = (string)DBDatetime::now();
539
540
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
541
            // Special handling required for attributes that don't exist in the response.
542
            if (!isset($data[$attribute])) {
543
                // a attribute we're expecting is missing from the LDAP response
544
                if ($this->config()->get("reset_missing_attributes")) {
545
                    // (Destructive) Reset the corresponding attribute on our side if instructed to do so.
546
                    if (method_exists($member->$field, "delete")
547
                        && method_exists($member->$field, "deleteFile")
548
                        && $member->$field->exists()
549
                    ) {
550
                        $member->$field->deleteFile();
551
                        $member->$field->delete();
552
                    } else {
553
                        $member->$field = null;
554
                    }
555
                // or log the information.
556
                } else {
557
                    $this->getLogger()->debug(
558
                        sprintf(
559
                            'Attribute %s configured in Member.ldap_field_mappings, ' .
560
                            'but no available attribute in AD data (GUID: %s, Member ID: %s)',
561
                            $attribute,
562
                            $data['objectguid'],
563
                            $member->ID
564
                        )
565
                    );
566
                }
567
568
                // No further processing required.
569
                continue;
570
            }
571
572
            if (in_array($attribute, $this->config()->photo_attributes)) {
573
                $this->processThumbnailPhoto($member, $field, $data, $attribute);
574
            } else {
575
                $member->$field = $data[$attribute];
576
            }
577
        }
578
579
        // this is to keep track of which group the user gets mapped to if there
580
        // is a default group defined so when they are removed from unmapped
581
        // groups in ->updateMemberGroups() they are not then removed from the
582
        // default group
583
        $mappedGroupIDs = [];
584
585
        // if a default group was configured, ensure the user is in that group
586
        if ($this->config()->default_group) {
587
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
588
            if (!($group && $group->exists())) {
589
                $this->getLogger()->debug(
590
                    sprintf(
591
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
592
                        $this->config()->default_group
593
                    )
594
                );
595
            } else {
596
                // The member must exist before we can use it as a relation:
597
                if (!$member->exists()) {
598
                    $member->write();
599
                }
600
601
                $group->Members()->add($member, [
602
                    'IsImportedFromLDAP' => '1'
603
                ]);
604
605
                $mappedGroupIDs[] = $group->ID;
606
            }
607
        }
608
609
        // Member must have an ID before manipulating Groups, otherwise they will not be added correctly.
610
        // However we cannot do a full ->write before the groups are associated, because this will upsync
611
        // the Member, in effect deleting all their LDAP group associations!
612
        $member->writeWithoutSync();
613
614
        if ($updateGroups) {
615
            $this->updateMemberGroups($data, $member, $mappedGroupIDs);
616
        }
617
618
        // This will throw an exception if there are two distinct GUIDs with the same email address.
619
        // We are happy with a raw 500 here at this stage.
620
        $member->write();
621
    }
622
623
    /**
624
     * Attempts to process the thumbnail photo for a given user and store it against a {@link Member} object. This will
625
     * overwrite any old file with the same name. The filename of the photo will be set to 'thumbnailphoto-<GUID>.jpg'.
626
     *
627
     * At the moment only JPEG files are supported, as this is mainly to support Active Directory, which always provides
628
     * the photo in a JPEG format, and always at a specific resolution.
629
     *
630
     * @param Member $member The SilverStripe Member object we are storing this file on
631
     * @param string $fieldName The SilverStripe field name we are storing this new file against
632
     * @param array $data Array of all data returned about this user from LDAP
633
     * @param string $attributeName Name of the attribute in the $data array to get the binary blog from
634
     * @return boolean true on success, false on failure
635
     *
636
     * @throws ValidationException
637
     */
638
    protected function processThumbnailPhoto(Member $member, $fieldName, $data, $attributeName)
639
    {
640
        $imageClass = $member->getRelationClass($fieldName);
641
        if ($imageClass !== Image::class && !is_subclass_of($imageClass, Image::class)) {
642
            $this->getLogger()->warning(
643
                sprintf(
644
                    'Member field %s configured for ' . $attributeName . ' AD attribute, but it isn\'t a valid relation to an '
645
                        . 'Image class',
646
                    $fieldName
647
                )
648
            );
649
650
            return false;
651
        }
652
653
        // Use and update existing Image object (if one exists), or create a new image if not - prevents ID thrashing
654
        /** @var File $existingObj */
655
        $existingObj = $member->getComponent($fieldName);
656
        if ($existingObj && $existingObj->exists()) {
657
            $file = $existingObj;
658
659
            // If the file hashes match, and the file already exists, we don't need to update anything.
660
            $hash = $existingObj->File->getHash();
661
            if (hash_equals($hash, sha1($data[$attributeName]))) {
662
                return true;
663
            }
664
        } else {
665
            $file = Image::create();
666
        }
667
668
        // Setup variables
669
        $thumbnailFolder = Folder::find_or_make($member->config()->ldap_thumbnail_path);
670
        $filename = sprintf($attributeName . '-%s.jpg', $data['objectguid']);
671
        $filePath = File::join_paths($thumbnailFolder->getFilename(), $filename);
672
        $fileCfg = [
673
            // if there's a filename conflict we've got new content so overwrite it.
674
            'conflict' => AssetStore::CONFLICT_OVERWRITE,
675
            'visibility' => AssetStore::VISIBILITY_PUBLIC
676
        ];
677
678
        if (isset($data['displayname'])) {
679
            $userName = $data['displayname'];
680
        } else {
681
            $userName = $member->Name;
682
        }
683
684
        $file->Title = sprintf('Thumbnail photo for %s', $userName);
685
        $file->ShowInSearch = false;
686
        $file->ParentID = $thumbnailFolder->ID;
687
        $file->setFromString($data[$attributeName], $filePath, null, null, $fileCfg);
688
        $file->write();
689
        $file->publishRecursive();
690
691
        if ($file->exists()) {
692
            $relationField = sprintf('%sID', $fieldName);
693
            $member->{$relationField} = $file->ID;
694
        }
695
696
        return true;
697
    }
698
699
    /**
700
     * Ensure the user is mapped to any applicable groups.
701
     * @param array $data
702
     * @param Member $member
703
     * @param array $mappedGroupsToKeep
704
     */
705
    public function updateMemberGroups($data, Member $member, $mappedGroupsToKeep = [])
706
    {
707
        // this is to keep track of which groups the user gets mapped to and
708
        // we'll use that later to remove them from any groups that they're no
709
        // longer mapped to
710
        $mappedGroupIDs = $mappedGroupsToKeep;
711
712
        if (isset($data['memberof'])) {
713
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : [$data['memberof']];
714
            foreach ($ldapGroups as $groupDN) {
715
                foreach (LDAPGroupMapping::get() as $mapping) {
716
                    if (!$mapping->DN) {
717
                        $this->getLogger()->debug(
718
                            sprintf(
719
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
720
                                $mapping->ID
721
                            )
722
                        );
723
                        continue;
724
                    }
725
726
                    // the user is a direct member of group with a mapping, add them to the SS group.
727
                    if ($mapping->DN == $groupDN) {
728
                        $group = $mapping->Group();
729
                        if ($group && $group->exists()) {
730
                            $group->Members()->add($member, [
731
                                'IsImportedFromLDAP' => '1'
732
                            ]);
733
                            $mappedGroupIDs[] = $mapping->GroupID;
734
                        }
735
                    }
736
737
                    // the user *might* be a member of a nested group provided the scope of the mapping
738
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
739
                    // to see if they are a member of one of those. If they are, add them to the SS group
740
                    if ($mapping->Scope == 'Subtree') {
741
                        $childGroups = $this->getNestedGroups($mapping->DN, ['dn']);
742
                        if (!$childGroups) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $childGroups of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
743
                            continue;
744
                        }
745
746
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
747
                            if ($childGroupDN == $groupDN) {
748
                                $group = $mapping->Group();
749
                                if ($group && $group->exists()) {
750
                                    $group->Members()->add($member, [
751
                                        'IsImportedFromLDAP' => '1'
752
                                    ]);
753
                                    $mappedGroupIDs[] = $mapping->GroupID;
754
                                }
755
                            }
756
                        }
757
                    }
758
                }
759
            }
760
        }
761
762
        // Lookup the previous mappings and see if there is any mappings no longer present.
763
        $unmappedGroups = $member->Groups()->alterDataQuery(function (DataQuery $query) {
764
            // join with the Group_Members table because we only want those group members assigned by this module.
765
            $query->leftJoin("Group_Members", '"Group_Members"."GroupID" = "Group"."ID"');
766
            $query->where('"Group_Members"."IsImportedFromLDAP" = 1');
767
        });
768
769
        // Don't remove associations which have just been added and we know are already correct!
770
        if (!empty($mappedGroupIDs)) {
771
            $unmappedGroups = $unmappedGroups->filter("GroupID:NOT", $mappedGroupIDs);
772
        }
773
774
        // Remove the member from any previously mapped groups, where the mapping
775
        // has since been removed in the LDAP data source
776
        if ($unmappedGroups->count()) {
777
            foreach ($unmappedGroups as $group) {
778
                $group->Members()->remove($member);
779
            }
780
        }
781
    }
782
783
    /**
784
     * Sync a specific Group by updating it with LDAP data.
785
     *
786
     * @param Group $group An existing Group or a new Group object
787
     * @param array $data LDAP group object data
788
     *
789
     * @return bool
790
     */
791
    public function updateGroupFromLDAP(Group $group, $data)
792
    {
793
        if (!$this->enabled()) {
794
            return false;
795
        }
796
797
        // Synchronise specific guaranteed fields.
798
        $group->Code = $data['samaccountname'];
799
        $group->Title = $data['samaccountname'];
800
        if (!empty($data['description'])) {
801
            $group->Description = $data['description'];
802
        }
803
        $group->DN = $data['dn'];
804
        $group->LastSynced = (string)DBDatetime::now();
805
        $group->write();
806
807
        // Mappings on this group are automatically maintained to contain just the group's DN.
808
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
809
        $hasCorrectMapping = false;
810
        foreach ($group->LDAPGroupMappings() as $mapping) {
811
            if ($mapping->DN === $data['dn']) {
812
                // This is the correct mapping we want to retain.
813
                $hasCorrectMapping = true;
814
            } else {
815
                $mapping->delete();
816
            }
817
        }
818
819
        // Second, if the main mapping was not found, add it in.
820
        if (!$hasCorrectMapping) {
821
            $mapping = new LDAPGroupMapping();
822
            $mapping->DN = $data['dn'];
0 ignored issues
show
Bug Best Practice introduced by
The property DN does not exist on SilverStripe\LDAP\Model\LDAPGroupMapping. Since you implemented __set, consider adding a @property annotation.
Loading history...
823
            $mapping->write();
824
            $group->LDAPGroupMappings()->add($mapping);
825
        }
826
    }
827
828
    /**
829
     * Creates a new LDAP user from the passed Member record.
830
     * Note that the Member record must have a non-empty Username field for this to work.
831
     *
832
     * @param Member $member
833
     * @throws ValidationException
834
     * @throws Exception
835
     */
836
    public function createLDAPUser(Member $member)
837
    {
838
        if (!$this->enabled()) {
839
            return;
840
        }
841
        if (empty($member->Username)) {
842
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
843
        }
844
        if (!$this->config()->new_users_dn) {
845
            throw new Exception('LDAPService::new_users_dn must be configured to create LDAP users');
846
        }
847
848
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
849
        $member->Username = strtolower($member->Username);
850
851
        // Create user in LDAP using available information.
852
        $dn = sprintf('CN=%s,%s', $member->Username, $this->config()->new_users_dn);
853
854
        try {
855
            $this->add($dn, [
856
                'objectclass' => 'user',
857
                'cn' => $member->Username,
858
                'accountexpires' => '9223372036854775807',
859
                'useraccountcontrol' => '66048',
860
                'userprincipalname' => sprintf(
861
                    '%s@%s',
862
                    $member->Username,
863
                    $this->getGateway()->config()->options['accountDomainName']
864
                ),
865
            ]);
866
        } catch (Exception $e) {
867
            throw new ValidationException('LDAP synchronisation failure: ' . $e->getMessage());
868
        }
869
870
        $user = $this->getUserByUsername($member->Username);
871
        if (empty($user['objectguid'])) {
872
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
873
        }
874
875
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
876
        $member->GUID = $user['objectguid'];
877
    }
878
879
    /**
880
     * Creates a new LDAP group from the passed Group record.
881
     *
882
     * @param Group $group
883
     * @throws ValidationException
884
     */
885
    public function createLDAPGroup(Group $group)
886
    {
887
        if (!$this->enabled()) {
888
            return;
889
        }
890
        if (empty($group->Title)) {
891
            throw new ValidationException('Group missing Title. Cannot create LDAP group');
892
        }
893
        if (!$this->config()->new_groups_dn) {
894
            throw new Exception('LDAPService::new_groups_dn must be configured to create LDAP groups');
895
        }
896
897
        // LDAP isn't really meant to distinguish between a Title and Code. Squash them.
898
        $group->Code = $group->Title;
899
900
        $dn = sprintf('CN=%s,%s', $group->Title, $this->config()->new_groups_dn);
901
        try {
902
            $this->add($dn, [
903
                'objectclass' => 'group',
904
                'cn' => $group->Title,
905
                'name' => $group->Title,
906
                'samaccountname' => $group->Title,
907
                'description' => $group->Description,
908
                'distinguishedname' => $dn
909
            ]);
910
        } catch (Exception $e) {
911
            throw new ValidationException('LDAP group creation failure: ' . $e->getMessage());
912
        }
913
914
        $data = $this->getGroupByDN($dn);
915
        if (empty($data['objectguid'])) {
916
            throw new ValidationException(
917
                new ValidationResult(
918
                    false,
919
                    'LDAP group creation failure: group might have been created in LDAP. GUID is missing.'
920
                )
921
            );
922
        }
923
924
        // Creation was successful, mark the group as LDAP managed by setting the GUID.
925
        $group->GUID = $data['objectguid'];
926
        $group->DN = $data['dn'];
927
    }
928
929
    /**
930
     * Update the Member data back to the corresponding LDAP user object.
931
     *
932
     * @param Member $member
933
     * @throws ValidationException
934
     */
935
    public function updateLDAPFromMember(Member $member)
936
    {
937
        if (!$this->enabled()) {
938
            return;
939
        }
940
        if (!$member->GUID) {
941
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
942
        }
943
944
        $data = $this->getUserByGUID($member->GUID);
945
        if (empty($data['objectguid'])) {
946
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
947
        }
948
949
        if (empty($member->Username)) {
950
            throw new ValidationException('Member missing Username. Cannot update LDAP user');
951
        }
952
953
        $dn = $data['distinguishedname'];
954
955
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
956
        $member->Username = strtolower($member->Username);
957
958
        try {
959
            // If the common name (cn) has changed, we need to ensure they've been moved
960
            // to the new DN, to avoid any clashes between user objects.
961
            if ($data['cn'] != $member->Username) {
962
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
963
                $this->move($dn, $newDn);
964
                $dn = $newDn;
965
            }
966
        } catch (Exception $e) {
967
            throw new ValidationException('LDAP move failure: ' . $e->getMessage());
968
        }
969
970
        try {
971
            $attributes = [
972
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
973
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
974
                'userprincipalname' => sprintf(
975
                    '%s@%s',
976
                    $member->Username,
977
                    $this->getGateway()->config()->options['accountDomainName']
978
                ),
979
            ];
980
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
981
                $relationClass = $member->getRelationClass($field);
982
                if ($relationClass) {
983
                    // todo no support for writing back relations yet.
984
                } else {
985
                    $attributes[$attribute] = $member->$field;
986
                }
987
            }
988
989
            $this->update($dn, $attributes);
990
        } catch (Exception $e) {
991
            throw new ValidationException('LDAP synchronisation failure: ' . $e->getMessage());
992
        }
993
    }
994
995
    /**
996
     * Ensure the user belongs to the correct groups in LDAP from their membership
997
     * to local LDAP mapped SilverStripe groups.
998
     *
999
     * This also removes them from LDAP groups if they've been taken out of one.
1000
     * It will not affect group membership of non-mapped groups, so it will
1001
     * not touch such internal AD groups like "Domain Users".
1002
     *
1003
     * @param Member $member
1004
     * @throws ValidationException
1005
     */
1006
    public function updateLDAPGroupsForMember(Member $member)
1007
    {
1008
        if (!$this->enabled()) {
1009
            return;
1010
        }
1011
        if (!$member->GUID) {
1012
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
1013
        }
1014
1015
        $addGroups = [];
1016
        $removeGroups = [];
1017
1018
        $user = $this->getUserByGUID($member->GUID);
1019
        if (empty($user['objectguid'])) {
1020
            throw new ValidationException('LDAP update failure: user missing GUID');
1021
        }
1022
1023
        // If a user belongs to a single group, this comes through as a string.
1024
        // Normalise to a array so it's consistent.
1025
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : [];
1026
        if ($existingGroups && is_string($existingGroups)) {
1027
            $existingGroups = [$existingGroups];
1028
        }
1029
1030
        foreach ($member->Groups() as $group) {
1031
            if (!$group->GUID) {
1032
                continue;
1033
            }
1034
1035
            // mark this group as something we need to ensure the user belongs to in LDAP.
1036
            $addGroups[] = $group->DN;
1037
        }
1038
1039
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
1040
        // see if the user should be removed from any of them.
1041
        $remainingGroups = array_diff($existingGroups, $addGroups);
1042
1043
        foreach ($remainingGroups as $groupDn) {
1044
            // We only want to be removing groups we have a local Group mapped to. Removing
1045
            // membership for anything else would be bad!
1046
            $group = Group::get()->filter('DN', $groupDn)->first();
1047
            if (!$group || !$group->exists()) {
1048
                continue;
1049
            }
1050
1051
            // this group should be removed from the user's memberof attribute, as it's been removed.
1052
            $removeGroups[] = $groupDn;
1053
        }
1054
1055
        // go through the groups we want the user to be in and ensure they're in them.
1056
        foreach ($addGroups as $groupDn) {
1057
            $this->addLDAPUserToGroup($user['distinguishedname'], $groupDn);
1058
        }
1059
1060
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
1061
        foreach ($removeGroups as $groupDn) {
1062
            $members = $this->getLDAPGroupMembers($groupDn);
1063
1064
            // remove the user from the members data.
1065
            if (in_array($user['distinguishedname'], $members)) {
1066
                foreach ($members as $i => $dn) {
1067
                    if ($dn == $user['distinguishedname']) {
1068
                        unset($members[$i]);
1069
                    }
1070
                }
1071
            }
1072
1073
            try {
1074
                $this->update($groupDn, ['member' => $members]);
1075
            } catch (Exception $e) {
1076
                throw new ValidationException('LDAP group membership remove failure: ' . $e->getMessage());
1077
            }
1078
        }
1079
    }
1080
1081
    /**
1082
     * Add LDAP user by DN to LDAP group.
1083
     *
1084
     * @param string $userDn
1085
     * @param string $groupDn
1086
     * @throws Exception
1087
     */
1088
    public function addLDAPUserToGroup($userDn, $groupDn)
1089
    {
1090
        $members = $this->getLDAPGroupMembers($groupDn);
1091
1092
        // this user is already in the group, no need to do anything.
1093
        if (in_array($userDn, $members)) {
1094
            return;
1095
        }
1096
1097
        $members[] = $userDn;
1098
1099
        try {
1100
            $this->update($groupDn, ['member' => $members]);
1101
        } catch (Exception $e) {
1102
            throw new ValidationException('LDAP group membership add failure: ' . $e->getMessage());
1103
        }
1104
    }
1105
1106
    /**
1107
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
1108
     * password in the `unicodePwd` attribute.
1109
     *
1110
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
1111
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
1112
     *
1113
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
1114
     *
1115
     * @param Member $member
1116
     * @param string $password
1117
     * @param string|null $oldPassword Supply old password to perform a password change (as opposed to password reset)
1118
     * @return ValidationResult
1119
     */
1120
    public function setPassword(Member $member, $password, $oldPassword = null)
1121
    {
1122
        $validationResult = ValidationResult::create();
1123
1124
        $this->extend('onBeforeSetPassword', $member, $password, $validationResult);
1125
1126
        if (!$member->GUID) {
1127
            $this->getLogger()->debug(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
1128
            $validationResult->addError(
1129
                _t(
1130
                    'SilverStripe\\LDAP\\Authenticators\\LDAPAuthenticator.NOUSER',
1131
                    'Your account hasn\'t been setup properly, please contact an administrator.'
1132
                )
1133
            );
1134
            return $validationResult;
1135
        }
1136
1137
        $userData = $this->getUserByGUID($member->GUID);
1138
        if (empty($userData['distinguishedname'])) {
1139
            $validationResult->addError(
1140
                _t(
1141
                    'SilverStripe\\LDAP\\Authenticators\\LDAPAuthenticator.NOUSER',
1142
                    'Your account hasn\'t been setup properly, please contact an administrator.'
1143
                )
1144
            );
1145
            return $validationResult;
1146
        }
1147
1148
        try {
1149
            if (!empty($oldPassword)) {
1150
                $this->getGateway()->changePassword($userData['distinguishedname'], $password, $oldPassword);
1151
            } elseif ($this->config()->password_history_workaround) {
1152
                $this->passwordHistoryWorkaround($userData['distinguishedname'], $password);
1153
            } else {
1154
                $this->getGateway()->resetPassword($userData['distinguishedname'], $password);
1155
            }
1156
            $this->extend('onAfterSetPassword', $member, $password, $validationResult);
1157
        } catch (Exception $e) {
1158
            $validationResult->addError($e->getMessage());
1159
        }
1160
1161
        return $validationResult;
1162
    }
1163
1164
    /**
1165
     * Delete an LDAP user mapped to the Member record
1166
     * @param Member $member
1167
     * @throws ValidationException
1168
     */
1169
    public function deleteLDAPMember(Member $member)
1170
    {
1171
        if (!$this->enabled()) {
1172
            return;
1173
        }
1174
        if (!$member->GUID) {
1175
            throw new ValidationException('Member missing GUID. Cannot delete LDAP user');
1176
        }
1177
        $data = $this->getUserByGUID($member->GUID);
1178
        if (empty($data['distinguishedname'])) {
1179
            throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute');
1180
        }
1181
1182
        try {
1183
            $this->delete($data['distinguishedname']);
1184
        } catch (Exception $e) {
1185
            throw new ValidationException('LDAP delete user failed: ' . $e->getMessage());
1186
        }
1187
    }
1188
1189
    /**
1190
     * A simple proxy to LDAP update operation.
1191
     *
1192
     * @param string $dn Location to add the entry at.
1193
     * @param array $attributes A simple associative array of attributes.
1194
     */
1195
    public function update($dn, array $attributes)
1196
    {
1197
        $this->getGateway()->update($dn, $attributes);
1198
    }
1199
1200
    /**
1201
     * A simple proxy to LDAP delete operation.
1202
     *
1203
     * @param string $dn Location of object to delete
1204
     * @param bool $recursively Recursively delete nested objects?
1205
     */
1206
    public function delete($dn, $recursively = false)
1207
    {
1208
        $this->getGateway()->delete($dn, $recursively);
1209
    }
1210
1211
    /**
1212
     * A simple proxy to LDAP copy/delete operation.
1213
     *
1214
     * @param string $fromDn
1215
     * @param string $toDn
1216
     * @param bool $recursively Recursively move nested objects?
1217
     */
1218
    public function move($fromDn, $toDn, $recursively = false)
1219
    {
1220
        $this->getGateway()->move($fromDn, $toDn, $recursively);
1221
    }
1222
1223
    /**
1224
     * A simple proxy to LDAP add operation.
1225
     *
1226
     * @param string $dn Location to add the entry at.
1227
     * @param array $attributes A simple associative array of attributes.
1228
     */
1229
    public function add($dn, array $attributes)
1230
    {
1231
        $this->getGateway()->add($dn, $attributes);
1232
    }
1233
1234
    /**
1235
     * @param string $dn Distinguished name of the user
1236
     * @param string $password New password.
1237
     * @throws Exception
1238
     */
1239
    private function passwordHistoryWorkaround($dn, $password)
1240
    {
1241
        $generator = new RandomGenerator();
1242
        // 'Aa1' is there to satisfy the complexity criterion.
1243
        $tempPassword = sprintf('Aa1%s', substr($generator->randomToken('sha1'), 0, 21));
1244
        $this->getGateway()->resetPassword($dn, $tempPassword);
1245
        $this->getGateway()->changePassword($dn, $password, $tempPassword);
1246
    }
1247
1248
    /**
1249
     * Get a logger
1250
     *
1251
     * @return LoggerInterface
1252
     */
1253
    public function getLogger()
1254
    {
1255
        return Injector::inst()->get(LoggerInterface::class);
1256
    }
1257
}
1258