Completed
Pull Request — master (#80)
by Mateusz
02:27
created

LDAPService::passwordHistoryWorkaround()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 5
nc 1
nop 2
1
<?php
2
/**
3
 * Class LDAPService
4
 *
5
 * Provides LDAP operations expressed in terms of the SilverStripe domain.
6
 * All other modules should access LDAP through this class.
7
 *
8
 * This class builds on top of LDAPGateway's detailed code by adding:
9
 * - caching
10
 * - data aggregation and restructuring from multiple lower-level calls
11
 * - error handling
12
 *
13
 * LDAPService relies on Zend LDAP module's data structures for some parameters and some return values.
14
 */
15
class LDAPService extends Object implements Flushable
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
16
{
17
    /**
18
     * @var array
19
     */
20
    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...
21
        'gateway' => '%$LDAPGateway'
22
    ];
23
24
    /**
25
     * If configured, only user objects within these locations will be exposed to this service.
26
     *
27
     * @var array
28
     * @config
29
     */
30
    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...
31
32
    /**
33
     * If configured, only group objects within these locations will be exposed to this service.
34
     * @var array
35
     *
36
     * @config
37
     */
38
    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...
39
40
    /**
41
     * Location to create new users in (distinguished name).
42
     * @var string
43
     *
44
     * @config
45
     */
46
    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...
47
48
    /**
49
     * @var array
50
     */
51
    private static $_cache_nested_groups = [];
52
53
    /**
54
     * If this is configured to a "Code" value of a {@link Group} in SilverStripe, the user will always
55
     * be added to this group's membership when imported, regardless of any sort of group mappings.
56
     *
57
     * @var string
58
     * @config
59
     */
60
    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...
61
62
    /**
63
     * @var bool
64
     */
65
    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...
66
67
    /**
68
     * Get the cache objecgt used for LDAP results. Note that the default lifetime set here
69
     * is 8 hours, but you can change that by calling SS_Cache::set_lifetime('ldap', <lifetime in seconds>)
70
     *
71
     * @return Zend_Cache_Frontend
72
     */
73
    public static function get_cache()
74
    {
75
        return SS_Cache::factory('ldap', 'Output', [
76
            'automatic_serialization' => true,
77
            'lifetime' => 28800
78
        ]);
79
    }
80
81
    /**
82
     * Flushes out the LDAP results cache when flush=1 is called.
83
     */
84
    public static function flush()
85
    {
86
        $cache = self::get_cache();
87
        $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
88
    }
89
90
    /**
91
     * @var LDAPGateway
92
     */
93
    public $gateway;
94
95
    /**
96
     * Setter for gateway. Useful for overriding the gateway with a fake for testing.
97
     * @var LDAPGateway
98
     */
99
    public function setGateway($gateway)
100
    {
101
        $this->gateway = $gateway;
102
    }
103
104
    /**
105
     * Checkes whether or not the service is enabled.
106
     *
107
     * @return bool
108
     */
109
    public function enabled()
110
    {
111
        $options = Config::inst()->get('LDAPGateway', 'options');
112
        return !empty($options);
113
    }
114
115
    /**
116
     * Authenticate the given username and password with LDAP.
117
     *
118
     * @param string $username
119
     * @param string $password
120
     *
121
     * @return array
122
     */
123
    public function authenticate($username, $password)
124
    {
125
        $result = $this->gateway->authenticate($username, $password);
126
        $messages = $result->getMessages();
127
128
        // all messages beyond the first one are for debugging and
129
        // not suitable to display to the user.
130
        foreach ($messages as $i => $message) {
131
            if ($i > 0) {
132
                SS_Log::log(str_replace("\n", "\n  ", $message), SS_Log::DEBUG);
133
            }
134
        }
135
136
        $message = $messages[0]; // first message is user readable, suitable for showing on login form
137
138
        // show better errors than the defaults for various status codes returned by LDAP
139 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...
140
            $message = _t(
141
                'LDAPService.ACCOUNTLOCKEDOUT',
142
                'Your account has been temporarily locked because of too many failed login attempts. ' .
143
                'Please try again later.'
144
            );
145
        }
146 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...
147
            $message = _t(
148
                'LDAPService.INVALIDCREDENTIALS',
149
                'The provided details don\'t seem to be correct. Please try again.'
150
            );
151
        }
152
153
        return [
154
            'success' => $result->getCode() === 1,
155
            'identity' => $result->getIdentity(),
156
            'message' => $message
157
        ];
158
    }
159
160
    /**
161
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
162
     *
163
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
164
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
165
     * @return array
166
     */
167
    public function getNodes($cached = true, $attributes = [])
168
    {
169
        $cache = self::get_cache();
170
        $results = $cache->load('nodes' . md5(implode('', $attributes)));
171
172
        if (!$results || !$cached) {
173
            $results = [];
174
            $records = $this->gateway->getNodes(null, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
175
            foreach ($records as $record) {
176
                $results[$record['dn']] = $record;
177
            }
178
179
            $cache->save($results);
180
        }
181
182
        return $results;
183
    }
184
185
    /**
186
     * Return all AD groups in configured search locations, including all nested groups.
187
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
188
     * to use the default baseDn defined in the connection.
189
     *
190
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
191
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
192
     * @param string $indexBy Attribute to use as an index.
193
     * @return array
194
     */
195
    public function getGroups($cached = true, $attributes = [], $indexBy = 'dn')
196
    {
197
        $searchLocations = $this->config()->groups_search_locations ?: [null];
198
        $cache = self::get_cache();
199
        $results = $cache->load('groups' . md5(implode('', array_merge($searchLocations, $attributes))));
200
201
        if (!$results || !$cached) {
202
            $results = [];
203 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...
204
                $records = $this->gateway->getGroups($searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
205
                if (!$records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records 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...
206
                    continue;
207
                }
208
209
                foreach ($records as $record) {
210
                    $results[$record[$indexBy]] = $record;
211
                }
212
            }
213
214
            $cache->save($results);
215
        }
216
217
        return $results;
218
    }
219
220
    /**
221
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
222
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
223
     *
224
     * @param string $dn
225
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
226
     * @return array
227
     */
228
    public function getNestedGroups($dn, $attributes = [])
229
    {
230
        if (isset(self::$_cache_nested_groups[$dn])) {
231
            return self::$_cache_nested_groups[$dn];
232
        }
233
234
        $searchLocations = $this->config()->groups_search_locations ?: [null];
235
        $results = [];
236 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...
237
            $records = $this->gateway->getNestedGroups($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
238
            foreach ($records as $record) {
239
                $results[$record['dn']] = $record;
240
            }
241
        }
242
243
        self::$_cache_nested_groups[$dn] = $results;
244
        return $results;
245
    }
246
247
    /**
248
     * Get a particular AD group's data given a GUID.
249
     *
250
     * @param string $guid
251
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
252
     * @return array
253
     */
254 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...
255
    {
256
        $searchLocations = $this->config()->groups_search_locations ?: [null];
257
        foreach ($searchLocations as $searchLocation) {
258
            $records = $this->gateway->getGroupByGUID($guid, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
259
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records 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...
260
                return $records[0];
261
            }
262
        }
263
    }
264
265
    /**
266
     * Get a particular AD group's data given a DN.
267
     *
268
     * @param string $dn
269
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
270
     * @return array
271
     */
272 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...
273
    {
274
        $searchLocations = $this->config()->groups_search_locations ?: [null];
275
        foreach ($searchLocations as $searchLocation) {
276
            $records = $this->gateway->getGroupByDN($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
277
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records 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...
278
                return $records[0];
279
            }
280
        }
281
    }
282
283
    /**
284
     * Return all AD users in configured search locations, including all users in nested groups.
285
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
286
     * to use the default baseDn defined in the connection.
287
     *
288
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
289
     * @return array
290
     */
291
    public function getUsers($attributes = [])
292
    {
293
        $searchLocations = $this->config()->users_search_locations ?: [null];
294
        $results = [];
295
296 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...
297
            $records = $this->gateway->getUsers($searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
298
            if (!$records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records 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...
299
                continue;
300
            }
301
302
            foreach ($records as $record) {
303
                $results[$record['objectguid']] = $record;
304
            }
305
        }
306
307
        return $results;
308
    }
309
310
    /**
311
     * Get a specific AD user's data given a GUID.
312
     *
313
     * @param string $guid
314
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
315
     * @return array
316
     */
317 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...
318
    {
319
        $searchLocations = $this->config()->users_search_locations ?: [null];
320
        foreach ($searchLocations as $searchLocation) {
321
            $records = $this->gateway->getUserByGUID($guid, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
322
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records 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...
323
                return $records[0];
324
            }
325
        }
326
    }
327
328
    /**
329
     * Get a specific AD user's data given a DN.
330
     *
331
     * @param string $dn
332
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
333
     *
334
     * @return array
335
     */
336 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...
337
    {
338
        $searchLocations = $this->config()->users_search_locations ?: [null];
339
        foreach ($searchLocations as $searchLocation) {
340
            $records = $this->gateway->getUserByDN($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
341
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records 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...
342
                return $records[0];
343
            }
344
        }
345
    }
346
347
    /**
348
     * Get a specific user's data given an email.
349
     *
350
     * @param string $email
351
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
352
     * @return array
353
     */
354 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...
355
    {
356
        $searchLocations = $this->config()->users_search_locations ?: [null];
357
        foreach ($searchLocations as $searchLocation) {
358
            $records = $this->gateway->getUserByEmail($email, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
359
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records 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...
360
                return $records[0];
361
            }
362
        }
363
    }
364
365
    /**
366
     * Get a specific user's data given a username.
367
     *
368
     * @param string $username
369
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
370
     * @return array
371
     */
372 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...
373
    {
374
        $searchLocations = $this->config()->users_search_locations ?: [null];
375
        foreach ($searchLocations as $searchLocation) {
376
            $records = $this->gateway->getUserByUsername($username, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
377
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records 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...
378
                return $records[0];
379
            }
380
        }
381
    }
382
383
    /**
384
     * Get a username for an email.
385
     *
386
     * @param string $email
387
     * @return string|null
388
     */
389
    public function getUsernameByEmail($email)
390
    {
391
        $data = $this->getUserByEmail($email);
392
        if (empty($data)) {
393
            return null;
394
        }
395
396
        return $this->gateway->getCanonicalUsername($data);
397
    }
398
399
    /**
400
     * Given a group DN, get the group membership data in LDAP.
401
     *
402
     * @param string $dn
403
     * @return array
404
     */
405
    public function getLDAPGroupMembers($dn)
406
    {
407
        $groupObj = Group::get()->filter('DN', $dn)->first();
408
        $groupData = $this->getGroupByGUID($groupObj->GUID);
409
        $members = !empty($groupData['member']) ? $groupData['member'] : [];
410
        // If a user belongs to a single group, this comes through as a string.
411
        // Normalise to a array so it's consistent.
412
        if ($members && is_string($members)) {
413
            $members = [$members];
414
        }
415
416
        return $members;
417
    }
418
419
    /**
420
     * Update the current Member record with data from LDAP.
421
     *
422
     * Constraints:
423
     * - Member *must* be in the database before calling this as it will need the ID to be mapped to a {@link Group}.
424
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
425
     *
426
     * @param Member
427
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
428
     *            If not given, the data will be looked up by the user's GUID.
429
     * @return bool
430
     */
431
    public function updateMemberFromLDAP(Member $member, $data = null)
432
    {
433
        if (!$this->enabled()) {
434
            return false;
435
        }
436
437
        if (!$member->GUID) {
438
            SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
439
            return false;
440
        }
441
442
        if (!$data) {
443
            $data = $this->getUserByGUID($member->GUID);
444
            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...
445
                SS_Log::log(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID), SS_Log::WARN);
446
                return false;
447
            }
448
        }
449
450
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
451
        $member->LastSynced = (string)SS_Datetime::now();
452
453
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
454
            if (!isset($data[$attribute])) {
455
                SS_Log::log(sprintf(
456
                    'Attribute %s configured in Member.ldap_field_mappings, but no available attribute in AD data (GUID: %s, Member ID: %s)',
457
                    $attribute,
458
                    $data['objectguid'],
459
                    $member->ID
460
                ), SS_Log::NOTICE);
461
462
                continue;
463
            }
464
465
            if ($attribute == 'thumbnailphoto') {
466
                $imageClass = $member->getRelationClass($field);
467
                if ($imageClass !== 'Image' && !is_subclass_of($imageClass, 'Image')) {
468
                    SS_Log::log(sprintf(
469
                        'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an Image class',
470
                        $field
471
                    ), SS_Log::WARN);
472
473
                    continue;
474
                }
475
476
                $filename = sprintf('thumbnailphoto-%s.jpg', $data['samaccountname']);
477
                $path = ASSETS_DIR . '/' . $member->config()->ldap_thumbnail_path;
478
                $absPath = BASE_PATH . '/' . $path;
479
                if (!file_exists($absPath)) {
480
                    Filesystem::makeFolder($absPath);
481
                }
482
483
                // remove existing record if it exists
484
                $existingObj = $member->getComponent($field);
485
                if ($existingObj && $existingObj->exists()) {
486
                    $existingObj->delete();
487
                }
488
489
                // The image data is provided in raw binary.
490
                file_put_contents($absPath . '/' . $filename, $data[$attribute]);
491
                $record = new $imageClass();
492
                $record->Name = $filename;
493
                $record->Filename = $path . '/' . $filename;
494
                $record->write();
495
496
                $relationField = $field . 'ID';
497
                $member->{$relationField} = $record->ID;
498
            } else {
499
                $member->$field = $data[$attribute];
500
            }
501
        }
502
503
        // if a default group was configured, ensure the user is in that group
504
        if ($this->config()->default_group) {
505
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
506
            if (!($group && $group->exists())) {
507
                SS_Log::log(
508
                    sprintf(
509
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
510
                        $this->config()->default_group
511
                    ),
512
                    SS_Log::WARN
513
                );
514
            } else {
515
                $group->Members()->add($member, [
516
                    'IsImportedFromLDAP' => '1'
517
                ]);
518
            }
519
        }
520
521
        // this is to keep track of which groups the user gets mapped to
522
        // and we'll use that later to remove them from any groups that they're no longer mapped to
523
        $mappedGroupIDs = [];
524
525
        // ensure the user is in any mapped groups
526
        if (isset($data['memberof'])) {
527
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : [$data['memberof']];
528
            foreach ($ldapGroups as $groupDN) {
529
                foreach (LDAPGroupMapping::get() as $mapping) {
530
                    if (!$mapping->DN) {
531
                        SS_Log::log(
532
                            sprintf(
533
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
534
                                $mapping->ID
535
                            ),
536
                            SS_Log::WARN
537
                        );
538
                        continue;
539
                    }
540
541
                    // the user is a direct member of group with a mapping, add them to the SS group.
542 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...
543
                        $group = $mapping->Group();
544
                        if ($group && $group->exists()) {
545
                            $group->Members()->add($member, [
546
                                'IsImportedFromLDAP' => '1'
547
                            ]);
548
                            $mappedGroupIDs[] = $mapping->GroupID;
549
                        }
550
                    }
551
552
                    // the user *might* be a member of a nested group provided the scope of the mapping
553
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
554
                    // to see if they are a member of one of those. If they are, add them to the SS group
555
                    if ($mapping->Scope == 'Subtree') {
556
                        $childGroups = $this->getNestedGroups($mapping->DN, ['dn']);
557
                        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...
558
                            continue;
559
                        }
560
561
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
562 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...
563
                                $group = $mapping->Group();
564
                                if ($group && $group->exists()) {
565
                                    $group->Members()->add($member, [
566
                                        'IsImportedFromLDAP' => '1'
567
                                    ]);
568
                                    $mappedGroupIDs[] = $mapping->GroupID;
569
                                }
570
                            }
571
                        }
572
                    }
573
                }
574
            }
575
        }
576
577
        // remove the user from any previously mapped groups, where the mapping has since been removed
578
        $groupRecords = DB::query(sprintf('SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s', $member->ID));
579
        foreach ($groupRecords as $groupRecord) {
580
            if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
581
                $group = Group::get()->byId($groupRecord['GroupID']);
582
                // Some groups may no longer exist. SilverStripe does not clean up join tables.
583
                if ($group) {
584
                    $group->Members()->remove($member);
585
                }
586
            }
587
        }
588
        // This will throw an exception if there are two distinct GUIDs with the same email address.
589
        // We are happy with a raw 500 here at this stage.
590
        $member->write();
591
    }
592
593
    /**
594
     * Sync a specific Group by updating it with LDAP data.
595
     *
596
     * @param Group $group An existing Group or a new Group object
597
     * @param array $data LDAP group object data
598
     *
599
     * @return bool
600
     */
601
    public function updateGroupFromLDAP(Group $group, $data)
602
    {
603
        if (!$this->enabled()) {
604
            return false;
605
        }
606
607
        // Synchronise specific guaranteed fields.
608
        $group->Code = $data['samaccountname'];
609
        if (!empty($data['name'])) {
610
            $group->Title = $data['name'];
611
        } else {
612
            $group->Title = $data['samaccountname'];
613
        }
614
        if (!empty($data['description'])) {
615
            $group->Description = $data['description'];
616
        }
617
        $group->DN = $data['dn'];
618
        $group->LastSynced = (string)SS_Datetime::now();
619
        $group->write();
620
621
        // Mappings on this group are automatically maintained to contain just the group's DN.
622
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
623
        $hasCorrectMapping = false;
624
        foreach ($group->LDAPGroupMappings() as $mapping) {
625
            if ($mapping->DN === $data['dn']) {
626
                // This is the correct mapping we want to retain.
627
                $hasCorrectMapping = true;
628
            } else {
629
                $mapping->delete();
630
            }
631
        }
632
633
        // Second, if the main mapping was not found, add it in.
634
        if (!$hasCorrectMapping) {
635
            $mapping = new LDAPGroupMapping();
636
            $mapping->DN = $data['dn'];
0 ignored issues
show
Documentation introduced by
The property DN does not exist on object<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...
637
            $mapping->write();
638
            $group->LDAPGroupMappings()->add($mapping);
639
        }
640
    }
641
642
    /**
643
     * Creates a new LDAP user from the passed Member record.
644
     * Note that the Member record must have a non-empty Username field for this to work.
645
     *
646
     * @param Member $member
647
     */
648
    public function createLDAPUser(Member $member)
649
    {
650
        if (!$this->enabled()) {
651
            return;
652
        }
653
        if (empty($member->Username)) {
654
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
655
        }
656
        if (!$this->config()->new_users_dn) {
657
            throw new Exception('LDAPService::new_users_dn must be configured to create LDAP users');
658
        }
659
660
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
661
        $member->Username = strtolower($member->Username);
662
663
        // Create user in LDAP using available information.
664
        $dn = sprintf('CN=%s,%s', $member->Username, $this->config()->new_users_dn);
665
666
        try {
667
            $this->add($dn, [
668
                'objectclass' => 'user',
669
                'cn' => $member->Username,
670
                'accountexpires' => '9223372036854775807',
671
                'useraccountcontrol' => '66048',
672
                'userprincipalname' => sprintf(
673
                    '%s@%s',
674
                    $member->Username,
675
                    $this->gateway->config()->options['accountDomainName']
676
                ),
677
            ]);
678
        } catch (\Exception $e) {
679
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
680
        }
681
682
        $user = $this->getUserByUsername($member->Username);
683
        if (empty($user['objectguid'])) {
684
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
685
        }
686
687
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
688
        $member->GUID = $user['objectguid'];
689
    }
690
691
    /**
692
     * Update the Member data back to the corresponding LDAP user object.
693
     *
694
     * @param Member $member
695
     * @throws ValidationException
696
     */
697
    public function updateLDAPFromMember(Member $member)
698
    {
699
        if (!$this->enabled()) {
700
            return;
701
        }
702
        if (!$member->GUID) {
703
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
704
        }
705
706
        $data = $this->getUserByGUID($member->GUID);
707
        if (empty($data['objectguid'])) {
708
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
709
        }
710
711
        if (empty($member->Username)) {
712
            throw new ValidationException('Member missing Username. Cannot update LDAP user');
713
        }
714
715
        $dn = $data['distinguishedname'];
716
717
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
718
        $member->Username = strtolower($member->Username);
719
720
        try {
721
            // If the common name (cn) has changed, we need to ensure they've been moved
722
            // to the new DN, to avoid any clashes between user objects.
723
            if ($data['cn'] != $member->Username) {
724
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
725
                $this->move($dn, $newDn);
726
                $dn = $newDn;
727
            }
728
        } catch (\Exception $e) {
729
            throw new ValidationException('LDAP move failure: '.$e->getMessage());
730
        }
731
732
        try {
733
            $attributes = [
734
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
735
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
736
                'userprincipalname' => sprintf(
737
                    '%s@%s',
738
                    $member->Username,
739
                    $this->gateway->config()->options['accountDomainName']
740
                ),
741
            ];
742
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
743
                $relationClass = $member->getRelationClass($field);
744
                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...
745
                    // todo no support for writing back relations yet.
746
                } else {
747
                    $attributes[$attribute] = $member->$field;
748
                }
749
            }
750
751
            $this->update($dn, $attributes);
752
        } catch (\Exception $e) {
753
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
754
        }
755
    }
756
757
    /**
758
     * Ensure the user belongs to the correct groups in LDAP from their membership
759
     * to local LDAP mapped SilverStripe groups.
760
     *
761
     * This also removes them from LDAP groups if they've been taken out of one.
762
     * It will not affect group membership of non-mapped groups, so it will
763
     * not touch such internal AD groups like "Domain Users".
764
     *
765
     * @param Member $member
766
     */
767
    public function updateLDAPGroupsForMember(Member $member)
768
    {
769
        if (!$this->enabled()) {
770
            return;
771
        }
772
        if (!$member->GUID) {
773
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
774
        }
775
776
        $addGroups = [];
777
        $removeGroups = [];
778
779
        $user = $this->getUserByGUID($member->GUID);
780
        if (empty($user['objectguid'])) {
781
            throw new ValidationException('LDAP update failure: user missing GUID');
782
        }
783
784
        // If a user belongs to a single group, this comes through as a string.
785
        // Normalise to a array so it's consistent.
786
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : [];
787
        if ($existingGroups && is_string($existingGroups)) {
788
            $existingGroups = [$existingGroups];
789
        }
790
791
        foreach ($member->Groups() as $group) {
792
            if (!$group->GUID) {
793
                continue;
794
            }
795
796
            // mark this group as something we need to ensure the user belongs to in LDAP.
797
            $addGroups[] = $group->DN;
798
        }
799
800
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
801
        // see if the user should be removed from any of them.
802
        $remainingGroups = array_diff($existingGroups, $addGroups);
803
804
        foreach ($remainingGroups as $groupDn) {
805
            // We only want to be removing groups we have a local Group mapped to. Removing
806
            // membership for anything else would be bad!
807
            $group = Group::get()->filter('DN', $groupDn)->first();
808
            if (!$group || !$group->exists()) {
809
                continue;
810
            }
811
812
            // this group should be removed from the user's memberof attribute, as it's been removed.
813
            $removeGroups[] = $groupDn;
814
        }
815
816
        // go through the groups we want the user to be in and ensure they're in them.
817
        foreach ($addGroups as $groupDn) {
818
            $members = $this->getLDAPGroupMembers($groupDn);
819
820
            // this user is already in the group, no need to do anything.
821
            if (in_array($user['distinguishedname'], $members)) {
822
                continue;
823
            }
824
825
            $members[] = $user['distinguishedname'];
826
827
            try {
828
                $this->update($groupDn, ['member' => $members]);
829
            } catch (\Exception $e) {
830
                throw new ValidationException('LDAP group membership add failure: '.$e->getMessage());
831
            }
832
        }
833
834
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
835
        foreach ($removeGroups as $groupDn) {
836
            $members = $this->getLDAPGroupMembers($groupDn);
837
838
            // remove the user from the members data.
839
            if (in_array($user['distinguishedname'], $members)) {
840
                foreach ($members as $i => $dn) {
841
                    if ($dn == $user['distinguishedname']) {
842
                        unset($members[$i]);
843
                    }
844
                }
845
            }
846
847
            try {
848
                $this->update($groupDn, ['member' => $members]);
849
            } catch (\Exception $e) {
850
                throw new ValidationException('LDAP group membership remove failure: '.$e->getMessage());
851
            }
852
        }
853
    }
854
855
    /**
856
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
857
     * password in the `unicodePwd` attribute.
858
     *
859
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
860
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
861
     *
862
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
863
     *
864
     * @param Member $member
865
     * @param string $password
866
     * @param string|null $oldPassword Supply old password to perform a password change (as opposed to password reset)
867
     * @return ValidationResult
868
     * @throws Exception
869
     */
870
    public function setPassword(Member $member, $password, $oldPassword = null)
871
    {
872
        $validationResult = ValidationResult::create(true);
873
874
        $this->extend('onBeforeSetPassword', $member, $password, $validationResult);
875
876
        if (!$member->GUID) {
877
            SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
878
            $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
879
            return $validationResult;
880
        }
881
882
        $userData = $this->getUserByGUID($member->GUID);
883
        if (empty($userData['distinguishedname'])) {
884
            $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
885
            return $validationResult;
886
        }
887
888
        try {
889
            if (!empty($oldPassword)) {
890
                $this->gateway->changePassword($userData['distinguishedname'], $password, $oldPassword);
891
            } else if ($this->config()->password_history_workaround) {
892
                $this->passwordHistoryWorkaround($userData['distinguishedname'], $password);
893
            } else {
894
                $this->gateway->resetPassword($userData['distinguishedname'], $password);
895
            }
896
            $this->extend('onAfterSetPassword', $member, $password, $validationResult);
897
        } catch (Exception $e) {
898
            var_dump($e);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($e); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
899
            exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method setPassword() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
900
            $validationResult->error($e->getMessage());
0 ignored issues
show
Unused Code introduced by
$validationResult->error($e->getMessage()); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
901
        }
902
903
        return $validationResult;
904
    }
905
906
    /**
907
     * For samba4 directory, there is no way to enforce password history on password resets.
908
     * This only happens with changePassword (which requires the old password).
909
     * This works around it by making the old password up and setting it administratively.
910
     *
911
     * A cleaner fix would be to use the LDAP_SERVER_POLICY_HINTS_OID connection flag,
912
     * but it's not implemented in samba https://bugzilla.samba.org/show_bug.cgi?id=12020
913
     *
914
     * @param string $dn Distinguished name of the user
915
     * @param string $password New password.
916
     * @throws Exception
917
     */
918
    private function passwordHistoryWorkaround($dn, $password) {
919
        $generator = new RandomGenerator();
920
        // 'Aa1' is there to satisfy the complexity criterion.
921
        $tempPassword = sprintf('Aa1%s', substr($generator->randomToken('sha1'), 0, 21));
922
        $this->gateway->resetPassword($dn, $tempPassword);
923
        $this->gateway->changePassword($dn, $password, $tempPassword);
924
    }
925
926
    /**
927
     * Delete an LDAP user mapped to the Member record
928
     * @param Member $member
929
     */
930
    public function deleteLDAPMember(Member $member) {
931
        if (!$this->enabled()) {
932
            return;
933
        }
934
        if (!$member->GUID) {
935
            throw new ValidationException('Member missing GUID. Cannot delete LDAP user');
936
        }
937
        $data = $this->getUserByGUID($member->GUID);
938
        if (empty($data['distinguishedname'])) {
939
            throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute');
940
        }
941
942
        try {
943
            $this->delete($data['distinguishedname']);
944
        } catch (\Exception $e) {
945
            throw new ValidationException('LDAP delete user failed: '.$e->getMessage());
946
        }
947
    }
948
949
    /**
950
     * A simple proxy to LDAP update operation.
951
     *
952
     * @param string $dn Location to add the entry at.
953
     * @param array $attributes A simple associative array of attributes.
954
     */
955
    public function update($dn, array $attributes)
956
    {
957
        $this->gateway->update($dn, $attributes);
958
    }
959
960
    /**
961
     * A simple proxy to LDAP delete operation.
962
     *
963
     * @param string $dn Location of object to delete
964
     * @param bool $recursively Recursively delete nested objects?
965
     */
966
    public function delete($dn, $recursively = false)
967
    {
968
        $this->gateway->delete($dn, $recursively);
969
    }
970
971
    /**
972
     * A simple proxy to LDAP copy/delete operation.
973
     *
974
     * @param string $fromDn
975
     * @param string $toDn
976
     * @param bool $recursively Recursively move nested objects?
977
     */
978
    public function move($fromDn, $toDn, $recursively = false)
979
    {
980
        $this->gateway->move($fromDn, $toDn, $recursively);
981
    }
982
983
    /**
984
     * A simple proxy to LDAP add operation.
985
     *
986
     * @param string $dn Location to add the entry at.
987
     * @param array $attributes A simple associative array of attributes.
988
     */
989
    public function add($dn, array $attributes)
990
    {
991
        $this->gateway->add($dn, $attributes);
992
    }
993
}
994