Completed
Push — master ( 875417...ea72ed )
by Daniel
9s
created

LDAPService::addLDAPUserToGroup()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 2
1
<?php
2
3
namespace SilverStripe\ActiveDirectory\Services;
4
5
use Exception;
6
use SilverStripe\ActiveDirectory\Model\LDAPGroupMapping;
7
use SilverStripe\Assets\Filesystem;
8
use SilverStripe\Core\Cache;
9
use SilverStripe\Core\Config\Config;
10
use SilverStripe\Core\Flushable;
11
use SilverStripe\Core\Injector\Injector;
12
use SilverStripe\Core\Object;
13
use SilverStripe\ORM\DB;
14
use SilverStripe\ORM\FieldType\DBDatetime;
15
use SilverStripe\ORM\ValidationException;
16
use SilverStripe\ORM\ValidationResult;
17
use SilverStripe\Security\Group;
18
use SilverStripe\Security\Member;
19
use SilverStripe\Security\RandomGenerator;
20
use Zend_Cache;
21
use Zend\Ldap\Ldap;
22
23
/**
24
 * Class LDAPService
25
 *
26
 * Provides LDAP operations expressed in terms of the SilverStripe domain.
27
 * All other modules should access LDAP through this class.
28
 *
29
 * This class builds on top of LDAPGateway's detailed code by adding:
30
 * - caching
31
 * - data aggregation and restructuring from multiple lower-level calls
32
 * - error handling
33
 *
34
 * LDAPService relies on Zend LDAP module's data structures for some parameters and some return values.
35
 *
36
 * @package activedirectory
37
 */
38
class LDAPService extends Object implements Flushable
39
{
40
    /**
41
     * @var array
42
     */
43
    private static $dependencies = [
0 ignored issues
show
Unused Code introduced by
The property $dependencies is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
44
        'gateway' => '%$SilverStripe\\ActiveDirectory\\Model\\LDAPGateway'
45
    ];
46
47
    /**
48
     * If configured, only user objects within these locations will be exposed to this service.
49
     *
50
     * @var array
51
     * @config
52
     */
53
    private static $users_search_locations = [];
0 ignored issues
show
Unused Code introduced by
The property $users_search_locations is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
54
55
    /**
56
     * If configured, only group objects within these locations will be exposed to this service.
57
     * @var array
58
     *
59
     * @config
60
     */
61
    private static $groups_search_locations = [];
0 ignored issues
show
Unused Code introduced by
The property $groups_search_locations is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
62
63
    /**
64
     * Location to create new users in (distinguished name).
65
     * @var string
66
     *
67
     * @config
68
     */
69
    private static $new_users_dn;
0 ignored issues
show
Unused Code introduced by
The property $new_users_dn is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
70
71
    /**
72
     * @var array
73
     */
74
    private static $_cache_nested_groups = [];
75
76
    /**
77
     * If this is configured to a "Code" value of a {@link Group} in SilverStripe, the user will always
78
     * be added to this group's membership when imported, regardless of any sort of group mappings.
79
     *
80
     * @var string
81
     * @config
82
     */
83
    private static $default_group;
0 ignored issues
show
Unused Code introduced by
The property $default_group is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
84
85
    /**
86
     * For samba4 directory, there is no way to enforce password history on password resets.
87
     * This only happens with changePassword (which requires the old password).
88
     * This works around it by making the old password up and setting it administratively.
89
     *
90
     * A cleaner fix would be to use the LDAP_SERVER_POLICY_HINTS_OID connection flag,
91
     * but it's not implemented in samba https://bugzilla.samba.org/show_bug.cgi?id=12020
92
     *
93
     * @var bool
94
     */
95
    private static $password_history_workaround = false;
0 ignored issues
show
Unused Code introduced by
The property $password_history_workaround is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
96
97
    /**
98
     * Get the cache object used for LDAP results. Note that the default lifetime set here
99
     * is 8 hours, but you can change that by calling Cache::set_lifetime('ldap', <lifetime in seconds>)
100
     *
101
     * @return Zend_Cache_Frontend
102
     */
103
    public static function get_cache()
104
    {
105
        return Cache::factory('ldap', 'Output', [
106
            'automatic_serialization' => true,
107
            'lifetime' => 28800
108
        ]);
109
    }
110
111
    /**
112
     * Flushes out the LDAP results cache when flush=1 is called.
113
     */
114
    public static function flush()
115
    {
116
        $cache = self::get_cache();
117
        $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
118
    }
119
120
    /**
121
     * @var LDAPGateway
122
     */
123
    public $gateway;
124
125
    /**
126
     * Setter for gateway. Useful for overriding the gateway with a fake for testing.
127
     * @var LDAPGateway
128
     */
129
    public function setGateway($gateway)
130
    {
131
        $this->gateway = $gateway;
132
    }
133
134
    /**
135
     * Checkes whether or not the service is enabled.
136
     *
137
     * @return bool
138
     */
139
    public function enabled()
140
    {
141
        $options = Config::inst()->get('SilverStripe\\ActiveDirectory\\Model\\LDAPGateway', 'options');
142
        return !empty($options);
143
    }
144
145
    /**
146
     * Authenticate the given username and password with LDAP.
147
     *
148
     * @param string $username
149
     * @param string $password
150
     *
151
     * @return array
152
     */
153
    public function authenticate($username, $password)
154
    {
155
        $result = $this->gateway->authenticate($username, $password);
156
        $messages = $result->getMessages();
157
158
        // all messages beyond the first one are for debugging and
159
        // not suitable to display to the user.
160
        foreach ($messages as $i => $message) {
161
            if ($i > 0) {
162
                $this->getLogger()->debug(str_replace("\n", "\n  ", $message));
163
            }
164
        }
165
166
        $message = $messages[0]; // first message is user readable, suitable for showing on login form
167
168
        // show better errors than the defaults for various status codes returned by LDAP
169 View Code Duplication
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_ACCOUNT_LOCKED_OUT') !== false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
170
            $message = _t(
171
                'LDAPService.ACCOUNTLOCKEDOUT',
172
                'Your account has been temporarily locked because of too many failed login attempts. ' .
173
                'Please try again later.'
174
            );
175
        }
176 View Code Duplication
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_LOGON_FAILURE') !== false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
            $message = _t(
178
                'LDAPService.INVALIDCREDENTIALS',
179
                'The provided details don\'t seem to be correct. Please try again.'
180
            );
181
        }
182
183
        return [
184
            'success' => $result->getCode() === 1,
185
            'identity' => $result->getIdentity(),
186
            'message' => $message
187
        ];
188
    }
189
190
    /**
191
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
192
     *
193
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
194
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
195
     * @return array
196
     */
197
    public function getNodes($cached = true, $attributes = [])
198
    {
199
        $cache = self::get_cache();
200
        $results = $cache->load('nodes' . md5(implode('', $attributes)));
201
202
        if (!$results || !$cached) {
203
            $results = [];
204
            $records = $this->gateway->getNodes(null, Ldap::SEARCH_SCOPE_SUB, $attributes);
205
            foreach ($records as $record) {
206
                $results[$record['dn']] = $record;
207
            }
208
209
            $cache->save($results);
210
        }
211
212
        return $results;
213
    }
214
215
    /**
216
     * Return all AD groups in configured search locations, including all nested groups.
217
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
218
     * to use the default baseDn defined in the connection.
219
     *
220
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
221
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
222
     * @param string $indexBy Attribute to use as an index.
223
     * @return array
224
     */
225
    public function getGroups($cached = true, $attributes = [], $indexBy = 'dn')
226
    {
227
        $searchLocations = $this->config()->groups_search_locations ?: [null];
228
        $cache = self::get_cache();
229
        $results = $cache->load('groups' . md5(implode('', array_merge($searchLocations, $attributes))));
230
231
        if (!$results || !$cached) {
232
            $results = [];
233 View Code Duplication
            foreach ($searchLocations as $searchLocation) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
234
                $records = $this->gateway->getGroups($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
235
                if (!$records) {
236
                    continue;
237
                }
238
239
                foreach ($records as $record) {
240
                    $results[$record[$indexBy]] = $record;
241
                }
242
            }
243
244
            $cache->save($results);
245
        }
246
247
        return $results;
248
    }
249
250
    /**
251
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
252
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
253
     *
254
     * @param string $dn
255
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
256
     * @return array
257
     */
258
    public function getNestedGroups($dn, $attributes = [])
259
    {
260
        if (isset(self::$_cache_nested_groups[$dn])) {
261
            return self::$_cache_nested_groups[$dn];
262
        }
263
264
        $searchLocations = $this->config()->groups_search_locations ?: [null];
265
        $results = [];
266 View Code Duplication
        foreach ($searchLocations as $searchLocation) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
267
            $records = $this->gateway->getNestedGroups($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
268
            foreach ($records as $record) {
269
                $results[$record['dn']] = $record;
270
            }
271
        }
272
273
        self::$_cache_nested_groups[$dn] = $results;
274
        return $results;
275
    }
276
277
    /**
278
     * Get a particular AD group's data given a GUID.
279
     *
280
     * @param string $guid
281
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
282
     * @return array
283
     */
284 View Code Duplication
    public function getGroupByGUID($guid, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
285
    {
286
        $searchLocations = $this->config()->groups_search_locations ?: [null];
287
        foreach ($searchLocations as $searchLocation) {
288
            $records = $this->gateway->getGroupByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
289
            if ($records) {
290
                return $records[0];
291
            }
292
        }
293
    }
294
295
    /**
296
     * Get a particular AD group's data given a DN.
297
     *
298
     * @param string $dn
299
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
300
     * @return array
301
     */
302 View Code Duplication
    public function getGroupByDN($dn, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
303
    {
304
        $searchLocations = $this->config()->groups_search_locations ?: [null];
305
        foreach ($searchLocations as $searchLocation) {
306
            $records = $this->gateway->getGroupByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
307
            if ($records) {
308
                return $records[0];
309
            }
310
        }
311
    }
312
313
    /**
314
     * Return all AD users in configured search locations, including all users in nested groups.
315
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
316
     * to use the default baseDn defined in the connection.
317
     *
318
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
319
     * @return array
320
     */
321
    public function getUsers($attributes = [])
322
    {
323
        $searchLocations = $this->config()->users_search_locations ?: [null];
324
        $results = [];
325
326 View Code Duplication
        foreach ($searchLocations as $searchLocation) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
327
            $records = $this->gateway->getUsers($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
328
            if (!$records) {
329
                continue;
330
            }
331
332
            foreach ($records as $record) {
333
                $results[$record['objectguid']] = $record;
334
            }
335
        }
336
337
        return $results;
338
    }
339
340
    /**
341
     * Get a specific AD user's data given a GUID.
342
     *
343
     * @param string $guid
344
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
345
     * @return array
346
     */
347 View Code Duplication
    public function getUserByGUID($guid, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
348
    {
349
        $searchLocations = $this->config()->users_search_locations ?: [null];
350
        foreach ($searchLocations as $searchLocation) {
351
            $records = $this->gateway->getUserByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
352
            if ($records) {
353
                return $records[0];
354
            }
355
        }
356
    }
357
358
    /**
359
     * Get a specific AD user's data given a DN.
360
     *
361
     * @param string $dn
362
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
363
     *
364
     * @return array
365
     */
366 View Code Duplication
    public function getUserByDN($dn, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
367
    {
368
        $searchLocations = $this->config()->users_search_locations ?: [null];
369
        foreach ($searchLocations as $searchLocation) {
370
            $records = $this->gateway->getUserByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
371
            if ($records) {
372
                return $records[0];
373
            }
374
        }
375
    }
376
377
    /**
378
     * Get a specific user's data given an email.
379
     *
380
     * @param string $email
381
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
382
     * @return array
383
     */
384 View Code Duplication
    public function getUserByEmail($email, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
385
    {
386
        $searchLocations = $this->config()->users_search_locations ?: [null];
387
        foreach ($searchLocations as $searchLocation) {
388
            $records = $this->gateway->getUserByEmail($email, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
389
            if ($records) {
390
                return $records[0];
391
            }
392
        }
393
    }
394
395
    /**
396
     * Get a specific user's data given a username.
397
     *
398
     * @param string $username
399
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
400
     * @return array
401
     */
402 View Code Duplication
    public function getUserByUsername($username, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
403
    {
404
        $searchLocations = $this->config()->users_search_locations ?: [null];
405
        foreach ($searchLocations as $searchLocation) {
406
            $records = $this->gateway->getUserByUsername($username, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
407
            if ($records) {
408
                return $records[0];
409
            }
410
        }
411
    }
412
413
    /**
414
     * Get a username for an email.
415
     *
416
     * @param string $email
417
     * @return string|null
418
     */
419
    public function getUsernameByEmail($email)
420
    {
421
        $data = $this->getUserByEmail($email);
422
        if (empty($data)) {
423
            return null;
424
        }
425
426
        return $this->gateway->getCanonicalUsername($data);
427
    }
428
429
    /**
430
     * Given a group DN, get the group membership data in LDAP.
431
     *
432
     * @param string $dn
433
     * @return array
434
     */
435
    public function getLDAPGroupMembers($dn)
436
    {
437
        $groupObj = Group::get()->filter('DN', $dn)->first();
438
        $groupData = $this->getGroupByGUID($groupObj->GUID);
439
        $members = !empty($groupData['member']) ? $groupData['member'] : [];
440
        // If a user belongs to a single group, this comes through as a string.
441
        // Normalise to a array so it's consistent.
442
        if ($members && is_string($members)) {
443
            $members = [$members];
444
        }
445
446
        return $members;
447
    }
448
449
    /**
450
     * Update the current Member record with data from LDAP.
451
     *
452
     * Constraints:
453
     * - Member *must* be in the database before calling this as it will need the ID to be mapped to a {@link Group}.
454
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
455
     *
456
     * @param Member
457
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
458
     *            If not given, the data will be looked up by the user's GUID.
459
     * @return bool
460
     */
461
    public function updateMemberFromLDAP(Member $member, $data = null)
462
    {
463
        if (!$this->enabled()) {
464
            return false;
465
        }
466
467
        if (!$member->GUID) {
468
            $this->getLogger()->warn(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
469
            return false;
470
        }
471
472
        if (!$data) {
473
            $data = $this->getUserByGUID($member->GUID);
474
            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...
475
                $this->getLogger()->warn(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID));
476
                return false;
477
            }
478
        }
479
480
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
481
        $member->LastSynced = (string)DBDatetime::now();
482
483
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
484
            if (!isset($data[$attribute])) {
485
                $this->getLogger()->notice(
486
                    sprintf(
487
                        'Attribute %s configured in Member.ldap_field_mappings, but no available attribute in AD data (GUID: %s, Member ID: %s)',
488
                        $attribute,
489
                        $data['objectguid'],
490
                        $member->ID
491
                    )
492
                );
493
494
                continue;
495
            }
496
497
            if ($attribute == 'thumbnailphoto') {
498
                $imageClass = $member->getRelationClass($field);
499
                if ($imageClass !== 'SilverStripe\\Assets\\Image'
500
                    && !is_subclass_of($imageClass, 'SilverStripe\\Assets\\Image')
501
                ) {
502
                    $this->getLogger()->warn(
503
                        sprintf(
504
                            'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an Image class',
505
                            $field
506
                        )
507
                    );
508
509
                    continue;
510
                }
511
512
                $filename = sprintf('thumbnailphoto-%s.jpg', $data['samaccountname']);
513
                $path = ASSETS_DIR . '/' . $member->config()->ldap_thumbnail_path;
514
                $absPath = BASE_PATH . '/' . $path;
515
                if (!file_exists($absPath)) {
516
                    Filesystem::makeFolder($absPath);
517
                }
518
519
                // remove existing record if it exists
520
                $existingObj = $member->getComponent($field);
521
                if ($existingObj && $existingObj->exists()) {
522
                    $existingObj->delete();
523
                }
524
525
                // The image data is provided in raw binary.
526
                file_put_contents($absPath . '/' . $filename, $data[$attribute]);
527
                $record = new $imageClass();
528
                $record->Name = $filename;
529
                $record->Filename = $path . '/' . $filename;
530
                $record->write();
531
532
                $relationField = $field . 'ID';
533
                $member->{$relationField} = $record->ID;
534
            } else {
535
                $member->$field = $data[$attribute];
536
            }
537
        }
538
539
        // if a default group was configured, ensure the user is in that group
540
        if ($this->config()->default_group) {
541
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
542
            if (!($group && $group->exists())) {
543
                $this->getLogger()->warn(
544
                    sprintf(
545
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
546
                        $this->config()->default_group
547
                    )
548
                );
549
            } else {
550
                $group->Members()->add($member, [
551
                    'IsImportedFromLDAP' => '1'
552
                ]);
553
            }
554
        }
555
556
        // this is to keep track of which groups the user gets mapped to
557
        // and we'll use that later to remove them from any groups that they're no longer mapped to
558
        $mappedGroupIDs = [];
559
560
        // ensure the user is in any mapped groups
561
        if (isset($data['memberof'])) {
562
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : [$data['memberof']];
563
            foreach ($ldapGroups as $groupDN) {
564
                foreach (LDAPGroupMapping::get() as $mapping) {
565
                    if (!$mapping->DN) {
566
                        $this->getLogger()->warn(
567
                            sprintf(
568
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
569
                                $mapping->ID
570
                            )
571
                        );
572
                        continue;
573
                    }
574
575
                    // the user is a direct member of group with a mapping, add them to the SS group.
576 View Code Duplication
                    if ($mapping->DN == $groupDN) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
577
                        $group = $mapping->Group();
578
                        if ($group && $group->exists()) {
579
                            $group->Members()->add($member, [
580
                                'IsImportedFromLDAP' => '1'
581
                            ]);
582
                            $mappedGroupIDs[] = $mapping->GroupID;
583
                        }
584
                    }
585
586
                    // the user *might* be a member of a nested group provided the scope of the mapping
587
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
588
                    // to see if they are a member of one of those. If they are, add them to the SS group
589
                    if ($mapping->Scope == 'Subtree') {
590
                        $childGroups = $this->getNestedGroups($mapping->DN, ['dn']);
591
                        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...
592
                            continue;
593
                        }
594
595
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
596 View Code Duplication
                            if ($childGroupDN == $groupDN) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
597
                                $group = $mapping->Group();
598
                                if ($group && $group->exists()) {
599
                                    $group->Members()->add($member, [
600
                                        'IsImportedFromLDAP' => '1'
601
                                    ]);
602
                                    $mappedGroupIDs[] = $mapping->GroupID;
603
                                }
604
                            }
605
                        }
606
                    }
607
                }
608
            }
609
        }
610
611
        // remove the user from any previously mapped groups, where the mapping has since been removed
612
        $groupRecords = DB::query(
613
            sprintf(
614
                'SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s',
615
                $member->ID
616
            )
617
        );
618
619
        foreach ($groupRecords as $groupRecord) {
620
            if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
621
                $group = Group::get()->byId($groupRecord['GroupID']);
622
                // Some groups may no longer exist. SilverStripe does not clean up join tables.
623
                if ($group) {
624
                    $group->Members()->remove($member);
625
                }
626
            }
627
        }
628
        // This will throw an exception if there are two distinct GUIDs with the same email address.
629
        // We are happy with a raw 500 here at this stage.
630
        $member->write();
631
    }
632
633
    /**
634
     * Sync a specific Group by updating it with LDAP data.
635
     *
636
     * @param Group $group An existing Group or a new Group object
637
     * @param array $data LDAP group object data
638
     *
639
     * @return bool
640
     */
641
    public function updateGroupFromLDAP(Group $group, $data)
642
    {
643
        if (!$this->enabled()) {
644
            return false;
645
        }
646
647
        // Synchronise specific guaranteed fields.
648
        $group->Code = $data['samaccountname'];
649
        if (!empty($data['name'])) {
650
            $group->Title = $data['name'];
651
        } else {
652
            $group->Title = $data['samaccountname'];
653
        }
654
        if (!empty($data['description'])) {
655
            $group->Description = $data['description'];
656
        }
657
        $group->DN = $data['dn'];
658
        $group->LastSynced = (string)DBDatetime::now();
659
        $group->write();
660
661
        // Mappings on this group are automatically maintained to contain just the group's DN.
662
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
663
        $hasCorrectMapping = false;
664
        foreach ($group->LDAPGroupMappings() as $mapping) {
665
            if ($mapping->DN === $data['dn']) {
666
                // This is the correct mapping we want to retain.
667
                $hasCorrectMapping = true;
668
            } else {
669
                $mapping->delete();
670
            }
671
        }
672
673
        // Second, if the main mapping was not found, add it in.
674
        if (!$hasCorrectMapping) {
675
            $mapping = new LDAPGroupMapping();
676
            $mapping->DN = $data['dn'];
0 ignored issues
show
Documentation introduced by
The property DN does not exist on object<SilverStripe\Acti...Model\LDAPGroupMapping>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
677
            $mapping->write();
678
            $group->LDAPGroupMappings()->add($mapping);
679
        }
680
    }
681
682
    /**
683
     * Creates a new LDAP user from the passed Member record.
684
     * Note that the Member record must have a non-empty Username field for this to work.
685
     *
686
     * @param Member $member
687
     * @throws ValidationException
688
     * @throws Exception
689
     */
690
    public function createLDAPUser(Member $member)
691
    {
692
        if (!$this->enabled()) {
693
            return;
694
        }
695
        if (empty($member->Username)) {
696
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
697
        }
698
        if (!$this->config()->new_users_dn) {
699
            throw new Exception('LDAPService::new_users_dn must be configured to create LDAP users');
700
        }
701
702
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
703
        $member->Username = strtolower($member->Username);
704
705
        // Create user in LDAP using available information.
706
        $dn = sprintf('CN=%s,%s', $member->Username, $this->config()->new_users_dn);
707
708
        try {
709
            $this->add($dn, [
710
                'objectclass' => 'user',
711
                'cn' => $member->Username,
712
                'accountexpires' => '9223372036854775807',
713
                'useraccountcontrol' => '66048',
714
                'userprincipalname' => sprintf(
715
                    '%s@%s',
716
                    $member->Username,
717
                    $this->gateway->config()->options['accountDomainName']
718
                ),
719
            ]);
720
        } catch (Exception $e) {
721
            throw new ValidationException('LDAP synchronisation failure: ' . $e->getMessage());
722
        }
723
724
        $user = $this->getUserByUsername($member->Username);
725
        if (empty($user['objectguid'])) {
726
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
727
        }
728
729
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
730
        $member->GUID = $user['objectguid'];
731
    }
732
733
    /**
734
     * Update the Member data back to the corresponding LDAP user object.
735
     *
736
     * @param Member $member
737
     * @throws ValidationException
738
     */
739
    public function updateLDAPFromMember(Member $member)
740
    {
741
        if (!$this->enabled()) {
742
            return;
743
        }
744
        if (!$member->GUID) {
745
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
746
        }
747
748
        $data = $this->getUserByGUID($member->GUID);
749
        if (empty($data['objectguid'])) {
750
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
751
        }
752
753
        if (empty($member->Username)) {
754
            throw new ValidationException('Member missing Username. Cannot update LDAP user');
755
        }
756
757
        $dn = $data['distinguishedname'];
758
759
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
760
        $member->Username = strtolower($member->Username);
761
762
        try {
763
            // If the common name (cn) has changed, we need to ensure they've been moved
764
            // to the new DN, to avoid any clashes between user objects.
765
            if ($data['cn'] != $member->Username) {
766
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
767
                $this->move($dn, $newDn);
768
                $dn = $newDn;
769
            }
770
        } catch (Exception $e) {
771
            throw new ValidationException('LDAP move failure: '.$e->getMessage());
772
        }
773
774
        try {
775
            $attributes = [
776
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
777
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
778
                'userprincipalname' => sprintf(
779
                    '%s@%s',
780
                    $member->Username,
781
                    $this->gateway->config()->options['accountDomainName']
782
                ),
783
            ];
784
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
785
                $relationClass = $member->getRelationClass($field);
786
                if ($relationClass) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
787
                    // todo no support for writing back relations yet.
788
                } else {
789
                    $attributes[$attribute] = $member->$field;
790
                }
791
            }
792
793
            $this->update($dn, $attributes);
794
        } catch (Exception $e) {
795
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
796
        }
797
    }
798
799
    /**
800
     * Ensure the user belongs to the correct groups in LDAP from their membership
801
     * to local LDAP mapped SilverStripe groups.
802
     *
803
     * This also removes them from LDAP groups if they've been taken out of one.
804
     * It will not affect group membership of non-mapped groups, so it will
805
     * not touch such internal AD groups like "Domain Users".
806
     *
807
     * @param Member $member
808
     * @throws ValidationException
809
     */
810
    public function updateLDAPGroupsForMember(Member $member)
811
    {
812
        if (!$this->enabled()) {
813
            return;
814
        }
815
        if (!$member->GUID) {
816
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
817
        }
818
819
        $addGroups = [];
820
        $removeGroups = [];
821
822
        $user = $this->getUserByGUID($member->GUID);
823
        if (empty($user['objectguid'])) {
824
            throw new ValidationException('LDAP update failure: user missing GUID');
825
        }
826
827
        // If a user belongs to a single group, this comes through as a string.
828
        // Normalise to a array so it's consistent.
829
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : [];
830
        if ($existingGroups && is_string($existingGroups)) {
831
            $existingGroups = [$existingGroups];
832
        }
833
834
        foreach ($member->Groups() as $group) {
835
            if (!$group->GUID) {
836
                continue;
837
            }
838
839
            // mark this group as something we need to ensure the user belongs to in LDAP.
840
            $addGroups[] = $group->DN;
841
        }
842
843
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
844
        // see if the user should be removed from any of them.
845
        $remainingGroups = array_diff($existingGroups, $addGroups);
846
847
        foreach ($remainingGroups as $groupDn) {
848
            // We only want to be removing groups we have a local Group mapped to. Removing
849
            // membership for anything else would be bad!
850
            $group = Group::get()->filter('DN', $groupDn)->first();
851
            if (!$group || !$group->exists()) {
852
                continue;
853
            }
854
855
            // this group should be removed from the user's memberof attribute, as it's been removed.
856
            $removeGroups[] = $groupDn;
857
        }
858
859
        // go through the groups we want the user to be in and ensure they're in them.
860
        foreach ($addGroups as $groupDn) {
861
            $this->addLDAPUserToGroup($user['distinguishedname'], $groupDn);
862
        }
863
864
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
865
        foreach ($removeGroups as $groupDn) {
866
            $members = $this->getLDAPGroupMembers($groupDn);
867
868
            // remove the user from the members data.
869
            if (in_array($user['distinguishedname'], $members)) {
870
                foreach ($members as $i => $dn) {
871
                    if ($dn == $user['distinguishedname']) {
872
                        unset($members[$i]);
873
                    }
874
                }
875
            }
876
877
            try {
878
                $this->update($groupDn, ['member' => $members]);
879
            } catch (Exception $e) {
880
                throw new ValidationException('LDAP group membership remove failure: ' . $e->getMessage());
881
            }
882
        }
883
    }
884
885
    /**
886
     * Add LDAP user by DN to LDAP group.
887
     *
888
     * @param string $userDn
889
     * @param string $groupDn
890
     * @throws \Exception
891
     */
892
    public function addLDAPUserToGroup($userDn, $groupDn) {
893
        $members = $this->getLDAPGroupMembers($groupDn);
894
895
        // this user is already in the group, no need to do anything.
896
        if (in_array($userDn, $members)) {
897
            return;
898
        }
899
900
        $members[] = $userDn;
901
902
        try {
903
            $this->update($groupDn, ['member' => $members]);
904
        } catch (Exception $e) {
905
            throw new ValidationException('LDAP group membership add failure: ' . $e->getMessage());
906
        }
907
    }
908
909
    /**
910
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
911
     * password in the `unicodePwd` attribute.
912
     *
913
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
914
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
915
     *
916
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
917
     *
918
     * @param Member $member
919
     * @param string $password
920
     * @param string|null $oldPassword Supply old password to perform a password change (as opposed to password reset)
921
     * @return ValidationResult
922
     */
923
    public function setPassword(Member $member, $password, $oldPassword = null)
924
    {
925
        $validationResult = ValidationResult::create();
926
927
        $this->extend('onBeforeSetPassword', $member, $password, $validationResult);
928
929
        if (!$member->GUID) {
930
            $this->getLogger()->warn(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
931
            $validationResult->addError(
932
                _t(
933
                    'LDAPAuthenticator.NOUSER',
934
                    'Your account hasn\'t been setup properly, please contact an administrator.'
935
                )
936
            );
937
            return $validationResult;
938
        }
939
940
        $userData = $this->getUserByGUID($member->GUID);
941
        if (empty($userData['distinguishedname'])) {
942
            $validationResult->addError(
943
                _t(
944
                    'LDAPAuthenticator.NOUSER',
945
                    'Your account hasn\'t been setup properly, please contact an administrator.'
946
                )
947
            );
948
            return $validationResult;
949
        }
950
951
        try {
952
            if (!empty($oldPassword)) {
953
                $this->gateway->changePassword($userData['distinguishedname'], $password, $oldPassword);
954
            } elseif ($this->config()->password_history_workaround) {
955
                $this->passwordHistoryWorkaround($userData['distinguishedname'], $password);
956
            } else {
957
                $this->gateway->resetPassword($userData['distinguishedname'], $password);
958
            }
959
            $this->extend('onAfterSetPassword', $member, $password, $validationResult);
960
        } catch (Exception $e) {
961
            $validationResult->addError($e->getMessage());
962
        }
963
964
        return $validationResult;
965
    }
966
967
    /**
968
     * Delete an LDAP user mapped to the Member record
969
     * @param Member $member
970
     * @throws ValidationException
971
     */
972
    public function deleteLDAPMember(Member $member)
973
    {
974
        if (!$this->enabled()) {
975
            return;
976
        }
977
        if (!$member->GUID) {
978
            throw new ValidationException('Member missing GUID. Cannot delete LDAP user');
979
        }
980
        $data = $this->getUserByGUID($member->GUID);
981
        if (empty($data['distinguishedname'])) {
982
            throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute');
983
        }
984
985
        try {
986
            $this->delete($data['distinguishedname']);
987
        } catch (Exception $e) {
988
            throw new ValidationException('LDAP delete user failed: ' . $e->getMessage());
989
        }
990
    }
991
992
    /**
993
     * A simple proxy to LDAP update operation.
994
     *
995
     * @param string $dn Location to add the entry at.
996
     * @param array $attributes A simple associative array of attributes.
997
     */
998
    public function update($dn, array $attributes)
999
    {
1000
        $this->gateway->update($dn, $attributes);
1001
    }
1002
1003
    /**
1004
     * A simple proxy to LDAP delete operation.
1005
     *
1006
     * @param string $dn Location of object to delete
1007
     * @param bool $recursively Recursively delete nested objects?
1008
     */
1009
    public function delete($dn, $recursively = false)
1010
    {
1011
        $this->gateway->delete($dn, $recursively);
1012
    }
1013
1014
    /**
1015
     * A simple proxy to LDAP copy/delete operation.
1016
     *
1017
     * @param string $fromDn
1018
     * @param string $toDn
1019
     * @param bool $recursively Recursively move nested objects?
1020
     */
1021
    public function move($fromDn, $toDn, $recursively = false)
1022
    {
1023
        $this->gateway->move($fromDn, $toDn, $recursively);
1024
    }
1025
1026
    /**
1027
     * A simple proxy to LDAP add operation.
1028
     *
1029
     * @param string $dn Location to add the entry at.
1030
     * @param array $attributes A simple associative array of attributes.
1031
     */
1032
    public function add($dn, array $attributes)
1033
    {
1034
        $this->gateway->add($dn, $attributes);
1035
    }
1036
1037
    /**
1038
     * @param string $dn Distinguished name of the user
1039
     * @param string $password New password.
1040
     * @throws Exception
1041
     */
1042
    private function passwordHistoryWorkaround($dn, $password)
1043
    {
1044
        $generator = new RandomGenerator();
1045
        // 'Aa1' is there to satisfy the complexity criterion.
1046
        $tempPassword = sprintf('Aa1%s', substr($generator->randomToken('sha1'), 0, 21));
1047
        $this->gateway->resetPassword($dn, $tempPassword);
1048
        $this->gateway->changePassword($dn, $password, $tempPassword);
1049
    }
1050
1051
    /**
1052
     * Get a logger
1053
     *
1054
     * @return LoggerInterface
1055
     */
1056
    public function getLogger()
1057
    {
1058
        return Injector::inst()->get('Logger');
1059
    }
1060
}
1061