Passed
Pull Request — master (#28)
by Tim
02:28
created

AttributeAddUsersGroups::getGroups()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 162
Code Lines 87

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 7
eloc 87
c 4
b 0
f 0
nc 8
nop 1
dl 0
loc 162
rs 7.3503

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Does a reverse membership lookup on the logged in user,
5
 * looking for groups it is a member of and adds them to
6
 * a defined attribute, in DN format.
7
 *
8
 * @package simplesamlphp/simplesamlphp-module-ldap
9
 */
10
11
declare(strict_types=1);
12
13
namespace SimpleSAML\Module\ldap\Auth\Process;
14
15
use SimpleSAML\Assert\Assert;
16
use SimpleSAML\Error;
17
use SimpleSAML\Logger;
18
use SimpleSAML\Module\ldap\Utils\Ldap as LdapUtils;
19
use SimpleSAML\Utils;
20
use Symfony\Component\Ldap\Adapter\ExtLdap\Query;
21
22
class AttributeAddUsersGroups extends BaseFilter
23
{
24
    /** @var string */
25
    protected string $searchUsername;
26
27
    /** @var string */
28
    protected string $searchPassword;
29
30
    /** @var string */
31
    protected string $product;
32
33
34
    /**
35
     * Initialize this filter.
36
     *
37
     * @param array $config Configuration information about this filter.
38
     * @param mixed $reserved For future use.
39
     */
40
    public function __construct(array $config, $reserved)
41
    {
42
        parent::__construct($config, $reserved);
43
44
        // Get filter specific config options
45
        $this->searchUsername = $this->config->getString('search.username');
46
        $this->searchPassword = $this->config->getString('search.password', null);
47
        $this->product = $this->config->getString('product', 'ActiveDirectory');
48
    }
49
50
51
    /**
52
     * LDAP search filters to be added to the base filters for this authproc-filter.
53
     * It's an array of key => value pairs that will be translated to (key=value) in the ldap query.
54
     *
55
     * @var array
56
     */
57
    protected array $additional_filters;
58
59
60
    /**
61
     * This is run when the filter is processed by SimpleSAML.
62
     * It will attempt to find the current users groups using
63
     * the best method possible for the LDAP product. The groups
64
     * are then added to the request attributes.
65
     *
66
     * @throws \SimpleSAML\Error\Exception
67
     * @param array &$state
68
     */
69
    public function process(array &$state): void
70
    {
71
        Assert::keyExists($state, 'Attributes');
72
73
        // Log the process
74
        Logger::debug(sprintf(
75
            '%s : Attempting to get the users groups...',
76
            $this->title
77
        ));
78
79
        $this->additional_filters = $this->config->getArray('additional_filters', []);
80
81
        // Reference the attributes, just to make the names shorter
82
        $attributes = &$state['Attributes'];
83
        $map = &$this->attribute_map;
84
85
        // Get the users groups from LDAP
86
        $groups = $this->getGroups($attributes);
87
88
        // If there are none, do not proceed
89
        if (empty($groups)) {
90
            return;
91
        }
92
93
        // Make the array if it is not set already
94
        if (!isset($attributes[$map['groups']])) {
95
            $attributes[$map['groups']] = [];
96
        }
97
98
        // Must be an array, else cannot merge groups
99
        if (!is_array($attributes[$map['groups']])) {
100
            throw new Error\Exception(sprintf(
101
                '%s : The group attribute [%s] is not an array of group DNs. %s',
102
                $this->title,
103
                $map['groups'],
104
                $this->varExport($attributes[$map['groups']])
105
            ));
106
        }
107
108
        // Add the users group(s)
109
        $group_attribute = &$attributes[$map['groups']];
110
        $group_attribute = array_merge($group_attribute, $groups);
111
        $group_attribute = array_unique($group_attribute);
112
113
        // All done
114
        Logger::debug(sprintf(
115
            '%s : Added users groups to the group attribute[%s]: %s',
116
            $this->title,
117
            $map['groups'],
118
            implode('; ', $groups)
119
        ));
120
    }
121
122
123
    /**
124
     * Will perform a search using the required attribute values from the user to
125
     * get their group membership, recursively.
126
     *
127
     * @throws \SimpleSAML\Error\Exception
128
     * @param array $attributes
129
     * @return array
130
     */
131
    protected function getGroups(array $attributes): array
132
    {
133
        // Log the request
134
        Logger::debug(sprintf(
135
            '%s : Checking for groups based on the best method for the LDAP product.',
136
            $this->title
137
        ));
138
139
        $ldapUtils = new LdapUtils();
140
        $ldap = $ldapUtils->bind($this->ldapServers, $this->searchUsername, $this->searchPassword);
141
142
        $options = [
143
            'scope' => $this->config->getString('search.scope', Query::SCOPE_SUB),
144
            'timeout' => $this->config->getInteger('timeout', 3),
145
        ];
146
147
        // Reference the map, just to make the name shorter
148
        $map = &$this->attribute_map;
149
150
151
        // All map-properties are guaranteed to exist and have a default value
152
        $dn_attribute = $map['dn'];
153
        $return_attribute = $map['return'];
154
155
        // Based on the directory service, search LDAP for groups
156
        // If any attributes are needed, prepare them before calling search method
157
        switch ($this->product) {
158
            case 'ActiveDirectory':
159
                $arrayUtils = new Utils\Arrays();
160
161
                // Log the AD specific search
162
                Logger::debug(sprintf(
163
                    '%s : Searching LDAP using ActiveDirectory specific method.',
164
                    $this->title
165
                ));
166
167
                // Make sure the defined DN attribute exists
168
                if (!isset($attributes[$dn_attribute])) {
169
                    Logger::warning(sprintf(
170
                        "%s : The DN attribute [%s] is not defined in the user's Attributes: %s",
171
                        $this->title,
172
                        $dn_attribute,
173
                        implode(', ', array_keys($attributes)),
174
                    ));
175
176
                    return [];
177
                }
178
179
                // Make sure the defined DN attribute has a value
180
                if (!isset($attributes[$dn_attribute][0]) || !$attributes[$dn_attribute][0]) {
181
                    Logger::warning(sprintf(
182
                        '%s : The DN attribute [%s] does not have a [0] value defined. %s',
183
                        $this->title,
184
                        $dn_attribute,
185
                        $this->varExport($attributes[$dn_attribute])
186
                    ));
187
188
                    return [];
189
                }
190
191
                // Log the search
192
                Logger::debug(sprintf(
193
                    '%s : Searching ActiveDirectory group membership.'
194
                        . ' DN: %s DN Attribute: %s Member Attribute: %s Type Attribute: %s Type Value: %s Base: %s',
195
                    $this->title,
196
                    $attributes[$dn_attribute][0],
197
                    $dn_attribute,
198
                    $map['member'],
199
                    $map['type'],
200
                    $this->type_map['group'],
201
                    implode('; ', $arrayUtils->arrayize($this->searchBase))
202
                ));
203
204
                $filter = sprintf(
205
                    "(&(%s=%s)(%s=%s))",
206
                    $map['type'],
207
                    $this->type_map['group'],
208
                    $map['member'] . ':1.2.840.113556.1.4.1941:',
209
                    $attributes[$dn_attribute][0],
210
                );
211
212
                break;
213
            case 'OpenLDAP':
214
                // Log the OpenLDAP specific search
215
                Logger::debug(sprintf(
216
                    '%s : Searching LDAP using OpenLDAP specific method.',
217
                    $this->title
218
                ));
219
220
                Logger::debug(sprintf(
221
                    '%s : Searching for groups in base [%s] with filter (%s=%s) and attributes %s',
222
                    $this->title,
223
                    implode(', ', $this->searchBase),
224
                    $map['memberof'],
225
                    $attributes[$map['username']][0],
226
                    $map['member']
227
                ));
228
229
                $filter = sprintf(
230
                    '(&(%s=%s))',
231
                    $map['memberof'],
232
                    $attributes[$map['username']][0]
233
                );
234
                break;
235
            default:
236
                // Log the generic search
237
                Logger::debug(
238
                    $this->title . 'Searching LDAP using the generic search method.'
239
                );
240
241
                Logger::debug(sprintf(
242
                    '%s : Checking DNs for groups. DNs: %s Attributes: %s, %s Group Type: %s',
243
                    $this->title,
244
                    implode('; ', $memberof),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $memberof seems to be never defined.
Loading history...
245
                    $map['memberof'],
246
                    $map['type'],
247
                    $this->type_map['group']
248
                ));
249
250
/**
251
 * @ TODO: finish generic search  method
252
 *
253
 *               // Search for the users group membership, recursively
254
 *               $groups = $this->search($attributes[$map['memberof']]);
255
 */
256
        }
257
258
        $entries = $ldapUtils->searchForMultiple(
259
            $ldap,
260
            $this->searchBase,
261
            $filter,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $filter does not seem to be defined for all execution paths leading up to this point.
Loading history...
262
            $options,
263
            true
264
        );
265
266
        $groups = [];
267
        foreach ($entries as $entry) {
268
/**
269
            $tmp = array_intersect_key(
270
                $entry->getAttributes(),
271
                array_fill_keys(array_values($this->searchAttributes), null)
272
            );
273
274
            $binaries = array_intersect(
275
                array_keys($tmp),
276
                $this->binaryAttributes,
277
            );
278
            foreach ($binaries as $binary) {
279
                $tmp[$binary] = array_map('base64_encode', $entry->getAttribute($binary));
280
            }
281
*/
282
            $groups[] = array_pop($entry->getAttribute($return_attribute));
0 ignored issues
show
Bug introduced by
$entry->getAttribute($return_attribute) cannot be passed to array_pop() as the parameter $array expects a reference. ( Ignorable by Annotation )

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

282
            $groups[] = array_pop(/** @scrutinizer ignore-type */ $entry->getAttribute($return_attribute));
Loading history...
283
        }
284
285
Logger::debug("TMP:  " . var_export($groups));
0 ignored issues
show
Bug introduced by
Are you sure the usage of var_export($groups) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
286
287
        // All done
288
        Logger::debug(
289
            $this->title . 'User found to be a member of the groups:' . implode('; ', $groups)
290
        );
291
292
        return $groups;
293
    }
294
295
296
    /**
297
     * OpenLDAP optimized search
298
     * using the required attribute values from the user to
299
     * get their group membership, recursively.
300
     *
301
     * @throws \SimpleSAML\Error\Exception
302
     * @param array $attributes
303
     * @return array
304
    protected function getGroupsOpenLdap(array $attributes): array
305
    {
306
        $groups = [];
307
        try {
308
            // Intention is to filter in 'ou=groups,dc=example,dc=com' for
309
            // '(memberUid = <value of attribute.username>)' and take only the attributes 'cn' (=name of the group)
310
            //
311
            $all_groups = $ldapUtils->searchForMultiple(
312
                $openldap_base,
313
                array_merge(
314
                    [
315
                        $map['memberof'] => $attributes[$map['username']][0]
316
                    ],
317
                    $this->additional_filters
318
                ),
319
                [$map['return']]
320
            );
321
        } catch (Error\UserNotFound $e) {
322
            return $groups; // if no groups found return with empty (still just initialized) groups array
323
        }
324
325
        // run through all groups and add each to our groups array
326
        foreach ($all_groups as $group_entry) {
327
            $groups[] = $group_entry[$map['return']][0];
328
        }
329
330
        return $groups;
331
    }
332
     */
333
334
335
    /**
336
     * Active Directory optimized search
337
     * using the required attribute values from the user to
338
     * get their group membership, recursively.
339
     *
340
     * @throws \SimpleSAML\Error\Exception
341
     * @param array $attributes
342
     * @return array
343
     */
344
    protected function getGroupsActiveDirectory(array $attributes): array
345
    {
346
        // Reference the map, just to make the name shorter
347
        //$map = &$this->attribute_map;
348
/**
349
        // Make sure the defined dn attribute exists
350
        if (!isset($attributes[$map['dn']])) {
351
            throw new Error\Exception(
352
                $this->title . 'The DN attribute [' . $map['dn'] .
353
                '] is not defined in the user\'s Attributes: ' . implode(', ', array_keys($attributes))
354
            );
355
        }
356
357
        // DN attribute must have a value
358
        if (!isset($attributes[$map['dn']][0]) || !$attributes[$map['dn']][0]) {
359
            throw new Error\Exception(
360
                $this->title . 'The DN attribute [' . $map['dn'] .
361
                '] does not have a [0] value defined. ' . $this->varExport($attributes[$map['dn']])
362
            );
363
        }
364
*/
365
        // Pass to the AD specific search
366
        return $this->searchActiveDirectory($attributes[$map['dn']][0]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $map seems to be never defined.
Loading history...
367
    }
368
369
370
    /**
371
     * Looks for groups from the list of DN's passed. Also
372
     * recursively searches groups for further membership.
373
     * Avoids loops by only searching a DN once. Returns
374
     * the list of groups found.
375
     *
376
     * @param array $memberof
377
     * @return array
378
     */
379
    protected function search(array $memberof): array
380
    {
381
        // Used to determine what DN's have already been searched
382
        static $searched = [];
383
384
        // Init the groups variable
385
        $groups = [];
386
387
        // Shorten the variable name
388
        //$map = &$this->attribute_map;
389
390
        // Log the search
391
/**
392
        Logger::debug(
393
            $this->title . 'Checking DNs for groups.' .
394
            ' DNs: ' . implode('; ', $memberof) .
395
            ' Attributes: ' . $map['memberof'] . ', ' . $map['type'] .
396
            ' Group Type: ' . $this->type_map['group']
397
        );
398
*/
399
        // Work out what attributes to get for a group
400
        $use_group_name = false;
401
        $get_attributes = [$map['memberof'], $map['type']];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $map seems to be never defined.
Loading history...
402
        if (isset($map['name']) && $map['name']) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $map seems to never exist and therefore isset should always be false.
Loading history...
403
            $get_attributes[] = $map['name'];
404
            $use_group_name = true;
405
        }
406
407
        // Check each DN of the passed memberOf
408
        foreach ($memberof as $dn) {
409
            // Avoid infinite loops, only need to check a DN once
410
            if (isset($searched[$dn])) {
411
                continue;
412
            }
413
414
            // Track all DN's that are searched
415
            // Use DN for key as well, isset() is faster than in_array()
416
            $searched[$dn] = $dn;
417
418
            // Query LDAP for the attribute values for the DN
419
            try {
420
                $attributes = $this->getLdap()->getAttributes($dn, $get_attributes);
0 ignored issues
show
Bug introduced by
The method getLdap() does not exist on SimpleSAML\Module\ldap\A...AttributeAddUsersGroups. ( Ignorable by Annotation )

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

420
                $attributes = $this->/** @scrutinizer ignore-call */ getLdap()->getAttributes($dn, $get_attributes);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
421
            } catch (Error\AuthSource $e) {
422
                continue; // DN must not exist, just continue. Logged by the LDAP object
423
            }
424
425
            // Only look for groups
426
            if (!in_array($this->type_map['group'], $attributes[$map['type']], true)) {
427
                continue;
428
            }
429
430
            // Add to found groups array
431
            if ($use_group_name && isset($attributes[$map['name']]) && is_array($attributes[$map['name']])) {
432
                $groups[] = $attributes[$map['name']][0];
433
            } else {
434
                $groups[] = $dn;
435
            }
436
437
            // Recursively search "sub" groups
438
            if (!empty($attributes[$map['memberof']])) {
439
                $groups = array_merge($groups, $this->search($attributes[$map['memberof']]));
440
            }
441
        }
442
443
        // Return only the unique group names
444
        return array_unique($groups);
445
    }
446
447
448
    /**
449
     * Searches LDAP using a ActiveDirectory specific filter,
450
     * looking for group membership for the users DN. Returns
451
     * the list of group DNs retrieved.
452
     *
453
     * @param string $dn
454
     * @return array
455
     */
456
    protected function searchActiveDirectory(string $dn): array
457
    {
458
//        $arrayUtils = new Utils\Arrays();
459
460
//        // Shorten the variable name
461
        //$map = &$this->attribute_map;
462
463
        // Log the search
464
/*
465
        Logger::debug(
466
            $this->title . 'Searching ActiveDirectory group membership.' .
467
            ' DN: ' . $dn .
468
            ' DN Attribute: ' . $map['dn'] .
469
            ' Return Attribute: ' . $map['return'] .
470
            ' Member Attribute: ' . $map['member'] .
471
            ' Type Attribute: ' . $map['type'] .
472
            ' Type Value: ' . $this->type_map['group'] .
473
            ' Base: ' . implode('; ', $arrayUtils->arrayize($this->base_dn))
474
        );
475
*/
476
477
        // AD connections should have this set
478
        //$this->getLdap()->setOption(LDAP_OPT_REFERRALS, 0);
479
480
        // Search AD with the specific recursive flag
481
/**
482
        try {
483
            $entries = $this->getLdap()->searchformultiple(
484
                $this->base_dn,
485
                array_merge(
486
                    [
487
                        $map['type'] => $this->type_map['group'],
488
                        $map['member'] . ':1.2.840.113556.1.4.1941:' => $dn
489
                    ],
490
                    $this->additional_filters
491
                ),
492
                [$map['return']]
493
            );
494
495
        // The search may throw an exception if no entries
496
        // are found, unlikely but possible.
497
        } catch (Error\UserNotFound $e) {
498
            return [];
499
        }
500
*/
501
        //Init the groups
502
        $groups = [];
503
504
        // Check each entry..
505
        foreach ($entries as $entry) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $entries seems to be never defined.
Loading history...
506
            // Check for the DN using the original attribute name
507
            if (isset($entry[$map['return']][0])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $map seems to be never defined.
Loading history...
508
                $groups[] = $entry[$map['return']][0];
509
                continue;
510
            }
511
512
            // Sometimes the returned attribute names are lowercase
513
            if (isset($entry[strtolower($map['return'])][0])) {
514
                $groups[] = $entry[strtolower($map['return'])][0];
515
                continue;
516
            }
517
518
            // AD queries also seem to return the objects dn by default
519
            if (isset($entry['return'])) {
520
                $groups[] = $entry['return'];
521
                continue;
522
            }
523
524
            // Could not find DN, log and continue
525
            Logger::notice(
526
                $this->title . 'The return attribute [' .
527
                implode(', ', [$map['return'], strtolower($map['return'])]) .
528
                '] could not be found in the entry. ' . $this->varExport($entry)
529
            );
530
        }
531
532
        // All done
533
        return $groups;
534
    }
535
}
536