Completed
Pull Request — master (#18)
by Matt
04:55
created

LDAPService::flush()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

Loading history...
159
    }
160
161
    /**
162
     * Setter for gateway. Useful for overriding the gateway with a fake for testing.
163
     * @var LDAPGateway
164
     */
165
    public function setGateway($gateway)
166
    {
167
        $this->gateway = $gateway;
168
    }
169
170
    /**
171
     * Return the LDAP gateway currently in use. Can be strung together to access the underlying Zend\Ldap instance, or
172
     * the PHP ldap resource itself. For example:
173
     * - Get the Zend\Ldap object: $service->getGateway()->getLdap() // Zend\Ldap\Ldap object
174
     * - Get the underlying PHP ldap resource: $service->getGateway()->getLdap()->getResource() // php resource
175
     *
176
     * @return LDAPGateway
177
     */
178
    public function getGateway()
179
    {
180
        return $this->gateway;
181
    }
182
183
    /**
184
     * Checkes whether or not the service is enabled.
185
     *
186
     * @return bool
187
     */
188
    public function enabled()
189
    {
190
        $options = Config::inst()->get(LDAPGateway::class, 'options');
191
        return !empty($options);
192
    }
193
194
    /**
195
     * Authenticate the given username and password with LDAP.
196
     *
197
     * @param string $username
198
     * @param string $password
199
     *
200
     * @return array
201
     */
202
    public function authenticate($username, $password)
203
    {
204
        $result = $this->gateway->authenticate($username, $password);
205
        $messages = $result->getMessages();
206
207
        // all messages beyond the first one are for debugging and
208
        // not suitable to display to the user.
209
        foreach ($messages as $i => $message) {
210
            if ($i > 0) {
211
                $this->getLogger()->debug(str_replace("\n", "\n  ", $message));
212
            }
213
        }
214
215
        $message = $messages[0]; // first message is user readable, suitable for showing on login form
216
217
        // show better errors than the defaults for various status codes returned by LDAP
218
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_ACCOUNT_LOCKED_OUT') !== false) {
219
            $message = _t(
220
                __CLASS__ . '.ACCOUNTLOCKEDOUT',
221
                'Your account has been temporarily locked because of too many failed login attempts. ' .
222
                'Please try again later.'
223
            );
224
        }
225
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_LOGON_FAILURE') !== false) {
226
            $message = _t(
227
                __CLASS__ . '.INVALIDCREDENTIALS',
228
                'The provided details don\'t seem to be correct. Please try again.'
229
            );
230
        }
231
232
        return [
233
            'success' => $result->getCode() === 1,
234
            'identity' => $result->getIdentity(),
235
            'message' => $message,
236
            'code' => $result->getCode()
237
        ];
238
    }
239
240
    /**
241
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
242
     *
243
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
244
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
245
     * @return array
246
     */
247
    public function getNodes($cached = true, $attributes = [])
248
    {
249
        $cache = self::get_cache();
250
        $cacheKey = 'nodes' . md5(implode('', $attributes));
251
        $results = $cache->has($cacheKey);
252
253
        if (!$results || !$cached) {
254
            $results = [];
255
            $records = $this->gateway->getNodes(null, Ldap::SEARCH_SCOPE_SUB, $attributes);
256
            foreach ($records as $record) {
257
                $results[$record['dn']] = $record;
258
            }
259
260
            $cache->set($cacheKey, $results);
261
        }
262
263
        return $results;
264
    }
265
266
    /**
267
     * Return all AD groups in configured search locations, including all nested groups.
268
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
269
     * to use the default baseDn defined in the connection.
270
     *
271
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
272
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
273
     * @param string $indexBy Attribute to use as an index.
274
     * @return array
275
     */
276
    public function getGroups($cached = true, $attributes = [], $indexBy = 'dn')
277
    {
278
        $searchLocations = $this->config()->groups_search_locations ?: [null];
279
        $cache = self::get_cache();
280
        $cacheKey = 'groups' . md5(implode('', array_merge($searchLocations, $attributes)));
281
        $results = $cache->has($cacheKey);
282
283
        if (!$results || !$cached) {
284
            $results = [];
285
            foreach ($searchLocations as $searchLocation) {
286
                $records = $this->gateway->getGroups($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
287
                if (!$records) {
288
                    continue;
289
                }
290
291
                foreach ($records as $record) {
292
                    $results[$record[$indexBy]] = $record;
293
                }
294
            }
295
296
            $cache->set($cacheKey, $results);
297
        }
298
299
        if ($cached && $results === true) {
300
            $results = $cache->get($cacheKey);
301
        }
302
303
        return $results;
304
    }
305
306
    /**
307
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
308
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
309
     *
310
     * @param string $dn
311
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
312
     * @return array
313
     */
314
    public function getNestedGroups($dn, $attributes = [])
315
    {
316
        if (isset(self::$_cache_nested_groups[$dn])) {
317
            return self::$_cache_nested_groups[$dn];
318
        }
319
320
        $searchLocations = $this->config()->groups_search_locations ?: [null];
321
        $results = [];
322
        foreach ($searchLocations as $searchLocation) {
323
            $records = $this->gateway->getNestedGroups($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
324
            foreach ($records as $record) {
325
                $results[$record['dn']] = $record;
326
            }
327
        }
328
329
        self::$_cache_nested_groups[$dn] = $results;
330
        return $results;
331
    }
332
333
    /**
334
     * Get a particular AD group's data given a GUID.
335
     *
336
     * @param string $guid
337
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
338
     * @return array
339
     */
340
    public function getGroupByGUID($guid, $attributes = [])
341
    {
342
        $searchLocations = $this->config()->groups_search_locations ?: [null];
343
        foreach ($searchLocations as $searchLocation) {
344
            $records = $this->gateway->getGroupByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
345
            if ($records) {
346
                return $records[0];
347
            }
348
        }
349
    }
350
351
    /**
352
     * Get a particular AD group's data given a DN.
353
     *
354
     * @param string $dn
355
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
356
     * @return array
357
     */
358
    public function getGroupByDN($dn, $attributes = [])
359
    {
360
        $searchLocations = $this->config()->groups_search_locations ?: [null];
361
        foreach ($searchLocations as $searchLocation) {
362
            $records = $this->gateway->getGroupByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
363
            if ($records) {
364
                return $records[0];
365
            }
366
        }
367
    }
368
369
    /**
370
     * Return all AD users in configured search locations, including all users in nested groups.
371
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
372
     * to use the default baseDn defined in the connection.
373
     *
374
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
375
     * @return array
376
     */
377
    public function getUsers($attributes = [])
378
    {
379
        $searchLocations = $this->config()->users_search_locations ?: [null];
380
        $results = [];
381
382
        foreach ($searchLocations as $searchLocation) {
383
            $records = $this->gateway->getUsersWithIterator($searchLocation, $attributes);
384
            if (!$records) {
385
                continue;
386
            }
387
388
            foreach ($records as $record) {
389
                $results[$record['objectguid']] = $record;
390
            }
391
        }
392
393
        return $results;
394
    }
395
396
    /**
397
     * Get a specific AD user's data given a GUID.
398
     *
399
     * @param string $guid
400
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
401
     * @return array
402
     */
403
    public function getUserByGUID($guid, $attributes = [])
404
    {
405
        $searchLocations = $this->config()->users_search_locations ?: [null];
406
        foreach ($searchLocations as $searchLocation) {
407
            $records = $this->gateway->getUserByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
408
            if ($records) {
409
                return $records[0];
410
            }
411
        }
412
    }
413
414
    /**
415
     * Get a specific AD user's data given a DN.
416
     *
417
     * @param string $dn
418
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
419
     *
420
     * @return array
421
     */
422
    public function getUserByDN($dn, $attributes = [])
423
    {
424
        $searchLocations = $this->config()->users_search_locations ?: [null];
425
        foreach ($searchLocations as $searchLocation) {
426
            $records = $this->gateway->getUserByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
427
            if ($records) {
428
                return $records[0];
429
            }
430
        }
431
    }
432
433
    /**
434
     * Get a specific user's data given an email.
435
     *
436
     * @param string $email
437
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
438
     * @return array
439
     */
440
    public function getUserByEmail($email, $attributes = [])
441
    {
442
        $searchLocations = $this->config()->users_search_locations ?: [null];
443
        foreach ($searchLocations as $searchLocation) {
444
            $records = $this->gateway->getUserByEmail($email, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
445
            if ($records) {
446
                return $records[0];
447
            }
448
        }
449
    }
450
451
    /**
452
     * Get a specific user's data given a username.
453
     *
454
     * @param string $username
455
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
456
     * @return array
457
     */
458
    public function getUserByUsername($username, $attributes = [])
459
    {
460
        $searchLocations = $this->config()->users_search_locations ?: [null];
461
        foreach ($searchLocations as $searchLocation) {
462
            $records = $this->gateway->getUserByUsername(
463
                $username,
464
                $searchLocation,
465
                Ldap::SEARCH_SCOPE_SUB,
466
                $attributes
467
            );
468
            if ($records) {
469
                return $records[0];
470
            }
471
        }
472
    }
473
474
    /**
475
     * Get a username for an email.
476
     *
477
     * @param string $email
478
     * @return string|null
479
     */
480
    public function getUsernameByEmail($email)
481
    {
482
        $data = $this->getUserByEmail($email);
483
        if (empty($data)) {
484
            return null;
485
        }
486
487
        return $this->gateway->getCanonicalUsername($data);
488
    }
489
490
    /**
491
     * Given a group DN, get the group membership data in LDAP.
492
     *
493
     * @param string $dn
494
     * @return array
495
     */
496
    public function getLDAPGroupMembers($dn)
497
    {
498
        $groupObj = Group::get()->filter('DN', $dn)->first();
499
        $groupData = $this->getGroupByGUID($groupObj->GUID);
500
        $members = !empty($groupData['member']) ? $groupData['member'] : [];
501
        // If a user belongs to a single group, this comes through as a string.
502
        // Normalise to a array so it's consistent.
503
        if ($members && is_string($members)) {
504
            $members = [$members];
505
        }
506
507
        return $members;
508
    }
509
510
    /**
511
     * Update the current Member record with data from LDAP.
512
     *
513
     * It's allowed to pass an unwritten Member record here, because it's not always possible to satisfy
514
     * field constraints without importing data from LDAP (for example if the application requires Username
515
     * through a Validator). Even though unwritten, it still must have the GUID set.
516
     *
517
     * Constraints:
518
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
519
     *
520
     * @param Member $member
521
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
522
     *            If not given, the data will be looked up by the user's GUID.
523
     * @param bool $updateGroups controls whether to run the resource-intensive group update function as well. This is
524
     *                          skipped during login to reduce load.
525
     * @return bool
526
     * @internal param $Member
527
     */
528
    public function updateMemberFromLDAP(Member $member, $data = null, $updateGroups = true)
529
    {
530
        if (!$this->enabled()) {
531
            return false;
532
        }
533
534
        if (!$member->GUID) {
535
            $this->getLogger()->debug(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
536
            return false;
537
        }
538
539
        if (!$data) {
540
            $data = $this->getUserByGUID($member->GUID);
541
            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...
542
                $this->getLogger()->debug(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID));
543
                return false;
544
            }
545
        }
546
547
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
548
        $member->LastSynced = (string)DBDatetime::now();
549
550
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
551
            // Special handling required for attributes that don't exist in the response.
552
            if (!isset($data[$attribute])) {
553
                // a attribute we're expecting is missing from the LDAP response
554
                if ($this->config()->get("reset_missing_attributes")) {
555
                    // (Destructive) Reset the corresponding attribute on our side if instructed to do so.
556
                    if (method_exists($member->$field, "delete")
557
                        && method_exists($member->$field, "deleteFile")
558
                        && $member->$field->exists()
559
                    ) {
560
                        $member->$field->deleteFile();
561
                        $member->$field->delete();
562
                    } else {
563
                        $member->$field = null;
564
                    }
565
                // or log the information.
566
                } else {
567
                    $this->getLogger()->debug(
568
                        sprintf(
569
                            'Attribute %s configured in Member.ldap_field_mappings, ' .
570
                            'but no available attribute in AD data (GUID: %s, Member ID: %s)',
571
                            $attribute,
572
                            $data['objectguid'],
573
                            $member->ID
574
                        )
575
                    );
576
                }
577
578
                // No further processing required.
579
                continue;
580
            }
581
582
            if ($attribute == 'thumbnailphoto') {
583
                $this->processThumbnailPhoto($member, $field, $data, $attribute);
584
            } else {
585
                $member->$field = $data[$attribute];
586
            }
587
        }
588
589
        // if a default group was configured, ensure the user is in that group
590
        if ($this->config()->default_group) {
591
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
592
            if (!($group && $group->exists())) {
593
                $this->getLogger()->debug(
594
                    sprintf(
595
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
596
                        $this->config()->default_group
597
                    )
598
                );
599
            } else {
600
                // The member must exist before we can use it as a relation:
601
                if (!$member->exists()) {
602
                    $member->write();
603
                }
604
605
                $group->Members()->add($member, [
606
                    'IsImportedFromLDAP' => '1'
607
                ]);
608
            }
609
        }
610
611
        // this is to keep track of which groups the user gets mapped to
612
        // and we'll use that later to remove them from any groups that they're no longer mapped to
613
        $mappedGroupIDs = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $mappedGroupIDs is dead and can be removed.
Loading history...
614
615
        // Member must have an ID before manipulating Groups, otherwise they will not be added correctly.
616
        // However we cannot do a full ->write before the groups are associated, because this will upsync
617
        // the Member, in effect deleting all their LDAP group associations!
618
        $member->writeWithoutSync();
619
620
        if ($updateGroups) {
621
            $this->updateMemberGroups($data, $member);
622
        }
623
624
        // This will throw an exception if there are two distinct GUIDs with the same email address.
625
        // We are happy with a raw 500 here at this stage.
626
        $member->write();
627
    }
628
629
    /**
630
     * Attempts to process the thumbnail photo for a given user and store it against a {@link Member} object. This will
631
     * overwrite any old file with the same name. The filename of the photo will be set to 'thumbnailphoto-<GUID>.jpg'.
632
     *
633
     * At the moment only JPEG files are supported, as this is mainly to support Active Directory, which always provides
634
     * the photo in a JPEG format, and always at a specific resolution.
635
     *
636
     * @param Member $member The SilverStripe Member object we are storing this file on
637
     * @param string $fieldName The SilverStripe field name we are storing this new file against
638
     * @param array $data Array of all data returned about this user from LDAP
639
     * @param string $attributeName Name of the attribute in the $data array to get the binary blog from
640
     * @return boolean true on success, false on failure
641
     *
642
     * @throws ValidationException
643
     */
644
    private function processThumbnailPhoto(Member $member, $fieldName, $data, $attributeName)
645
    {
646
        $imageClass = $member->getRelationClass($fieldName);
647
        if ($imageClass !== Image::class && !is_subclass_of($imageClass, Image::class)) {
648
            $this->getLogger()->warning(
649
                sprintf(
650
                    'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an '
651
                        . 'Image class',
652
                    $fieldName
653
                )
654
            );
655
656
            return false;
657
        }
658
659
        // Use and update existing Image object (if one exists), or create a new image if not - prevents ID thrashing
660
        /** @var File $existingObj */
661
        $existingObj = $member->getComponent($fieldName);
662
        if ($existingObj && $existingObj->exists()) {
663
            $file = $existingObj;
664
665
            // If the file hashes match, and the file already exists, we don't need to update anything.
666
            $hash = $existingObj->File->getHash();
667
            if (hash_equals($hash, sha1($data[$attributeName]))) {
668
                return true;
669
            }
670
        } else {
671
            $file = new Image();
672
        }
673
674
        // Setup variables
675
        $thumbnailFolder = Folder::find_or_make($member->config()->ldap_thumbnail_path);
676
        $filename = sprintf('thumbnailphoto-%s.jpg', $data['objectguid']);
677
        $filePath = File::join_paths($thumbnailFolder->getFilename(), $filename);
678
        $fileCfg = [
679
            // if there's a filename conflict we've got new content so overwrite it.
680
            'conflict' => AssetStore::CONFLICT_OVERWRITE,
681
            'visibility' => AssetStore::VISIBILITY_PUBLIC
682
        ];
683
684
        $file->Title = sprintf('Thumbnail photo for %s', $data['displayname']);
685
        $file->ShowInSearch = false;
0 ignored issues
show
Documentation Bug introduced by
The property $ShowInSearch was declared of type string, but false is of type false. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

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