Passed
Pull Request — master (#18)
by Matt
02:29
created

LDAPService::processThumbnailPhoto()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 43
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

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

156
        /** @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...
157
    }
158
159
    /**
160
     * Setter for gateway. Useful for overriding the gateway with a fake for testing.
161
     * @var LDAPGateway
162
     */
163
    public function setGateway($gateway)
164
    {
165
        $this->gateway = $gateway;
166
    }
167
168
    /**
169
     * Return the LDAP gateway currently in use. Can be strung together to access the underlying Zend\Ldap instance, or
170
     * the PHP ldap resource itself. For example:
171
     * - Get the Zend\Ldap object: $service->getGateway()->getLdap() // Zend\Ldap\Ldap object
172
     * - Get the underlying PHP ldap resource: $service->getGateway()->getLdap()->getResource() // php resource
173
     *
174
     * @return LDAPGateway
175
     */
176
    public function getGateway()
177
    {
178
        return $this->gateway;
179
    }
180
181
    /**
182
     * Checkes whether or not the service is enabled.
183
     *
184
     * @return bool
185
     */
186
    public function enabled()
187
    {
188
        $options = Config::inst()->get(LDAPGateway::class, 'options');
189
        return !empty($options);
190
    }
191
192
    /**
193
     * Authenticate the given username and password with LDAP.
194
     *
195
     * @param string $username
196
     * @param string $password
197
     *
198
     * @return array
199
     */
200
    public function authenticate($username, $password)
201
    {
202
        $result = $this->gateway->authenticate($username, $password);
203
        $messages = $result->getMessages();
204
205
        // all messages beyond the first one are for debugging and
206
        // not suitable to display to the user.
207
        foreach ($messages as $i => $message) {
208
            if ($i > 0) {
209
                $this->getLogger()->debug(str_replace("\n", "\n  ", $message));
210
            }
211
        }
212
213
        $message = $messages[0]; // first message is user readable, suitable for showing on login form
214
215
        // show better errors than the defaults for various status codes returned by LDAP
216
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_ACCOUNT_LOCKED_OUT') !== false) {
217
            $message = _t(
218
                __CLASS__ . '.ACCOUNTLOCKEDOUT',
219
                'Your account has been temporarily locked because of too many failed login attempts. ' .
220
                'Please try again later.'
221
            );
222
        }
223
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_LOGON_FAILURE') !== false) {
224
            $message = _t(
225
                __CLASS__ . '.INVALIDCREDENTIALS',
226
                'The provided details don\'t seem to be correct. Please try again.'
227
            );
228
        }
229
230
        return [
231
            'success' => $result->getCode() === 1,
232
            'identity' => $result->getIdentity(),
233
            'message' => $message,
234
            'code' => $result->getCode()
235
        ];
236
    }
237
238
    /**
239
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
240
     *
241
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
242
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
243
     * @return array
244
     */
245
    public function getNodes($cached = true, $attributes = [])
246
    {
247
        $cache = self::get_cache();
248
        $cacheKey = 'nodes' . md5(implode('', $attributes));
249
        $results = $cache->has($cacheKey);
250
251
        if (!$results || !$cached) {
252
            $results = [];
253
            $records = $this->gateway->getNodes(null, Ldap::SEARCH_SCOPE_SUB, $attributes);
254
            foreach ($records as $record) {
255
                $results[$record['dn']] = $record;
256
            }
257
258
            $cache->set($cacheKey, $results);
259
        }
260
261
        return $results;
262
    }
263
264
    /**
265
     * Return all AD groups in configured search locations, including all nested groups.
266
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
267
     * to use the default baseDn defined in the connection.
268
     *
269
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
270
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
271
     * @param string $indexBy Attribute to use as an index.
272
     * @return array
273
     */
274
    public function getGroups($cached = true, $attributes = [], $indexBy = 'dn')
275
    {
276
        $searchLocations = $this->config()->groups_search_locations ?: [null];
277
        $cache = self::get_cache();
278
        $cacheKey = 'groups' . md5(implode('', array_merge($searchLocations, $attributes)));
279
        $results = $cache->has($cacheKey);
280
281
        if (!$results || !$cached) {
282
            $results = [];
283
            foreach ($searchLocations as $searchLocation) {
284
                $records = $this->gateway->getGroups($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
285
                if (!$records) {
286
                    continue;
287
                }
288
289
                foreach ($records as $record) {
290
                    $results[$record[$indexBy]] = $record;
291
                }
292
            }
293
294
            $cache->set($cacheKey, $results);
295
        }
296
297
        if ($cached && $results === true) {
298
            $results = $cache->get($cacheKey);
299
        }
300
301
        return $results;
302
    }
303
304
    /**
305
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
306
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
307
     *
308
     * @param string $dn
309
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
310
     * @return array
311
     */
312
    public function getNestedGroups($dn, $attributes = [])
313
    {
314
        if (isset(self::$_cache_nested_groups[$dn])) {
315
            return self::$_cache_nested_groups[$dn];
316
        }
317
318
        $searchLocations = $this->config()->groups_search_locations ?: [null];
319
        $results = [];
320
        foreach ($searchLocations as $searchLocation) {
321
            $records = $this->gateway->getNestedGroups($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
322
            foreach ($records as $record) {
323
                $results[$record['dn']] = $record;
324
            }
325
        }
326
327
        self::$_cache_nested_groups[$dn] = $results;
328
        return $results;
329
    }
330
331
    /**
332
     * Get a particular AD group's data given a GUID.
333
     *
334
     * @param string $guid
335
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
336
     * @return array
337
     */
338
    public function getGroupByGUID($guid, $attributes = [])
339
    {
340
        $searchLocations = $this->config()->groups_search_locations ?: [null];
341
        foreach ($searchLocations as $searchLocation) {
342
            $records = $this->gateway->getGroupByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
343
            if ($records) {
344
                return $records[0];
345
            }
346
        }
347
    }
348
349
    /**
350
     * Get a particular AD group's data given a DN.
351
     *
352
     * @param string $dn
353
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
354
     * @return array
355
     */
356
    public function getGroupByDN($dn, $attributes = [])
357
    {
358
        $searchLocations = $this->config()->groups_search_locations ?: [null];
359
        foreach ($searchLocations as $searchLocation) {
360
            $records = $this->gateway->getGroupByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
361
            if ($records) {
362
                return $records[0];
363
            }
364
        }
365
    }
366
367
    /**
368
     * Return all AD users in configured search locations, including all users in nested groups.
369
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
370
     * to use the default baseDn defined in the connection.
371
     *
372
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
373
     * @return array
374
     */
375
    public function getUsers($attributes = [])
376
    {
377
        $searchLocations = $this->config()->users_search_locations ?: [null];
378
        $results = [];
379
380
        foreach ($searchLocations as $searchLocation) {
381
            $records = $this->gateway->getUsersWithIterator($searchLocation, $attributes);
382
            if (!$records) {
383
                continue;
384
            }
385
386
            foreach ($records as $record) {
387
                $results[$record['objectguid']] = $record;
388
            }
389
        }
390
391
        return $results;
392
    }
393
394
    /**
395
     * Get a specific AD user's data given a GUID.
396
     *
397
     * @param string $guid
398
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
399
     * @return array
400
     */
401
    public function getUserByGUID($guid, $attributes = [])
402
    {
403
        $searchLocations = $this->config()->users_search_locations ?: [null];
404
        foreach ($searchLocations as $searchLocation) {
405
            $records = $this->gateway->getUserByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
406
            if ($records) {
407
                return $records[0];
408
            }
409
        }
410
    }
411
412
    /**
413
     * Get a specific AD user's data given a DN.
414
     *
415
     * @param string $dn
416
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
417
     *
418
     * @return array
419
     */
420
    public function getUserByDN($dn, $attributes = [])
421
    {
422
        $searchLocations = $this->config()->users_search_locations ?: [null];
423
        foreach ($searchLocations as $searchLocation) {
424
            $records = $this->gateway->getUserByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
425
            if ($records) {
426
                return $records[0];
427
            }
428
        }
429
    }
430
431
    /**
432
     * Get a specific user's data given an email.
433
     *
434
     * @param string $email
435
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
436
     * @return array
437
     */
438
    public function getUserByEmail($email, $attributes = [])
439
    {
440
        $searchLocations = $this->config()->users_search_locations ?: [null];
441
        foreach ($searchLocations as $searchLocation) {
442
            $records = $this->gateway->getUserByEmail($email, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
443
            if ($records) {
444
                return $records[0];
445
            }
446
        }
447
    }
448
449
    /**
450
     * Get a specific user's data given a username.
451
     *
452
     * @param string $username
453
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
454
     * @return array
455
     */
456
    public function getUserByUsername($username, $attributes = [])
457
    {
458
        $searchLocations = $this->config()->users_search_locations ?: [null];
459
        foreach ($searchLocations as $searchLocation) {
460
            $records = $this->gateway->getUserByUsername(
461
                $username,
462
                $searchLocation,
463
                Ldap::SEARCH_SCOPE_SUB,
464
                $attributes
465
            );
466
            if ($records) {
467
                return $records[0];
468
            }
469
        }
470
    }
471
472
    /**
473
     * Get a username for an email.
474
     *
475
     * @param string $email
476
     * @return string|null
477
     */
478
    public function getUsernameByEmail($email)
479
    {
480
        $data = $this->getUserByEmail($email);
481
        if (empty($data)) {
482
            return null;
483
        }
484
485
        return $this->gateway->getCanonicalUsername($data);
486
    }
487
488
    /**
489
     * Given a group DN, get the group membership data in LDAP.
490
     *
491
     * @param string $dn
492
     * @return array
493
     */
494
    public function getLDAPGroupMembers($dn)
495
    {
496
        $groupObj = Group::get()->filter('DN', $dn)->first();
497
        $groupData = $this->getGroupByGUID($groupObj->GUID);
498
        $members = !empty($groupData['member']) ? $groupData['member'] : [];
499
        // If a user belongs to a single group, this comes through as a string.
500
        // Normalise to a array so it's consistent.
501
        if ($members && is_string($members)) {
502
            $members = [$members];
503
        }
504
505
        return $members;
506
    }
507
508
    /**
509
     * Update the current Member record with data from LDAP.
510
     *
511
     * It's allowed to pass an unwritten Member record here, because it's not always possible to satisfy
512
     * field constraints without importing data from LDAP (for example if the application requires Username
513
     * through a Validator). Even though unwritten, it still must have the GUID set.
514
     *
515
     * Constraints:
516
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
517
     *
518
     * @param Member $member
519
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
520
     *            If not given, the data will be looked up by the user's GUID.
521
     * @param bool $updateGroups controls whether to run the resource-intensive group update function as well. This is
522
     *                          skipped during login to reduce load.
523
     * @return bool
524
     * @internal param $Member
525
     */
526
    public function updateMemberFromLDAP(Member $member, $data = null, $updateGroups = true)
527
    {
528
        if (!$this->enabled()) {
529
            return false;
530
        }
531
532
        if (!$member->GUID) {
533
            $this->getLogger()->debug(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
534
            return false;
535
        }
536
537
        if (!$data) {
538
            $data = $this->getUserByGUID($member->GUID);
539
            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...
540
                $this->getLogger()->debug(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID));
541
                return false;
542
            }
543
        }
544
545
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
546
        $member->LastSynced = (string)DBDatetime::now();
547
548
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
549
            if (!isset($data[$attribute])) {
550
                $this->getLogger()->notice(
551
                    sprintf(
552
                        'Attribute %s configured in Member.ldap_field_mappings, ' .
553
                                'but no available attribute in AD data (GUID: %s, Member ID: %s)',
554
                        $attribute,
555
                        $data['objectguid'],
556
                        $member->ID
557
                    )
558
                );
559
560
                continue;
561
            }
562
563
            if ($attribute == 'thumbnailphoto') {
564
                $this->processThumbnailPhoto($member, $field, $data, $attribute);
565
            } else {
566
                $member->$field = $data[$attribute];
567
            }
568
        }
569
570
        // if a default group was configured, ensure the user is in that group
571
        if ($this->config()->default_group) {
572
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
573
            if (!($group && $group->exists())) {
574
                $this->getLogger()->debug(
575
                    sprintf(
576
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
577
                        $this->config()->default_group
578
                    )
579
                );
580
            } else {
581
                // The member must exist before we can use it as a relation:
582
                if (!$member->exists()) {
583
                    $member->write();
584
                }
585
586
                $group->Members()->add($member, [
587
                    'IsImportedFromLDAP' => '1'
588
                ]);
589
            }
590
        }
591
592
        // this is to keep track of which groups the user gets mapped to
593
        // and we'll use that later to remove them from any groups that they're no longer mapped to
594
        $mappedGroupIDs = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $mappedGroupIDs is dead and can be removed.
Loading history...
595
596
        // Member must have an ID before manipulating Groups, otherwise they will not be added correctly.
597
        // However we cannot do a full ->write before the groups are associated, because this will upsync
598
        // the Member, in effect deleting all their LDAP group associations!
599
        $member->writeWithoutSync();
600
601
        if ($updateGroups) {
602
            $this->updateMemberGroups($data, $member);
603
        }
604
605
        // This will throw an exception if there are two distinct GUIDs with the same email address.
606
        // We are happy with a raw 500 here at this stage.
607
        $member->write();
608
    }
609
610
    /**
611
     * Attempts to process the thumbnail photo for a given user and store it against a {@link Member} object. This will
612
     * overwrite any old file with the same name. The filename of the photo will be set to 'thumbnailphoto-<GUID>.jpg'.
613
     *
614
     * At the moment only JPEG files are supported, as this is mainly to support Active Directory, which always provides
615
     * the photo in a JPEG format, and always at a specific resolution.
616
     *
617
     * @param Member $member The SilverStripe Member object we are storing this file on
618
     * @param string $fieldName The SilverStripe field name we are storing this new file against
619
     * @param array $data Array of all data returned about this user from LDAP
620
     * @param string $attributeName Name of the attribute in the $data array to get the binary blog from
621
     * @return boolean true on success, false on failure
622
     */
623
    private function processThumbnailPhoto(Member $member, $fieldName, $data, $attributeName)
624
    {
625
        $imageClass = $member->getRelationClass($fieldName);
626
        if ($imageClass !== Image::class && !is_subclass_of($imageClass, Image::class)) {
627
            $this->getLogger()->warning(
628
                sprintf(
629
                    'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an '
630
                        . 'Image class',
631
                    $fieldName
632
                )
633
            );
634
635
            return false;
636
        }
637
638
        // Use and update existing Image object (if one exists), or create a new image if not - prevents ID thrashing
639
        /** @var File $existingObj */
640
        $existingObj = $member->getComponent($fieldName);
641
        if ($existingObj && $existingObj->exists()) {
642
            $file = $existingObj;
643
        } else {
644
            $file = new Image();
645
        }
646
647
        // Setup variables
648
        $thumbnailFolder = Folder::find_or_make($member->config()->ldap_thumbnail_path);
649
        $filename = sprintf('thumbnailphoto-%s.jpg', $data['objectguid']);
650
        $filePath = File::join_paths($thumbnailFolder->getFilename(), $filename);
651
        $fileCfg = [
652
            'conflict' => AssetStore::CONFLICT_OVERWRITE,
653
            'visibility' => AssetStore::VISIBILITY_PUBLIC
654
        ];
655
656
        $file->Title = sprintf('Thumbnail photo for %s', $data['displayname']);
657
        $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...
658
        $file->ParentID = $thumbnailFolder->ID;
659
        $file->setFromString($data[$attributeName], $filePath, null, null, $fileCfg);
660
        $file->write();
661
        $file->publishRecursive();
662
663
        if ($file->exists()) {
664
            $relationField = sprintf('%sID', $fieldName);
665
            $member->{$relationField} = $file->ID;
666
        }
667
    }
668
669
    /**
670
     * Ensure the user is mapped to any applicable groups.
671
     * @param array $data
672
     * @param Member $member
673
     */
674
    public function updateMemberGroups($data, Member $member)
675
    {
676
        if (isset($data['memberof'])) {
677
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : [$data['memberof']];
678
            foreach ($ldapGroups as $groupDN) {
679
                foreach (LDAPGroupMapping::get() as $mapping) {
680
                    if (!$mapping->DN) {
681
                        $this->getLogger()->debug(
682
                            sprintf(
683
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
684
                                $mapping->ID
685
                            )
686
                        );
687
                        continue;
688
                    }
689
690
                    // the user is a direct member of group with a mapping, add them to the SS group.
691
                    if ($mapping->DN == $groupDN) {
692
                        $group = $mapping->Group();
693
                        if ($group && $group->exists()) {
694
                            $group->Members()->add($member, [
695
                                'IsImportedFromLDAP' => '1'
696
                            ]);
697
                            $mappedGroupIDs[] = $mapping->GroupID;
698
                        }
699
                    }
700
701
                    // the user *might* be a member of a nested group provided the scope of the mapping
702
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
703
                    // to see if they are a member of one of those. If they are, add them to the SS group
704
                    if ($mapping->Scope == 'Subtree') {
705
                        $childGroups = $this->getNestedGroups($mapping->DN, ['dn']);
706
                        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...
707
                            continue;
708
                        }
709
710
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
711
                            if ($childGroupDN == $groupDN) {
712
                                $group = $mapping->Group();
713
                                if ($group && $group->exists()) {
714
                                    $group->Members()->add($member, [
715
                                        'IsImportedFromLDAP' => '1'
716
                                    ]);
717
                                    $mappedGroupIDs[] = $mapping->GroupID;
718
                                }
719
                            }
720
                        }
721
                    }
722
                }
723
            }
724
        }
725
726
        // remove the user from any previously mapped groups, where the mapping has since been removed
727
        $groupRecords = DB::query(
728
            sprintf(
729
                'SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s',
730
                $member->ID
731
            )
732
        );
733
734
        if (!empty($mappedGroupIDs)) {
735
            foreach ($groupRecords as $groupRecord) {
736
                if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
737
                    $group = Group::get()->byId($groupRecord['GroupID']);
738
                    // Some groups may no longer exist. SilverStripe does not clean up join tables.
739
                    if ($group) {
740
                        $group->Members()->remove($member);
741
                    }
742
                }
743
            }
744
        }
745
    }
746
747
    /**
748
     * Sync a specific Group by updating it with LDAP data.
749
     *
750
     * @param Group $group An existing Group or a new Group object
751
     * @param array $data LDAP group object data
752
     *
753
     * @return bool
754
     */
755
    public function updateGroupFromLDAP(Group $group, $data)
756
    {
757
        if (!$this->enabled()) {
758
            return false;
759
        }
760
761
        // Synchronise specific guaranteed fields.
762
        $group->Code = $data['samaccountname'];
763
        $group->Title = $data['samaccountname'];
764
        if (!empty($data['description'])) {
765
            $group->Description = $data['description'];
766
        }
767
        $group->DN = $data['dn'];
768
        $group->LastSynced = (string)DBDatetime::now();
769
        $group->write();
770
771
        // Mappings on this group are automatically maintained to contain just the group's DN.
772
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
773
        $hasCorrectMapping = false;
774
        foreach ($group->LDAPGroupMappings() as $mapping) {
775
            if ($mapping->DN === $data['dn']) {
776
                // This is the correct mapping we want to retain.
777
                $hasCorrectMapping = true;
778
            } else {
779
                $mapping->delete();
780
            }
781
        }
782
783
        // Second, if the main mapping was not found, add it in.
784
        if (!$hasCorrectMapping) {
785
            $mapping = new LDAPGroupMapping();
786
            $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...
787
            $mapping->write();
788
            $group->LDAPGroupMappings()->add($mapping);
789
        }
790
    }
791
792
    /**
793
     * Creates a new LDAP user from the passed Member record.
794
     * Note that the Member record must have a non-empty Username field for this to work.
795
     *
796
     * @param Member $member
797
     * @throws ValidationException
798
     * @throws Exception
799
     */
800
    public function createLDAPUser(Member $member)
801
    {
802
        if (!$this->enabled()) {
803
            return;
804
        }
805
        if (empty($member->Username)) {
806
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
807
        }
808
        if (!$this->config()->new_users_dn) {
809
            throw new Exception('LDAPService::new_users_dn must be configured to create LDAP users');
810
        }
811
812
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
813
        $member->Username = strtolower($member->Username);
814
815
        // Create user in LDAP using available information.
816
        $dn = sprintf('CN=%s,%s', $member->Username, $this->config()->new_users_dn);
817
818
        try {
819
            $this->add($dn, [
820
                'objectclass' => 'user',
821
                'cn' => $member->Username,
822
                'accountexpires' => '9223372036854775807',
823
                'useraccountcontrol' => '66048',
824
                'userprincipalname' => sprintf(
825
                    '%s@%s',
826
                    $member->Username,
827
                    $this->gateway->config()->options['accountDomainName']
828
                ),
829
            ]);
830
        } catch (Exception $e) {
831
            throw new ValidationException('LDAP synchronisation failure: ' . $e->getMessage());
832
        }
833
834
        $user = $this->getUserByUsername($member->Username);
835
        if (empty($user['objectguid'])) {
836
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
837
        }
838
839
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
840
        $member->GUID = $user['objectguid'];
841
    }
842
843
    /**
844
     * Creates a new LDAP group from the passed Group record.
845
     *
846
     * @param Group $group
847
     * @throws ValidationException
848
     */
849
    public function createLDAPGroup(Group $group)
850
    {
851
        if (!$this->enabled()) {
852
            return;
853
        }
854
        if (empty($group->Title)) {
855
            throw new ValidationException('Group missing Title. Cannot create LDAP group');
856
        }
857
        if (!$this->config()->new_groups_dn) {
858
            throw new Exception('LDAPService::new_groups_dn must be configured to create LDAP groups');
859
        }
860
861
        // LDAP isn't really meant to distinguish between a Title and Code. Squash them.
862
        $group->Code = $group->Title;
863
864
        $dn = sprintf('CN=%s,%s', $group->Title, $this->config()->new_groups_dn);
865
        try {
866
            $this->add($dn, [
867
                'objectclass' => 'group',
868
                'cn' => $group->Title,
869
                'name' => $group->Title,
870
                'samaccountname' => $group->Title,
871
                'description' => $group->Description,
872
                'distinguishedname' => $dn
873
            ]);
874
        } catch (Exception $e) {
875
            throw new ValidationException('LDAP group creation failure: ' . $e->getMessage());
876
        }
877
878
        $data = $this->getGroupByDN($dn);
879
        if (empty($data['objectguid'])) {
880
            throw new ValidationException(
881
                new ValidationResult(
882
                    false,
883
                    'LDAP group creation failure: group might have been created in LDAP. GUID is missing.'
884
                )
885
            );
886
        }
887
888
        // Creation was successful, mark the group as LDAP managed by setting the GUID.
889
        $group->GUID = $data['objectguid'];
890
        $group->DN = $data['dn'];
891
    }
892
893
    /**
894
     * Update the Member data back to the corresponding LDAP user object.
895
     *
896
     * @param Member $member
897
     * @throws ValidationException
898
     */
899
    public function updateLDAPFromMember(Member $member)
900
    {
901
        if (!$this->enabled()) {
902
            return;
903
        }
904
        if (!$member->GUID) {
905
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
906
        }
907
908
        $data = $this->getUserByGUID($member->GUID);
909
        if (empty($data['objectguid'])) {
910
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
911
        }
912
913
        if (empty($member->Username)) {
914
            throw new ValidationException('Member missing Username. Cannot update LDAP user');
915
        }
916
917
        $dn = $data['distinguishedname'];
918
919
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
920
        $member->Username = strtolower($member->Username);
921
922
        try {
923
            // If the common name (cn) has changed, we need to ensure they've been moved
924
            // to the new DN, to avoid any clashes between user objects.
925
            if ($data['cn'] != $member->Username) {
926
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
927
                $this->move($dn, $newDn);
928
                $dn = $newDn;
929
            }
930
        } catch (Exception $e) {
931
            throw new ValidationException('LDAP move failure: '.$e->getMessage());
932
        }
933
934
        try {
935
            $attributes = [
936
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
937
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
938
                'userprincipalname' => sprintf(
939
                    '%s@%s',
940
                    $member->Username,
941
                    $this->gateway->config()->options['accountDomainName']
942
                ),
943
            ];
944
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
945
                $relationClass = $member->getRelationClass($field);
946
                if ($relationClass) {
947
                    // todo no support for writing back relations yet.
948
                } else {
949
                    $attributes[$attribute] = $member->$field;
950
                }
951
            }
952
953
            $this->update($dn, $attributes);
954
        } catch (Exception $e) {
955
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
956
        }
957
    }
958
959
    /**
960
     * Ensure the user belongs to the correct groups in LDAP from their membership
961
     * to local LDAP mapped SilverStripe groups.
962
     *
963
     * This also removes them from LDAP groups if they've been taken out of one.
964
     * It will not affect group membership of non-mapped groups, so it will
965
     * not touch such internal AD groups like "Domain Users".
966
     *
967
     * @param Member $member
968
     * @throws ValidationException
969
     */
970
    public function updateLDAPGroupsForMember(Member $member)
971
    {
972
        if (!$this->enabled()) {
973
            return;
974
        }
975
        if (!$member->GUID) {
976
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
977
        }
978
979
        $addGroups = [];
980
        $removeGroups = [];
981
982
        $user = $this->getUserByGUID($member->GUID);
983
        if (empty($user['objectguid'])) {
984
            throw new ValidationException('LDAP update failure: user missing GUID');
985
        }
986
987
        // If a user belongs to a single group, this comes through as a string.
988
        // Normalise to a array so it's consistent.
989
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : [];
990
        if ($existingGroups && is_string($existingGroups)) {
991
            $existingGroups = [$existingGroups];
992
        }
993
994
        foreach ($member->Groups() as $group) {
995
            if (!$group->GUID) {
996
                continue;
997
            }
998
999
            // mark this group as something we need to ensure the user belongs to in LDAP.
1000
            $addGroups[] = $group->DN;
1001
        }
1002
1003
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
1004
        // see if the user should be removed from any of them.
1005
        $remainingGroups = array_diff($existingGroups, $addGroups);
1006
1007
        foreach ($remainingGroups as $groupDn) {
1008
            // We only want to be removing groups we have a local Group mapped to. Removing
1009
            // membership for anything else would be bad!
1010
            $group = Group::get()->filter('DN', $groupDn)->first();
1011
            if (!$group || !$group->exists()) {
1012
                continue;
1013
            }
1014
1015
            // this group should be removed from the user's memberof attribute, as it's been removed.
1016
            $removeGroups[] = $groupDn;
1017
        }
1018
1019
        // go through the groups we want the user to be in and ensure they're in them.
1020
        foreach ($addGroups as $groupDn) {
1021
            $this->addLDAPUserToGroup($user['distinguishedname'], $groupDn);
1022
        }
1023
1024
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
1025
        foreach ($removeGroups as $groupDn) {
1026
            $members = $this->getLDAPGroupMembers($groupDn);
1027
1028
            // remove the user from the members data.
1029
            if (in_array($user['distinguishedname'], $members)) {
1030
                foreach ($members as $i => $dn) {
1031
                    if ($dn == $user['distinguishedname']) {
1032
                        unset($members[$i]);
1033
                    }
1034
                }
1035
            }
1036
1037
            try {
1038
                $this->update($groupDn, ['member' => $members]);
1039
            } catch (Exception $e) {
1040
                throw new ValidationException('LDAP group membership remove failure: ' . $e->getMessage());
1041
            }
1042
        }
1043
    }
1044
1045
    /**
1046
     * Add LDAP user by DN to LDAP group.
1047
     *
1048
     * @param string $userDn
1049
     * @param string $groupDn
1050
     * @throws Exception
1051
     */
1052
    public function addLDAPUserToGroup($userDn, $groupDn)
1053
    {
1054
        $members = $this->getLDAPGroupMembers($groupDn);
1055
1056
        // this user is already in the group, no need to do anything.
1057
        if (in_array($userDn, $members)) {
1058
            return;
1059
        }
1060
1061
        $members[] = $userDn;
1062
1063
        try {
1064
            $this->update($groupDn, ['member' => $members]);
1065
        } catch (Exception $e) {
1066
            throw new ValidationException('LDAP group membership add failure: ' . $e->getMessage());
1067
        }
1068
    }
1069
1070
    /**
1071
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
1072
     * password in the `unicodePwd` attribute.
1073
     *
1074
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
1075
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
1076
     *
1077
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
1078
     *
1079
     * @param Member $member
1080
     * @param string $password
1081
     * @param string|null $oldPassword Supply old password to perform a password change (as opposed to password reset)
1082
     * @return ValidationResult
1083
     */
1084
    public function setPassword(Member $member, $password, $oldPassword = null)
1085
    {
1086
        $validationResult = ValidationResult::create();
1087
1088
        $this->extend('onBeforeSetPassword', $member, $password, $validationResult);
1089
1090
        if (!$member->GUID) {
1091
            $this->getLogger()->debug(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
1092
            $validationResult->addError(
1093
                _t(
1094
                    'SilverStripe\\LDAP\\Authenticators\\LDAPAuthenticator.NOUSER',
1095
                    'Your account hasn\'t been setup properly, please contact an administrator.'
1096
                )
1097
            );
1098
            return $validationResult;
1099
        }
1100
1101
        $userData = $this->getUserByGUID($member->GUID);
1102
        if (empty($userData['distinguishedname'])) {
1103
            $validationResult->addError(
1104
                _t(
1105
                    'SilverStripe\\LDAP\\Authenticators\\LDAPAuthenticator.NOUSER',
1106
                    'Your account hasn\'t been setup properly, please contact an administrator.'
1107
                )
1108
            );
1109
            return $validationResult;
1110
        }
1111
1112
        try {
1113
            if (!empty($oldPassword)) {
1114
                $this->gateway->changePassword($userData['distinguishedname'], $password, $oldPassword);
1115
            } elseif ($this->config()->password_history_workaround) {
1116
                $this->passwordHistoryWorkaround($userData['distinguishedname'], $password);
1117
            } else {
1118
                $this->gateway->resetPassword($userData['distinguishedname'], $password);
1119
            }
1120
            $this->extend('onAfterSetPassword', $member, $password, $validationResult);
1121
        } catch (Exception $e) {
1122
            $validationResult->addError($e->getMessage());
1123
        }
1124
1125
        return $validationResult;
1126
    }
1127
1128
    /**
1129
     * Delete an LDAP user mapped to the Member record
1130
     * @param Member $member
1131
     * @throws ValidationException
1132
     */
1133
    public function deleteLDAPMember(Member $member)
1134
    {
1135
        if (!$this->enabled()) {
1136
            return;
1137
        }
1138
        if (!$member->GUID) {
1139
            throw new ValidationException('Member missing GUID. Cannot delete LDAP user');
1140
        }
1141
        $data = $this->getUserByGUID($member->GUID);
1142
        if (empty($data['distinguishedname'])) {
1143
            throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute');
1144
        }
1145
1146
        try {
1147
            $this->delete($data['distinguishedname']);
1148
        } catch (Exception $e) {
1149
            throw new ValidationException('LDAP delete user failed: ' . $e->getMessage());
1150
        }
1151
    }
1152
1153
    /**
1154
     * A simple proxy to LDAP update operation.
1155
     *
1156
     * @param string $dn Location to add the entry at.
1157
     * @param array $attributes A simple associative array of attributes.
1158
     */
1159
    public function update($dn, array $attributes)
1160
    {
1161
        $this->gateway->update($dn, $attributes);
1162
    }
1163
1164
    /**
1165
     * A simple proxy to LDAP delete operation.
1166
     *
1167
     * @param string $dn Location of object to delete
1168
     * @param bool $recursively Recursively delete nested objects?
1169
     */
1170
    public function delete($dn, $recursively = false)
1171
    {
1172
        $this->gateway->delete($dn, $recursively);
1173
    }
1174
1175
    /**
1176
     * A simple proxy to LDAP copy/delete operation.
1177
     *
1178
     * @param string $fromDn
1179
     * @param string $toDn
1180
     * @param bool $recursively Recursively move nested objects?
1181
     */
1182
    public function move($fromDn, $toDn, $recursively = false)
1183
    {
1184
        $this->gateway->move($fromDn, $toDn, $recursively);
1185
    }
1186
1187
    /**
1188
     * A simple proxy to LDAP add operation.
1189
     *
1190
     * @param string $dn Location to add the entry at.
1191
     * @param array $attributes A simple associative array of attributes.
1192
     */
1193
    public function add($dn, array $attributes)
1194
    {
1195
        $this->gateway->add($dn, $attributes);
1196
    }
1197
1198
    /**
1199
     * @param string $dn Distinguished name of the user
1200
     * @param string $password New password.
1201
     * @throws Exception
1202
     */
1203
    private function passwordHistoryWorkaround($dn, $password)
1204
    {
1205
        $generator = new RandomGenerator();
1206
        // 'Aa1' is there to satisfy the complexity criterion.
1207
        $tempPassword = sprintf('Aa1%s', substr($generator->randomToken('sha1'), 0, 21));
1208
        $this->gateway->resetPassword($dn, $tempPassword);
1209
        $this->gateway->changePassword($dn, $password, $tempPassword);
1210
    }
1211
1212
    /**
1213
     * Get a logger
1214
     *
1215
     * @return LoggerInterface
1216
     */
1217
    public function getLogger()
1218
    {
1219
        return Injector::inst()->get(LoggerInterface::class);
1220
    }
1221
}
1222